blob: 9850fdecf355ccd6d6abb32936628631e23a77f1 [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;
Paul Jensen53f08952015-06-16 14:27:36 -040068import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
75import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090077import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090079import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080080import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
81import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080082import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090083import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090084import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080085import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
86import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080087import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
88import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
89import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090090import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090091import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060092import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070093import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080094import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090095import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070096import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
97import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070098import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080099import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100100import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700101import static android.system.OsConstants.IPPROTO_TCP;
102import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900103
Junyu Lai155760b2023-10-05 14:51:00 +0800104import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
105import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
106import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
107import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
108import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Xiao Ma60142372022-07-16 17:30:20 +0900109import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800110import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800111import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
112import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
113import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900114import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900115
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800116import static java.util.Map.Entry;
117
Chalard Jean5b639762020-03-09 21:25:37 +0900118import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000119import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800120import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600121import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800122import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000123import android.app.ActivityManager;
124import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800125import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800126import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700127import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700128import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900129import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800130import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700131import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800132import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800133import android.content.ContentResolver;
134import android.content.Context;
135import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700136import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800137import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900138import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700139import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800140import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900141import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900142import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700143import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800144import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800145import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800146import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900147import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800148import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900149import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800150import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900151import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800152import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700153import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900154import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800155import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800157import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800158import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800159import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900160import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900161import android.net.INetworkMonitor;
162import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900163import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900164import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700165import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800166import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900167import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900168import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900169import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800170import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900171import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900172import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100173import android.net.MatchAllNetworkSpecifier;
Yang Sun29037f62023-12-04 10:31:58 +0800174import android.net.MulticastRoutingConfig;
Ken Chen6df7a902021-04-09 15:08:42 +0800175import android.net.NativeNetworkConfig;
176import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800177import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700178import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700179import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900180import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700181import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800182import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700183import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900184import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900185import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000186import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900187import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700188import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900189import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700190import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900191import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700192import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800193import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900194import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700195import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000196import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800197import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900198import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800199import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400200import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700201import android.net.QosCallbackException;
202import android.net.QosFilter;
203import android.net.QosSocketFilter;
204import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700205import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800206import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800207import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900208import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400209import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800210import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800211import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400212import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800213import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900214import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900215import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900216import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900217import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800218import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900219import android.net.networkstack.ModuleNetworkStackClient;
220import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900221import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800222import android.net.resolv.aidl.DnsHealthEventParcel;
223import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
224import android.net.resolv.aidl.Nat64PrefixEventParcel;
225import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900226import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900227import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800228import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800230import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700231import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000232import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800233import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700234import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700235import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800236import android.os.Looper;
237import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700238import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700239import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900240import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800241import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700242import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700243import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800244import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700245import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900246import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900247import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700248import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700249import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400250import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800251import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900252import android.stats.connectivity.MeteredState;
253import android.stats.connectivity.RequestType;
254import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900255import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700256import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700257import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700258import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800259import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900260import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000261import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600262import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900263import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900264import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700265import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700266import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900267import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800268
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800269import androidx.annotation.RequiresApi;
270
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900271import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400272import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400273import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700274import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900275import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900276import com.android.metrics.ConnectionDurationForTransports;
277import com.android.metrics.ConnectionDurationPerTransports;
278import com.android.metrics.ConnectivitySampleMetricsHelper;
279import com.android.metrics.ConnectivityStateSample;
280import com.android.metrics.NetworkCountForTransports;
281import com.android.metrics.NetworkCountPerTransports;
282import com.android.metrics.NetworkDescription;
283import com.android.metrics.NetworkList;
284import com.android.metrics.NetworkRequestCount;
285import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800286import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900287import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800288import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000289import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900290import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800291import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900292import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900293import com.android.net.module.util.DeviceConfigUtils;
Junyu Lai2ff42d22023-12-07 16:57:13 +0800294import com.android.net.module.util.HandlerUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100295import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900296import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
297import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900298import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800299import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800300import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100301import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000302import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800303import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
304import com.android.networkstack.apishim.ConstantsShim;
305import com.android.networkstack.apishim.common.BroadcastOptionsShim;
306import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900307import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900308import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000309import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900310import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800311import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800312import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900313import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900314import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900315import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500316import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700317import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900318import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900319import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900320import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000321import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100322import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700323import com.android.server.connectivity.MockableSystemProperties;
Yang Sun29037f62023-12-04 10:31:58 +0800324import com.android.server.connectivity.MulticastRoutingCoordinatorService;
Chalard Jean43aae652022-09-14 21:33:06 +0900325import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700326import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600327import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900328import com.android.server.connectivity.NetworkNotificationManager;
329import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900330import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900331import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900332import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700333import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900334import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900335import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700336import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900337import com.android.server.connectivity.RoutingCoordinatorService;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800338import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000339import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800340import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600341
Josh Gao461a1222020-06-16 15:58:11 -0700342import libcore.io.IoUtils;
343
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900344import org.xmlpull.v1.XmlPullParserException;
345
The Android Open Source Project28527d22009-03-03 19:31:44 -0800346import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100347import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900348import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800349import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900350import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700351import java.net.Inet4Address;
Yang Sun29037f62023-12-04 10:31:58 +0800352import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700353import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900354import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900355import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700356import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700357import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700358import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700359import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800360import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900361import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800362import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700363import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700364import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700365import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700366import java.util.Map;
Yang Sun29037f62023-12-04 10:31:58 +0800367import java.util.Map.Entry;
Chalard Jean524f0b12021-10-25 21:11:56 +0900368import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700369import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900370import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600371import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900372import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600373import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900374import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900375import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800376
377/**
378 * @hide
379 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800380public class ConnectivityService extends IConnectivityManager.Stub
381 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900382 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800383
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900384 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900385 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900386 private static final String NETWORK_ARG = "networks";
387 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800388 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900389
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900390 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900391 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
392 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800393
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900394 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700395
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100396 /**
397 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
398 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800399 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100400 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
401 * (preferably via runtime resource overlays).
402 */
403 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
404 "http://connectivitycheck.gstatic.com/generate_204";
405
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700406 // TODO: create better separation between radio types and network types
407
Robert Greenwalt2034b912009-08-12 16:08:25 -0700408 // how long to wait before switching back to a radio's default network
409 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
410 // system property that can override the above value
411 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
412 "android.telephony.apn-restore";
413
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900414 // How long to wait before putting up a "This network doesn't have an Internet connection,
415 // connect anyway?" dialog after the user selects a network that doesn't validate.
416 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
417
Chalard Jean5fb43c72022-09-08 19:03:14 +0900418 // How long to wait before considering that a network is bad in the absence of any form
419 // of connectivity (valid, partial, captive portal). If none has been detected after this
420 // delay, the stack considers this network bad, which may affect how it's handled in ranking
421 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900422 // Timeout in case the "actively prefer bad wifi" feature is on
423 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
424 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900425 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900426
junyulai0ac374f2020-12-14 18:41:52 +0800427 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900428 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
429 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800430 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700431
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800432 // Delimiter used when creating the broadcast delivery group for sending
433 // CONNECTIVITY_ACTION broadcast.
434 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
435
he_won.hwang881307a2022-03-15 21:23:52 +0900436 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900437 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900438
Daniel Brightf9e945b2020-06-15 16:10:01 -0700439 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900440 @VisibleForTesting
441 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700442
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900443 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700444 @VisibleForTesting
445 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900446
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900447 @VisibleForTesting
448 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800449 @VisibleForTesting
450 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900451 // True if the cell radio of the device is capable of time-sharing.
452 @VisibleForTesting
453 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900454
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800455 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800456 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800457 private final int mReleasePendingIntentDelayMs;
458
Chalard Jean46bfbf02022-02-02 00:56:25 +0900459 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900460
Motomu Utsumif360aa62023-01-30 17:52:20 +0900461 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700462
Chalard Jean9473c982021-07-29 20:03:04 +0900463 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800464 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700465 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800466 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700467
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900468 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700469
junyulaif2c67e42018-08-07 19:50:45 +0800470 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000471 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
472 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800473 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900474 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800475
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900476 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900477 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000478 private final int mWakeUpMark;
479 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000480 // The Context is created for UserHandle.ALL.
481 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900482 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900483 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700484 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700485 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800486
Chenbo Feng15416292018-11-08 17:36:21 -0800487 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800488 protected IDnsResolver mDnsResolver;
489 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800490 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700491 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900492 private final NetworkStatsManager mStatsManager;
493 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800494 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700495
Benedict Wong493e04b2018-11-09 14:45:34 -0800496 /**
497 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
498 * instances.
499 */
500 @GuardedBy("mTNSLock")
501 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800502 private final CompanionDeviceManagerProxyService mCdmps;
Yang Sun29037f62023-12-04 10:31:58 +0800503 private final MulticastRoutingCoordinatorService mMulticastRoutingCoordinatorService;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900504 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800505
506 private final Object mTNSLock = new Object();
507
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700508 private String mCurrentTcpBufferSizes;
509
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900510 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000511 new Class[] {
512 ConnectivityService.class,
513 NetworkAgent.class,
514 NetworkAgentInfo.class,
515 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900516
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500517 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400518 // Tear down networks that have no chance (e.g. even if validated) of becoming
519 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500520 // all networks have been rematched against all NetworkRequests.
521 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400522 // Don't reap networks. This should be passed when some networks have not yet been
523 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500524 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900525 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500526
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900527 private enum UnneededFor {
528 LINGER, // Determine whether this network is unneeded and should be lingered.
529 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
530 }
531
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700532 /**
paulhuaa0743d2021-05-26 21:56:03 +0800533 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800534 * should have priority. The order is passed to netd which will use it together
535 * with UID ranges to generate the corresponding IP rule. This serves to
536 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800537 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800538 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000539 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800540 *
paulhu48291862021-07-14 14:53:57 +0800541 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
542 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800543 */
paulhu48291862021-07-14 14:53:57 +0800544 // Used when sending to netd to code for "no order".
545 static final int PREFERENCE_ORDER_NONE = 0;
546 // Order for requests that don't code for a per-app preference. As it is
547 // out of the valid range, the corresponding order should be
548 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800549 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800550 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800551 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800552 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
553 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800554 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800555 static final int PREFERENCE_ORDER_OEM = 10;
556 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800557 // See {@link #setProfileNetworkPreference}.
558 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800559 static final int PREFERENCE_ORDER_PROFILE = 20;
560 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800561 // better scores are connected.
562 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800563 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800564 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900565 // Preference order that signifies the network shouldn't be set as a default network for
566 // the UIDs, only give them access to it. TODO : replace this with a boolean
567 // in NativeUidRangeConfig
568 @VisibleForTesting
569 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
570 // Bound for the lowest valid preference order.
571 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800572
573 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700574 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700575 * from one net to another. Clear happens when we get a new
576 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
577 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700578 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700579 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700580
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700581 /**
582 * used internally to reload global proxy settings
583 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700584 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700585
Robert Greenwalt34848c02011-03-25 13:09:25 -0700586 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400587 * PAC manager has received new port.
588 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800589 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400590
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700591 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900592 * used internally when registering NetworkProviders
593 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700594 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900595 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700596
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700597 /**
598 * used internally when registering NetworkAgents
599 * obj = Messenger
600 */
601 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
602
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700603 /**
604 * used to add a network request
605 * includes a NetworkRequestInfo
606 */
607 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
608
609 /**
610 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900611 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700612 * cancel it.
613 * includes a NetworkRequestInfo
614 */
615 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
616
617 /**
618 * used to add a network listener - no request
619 * includes a NetworkRequestInfo
620 */
621 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
622
623 /**
624 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400625 * arg1 = UID of caller
626 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700627 */
628 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
629
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700630 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900631 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700632 * obj = Messenger
633 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900634 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700635
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700636 /**
637 * used internally to expire a wakelock when transitioning
638 * from one net to another. Expire happens when we fail to find
639 * a new network (typically after 1 minute) -
640 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
641 * a replacement network.
642 */
643 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
644
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700645 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800646 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400647 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800648 */
649 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
650
651 /**
652 * used to remove a pending intent and its associated network request.
653 * arg1 = UID of caller
654 * obj = PendingIntent
655 */
656 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
657
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900658 /**
659 * used to specify whether a network should be used even if unvalidated.
660 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
661 * arg2 = whether to remember this choice in the future (1 or 0)
662 * obj = network
663 */
664 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
665
666 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700667 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900668 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700669 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900670
Paul Jensenc8873fc2015-06-17 14:15:39 -0400671 /**
672 * used to add a network listener with a pending intent
673 * obj = NetworkRequestInfo
674 */
675 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
676
Hugo Benichid6b510a2017-04-06 17:22:18 +0900677 /**
678 * used to specify whether a network should not be penalized when it becomes unvalidated.
679 */
680 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
681
682 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700683 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900684 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700685 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900686
Erik Kline31b4a9e2018-01-11 21:07:29 +0900687 // Handle changes in Private DNS settings.
688 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
689
dalyk1720e542018-03-05 12:42:22 -0500690 // Handle private DNS validation status updates.
691 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
692
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900693 /**
694 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
695 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800696 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
697 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
698 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900699 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900700 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900701
702 /**
703 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
704 * config was resolved.
705 * obj = PrivateDnsConfig
706 * arg2 = netid
707 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900708 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900709
710 /**
711 * Request ConnectivityService display provisioning notification.
712 * arg1 = Whether to make the notification visible.
713 * arg2 = NetID.
714 * obj = Intent to be launched when notification selected by user, null if !arg1.
715 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900716 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900717
718 /**
lucaslin2240ef62019-03-12 13:08:03 +0800719 * Used to specify whether a network should be used even if connectivity is partial.
720 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
721 * false)
722 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
723 * obj = network
724 */
lucaslin444d43a2020-02-20 16:56:59 +0800725 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800726
727 /**
lucasline117e2e2019-10-22 18:27:33 +0800728 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
729 * Both of the arguments are bitmasks, and the value of bits come from
730 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900731 * arg1 = unused
732 * arg2 = netId
733 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800734 */
lucaslin444d43a2020-02-20 16:56:59 +0800735 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800736
737 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900738 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
739 * arg1 = unused
740 * arg2 = netId
741 * obj = captive portal data
742 */
lucaslin444d43a2020-02-20 16:56:59 +0800743 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900744
745 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900746 * Used by setRequireVpnForUids.
747 * arg1 = whether the specified UID ranges are required to use a VPN.
748 * obj = Array of UidRange objects.
749 */
750 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
751
752 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900753 * Used internally when setting the default networks for OemNetworkPreferences.
754 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800755 */
756 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
757
758 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800759 * Used to indicate the system default network becomes active.
760 */
761 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
762
763 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900764 * Used internally when setting a network preference for a user profile.
765 * obj = Pair<ProfileNetworkPreference, Listener>
766 */
767 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
768
769 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000770 * Event to specify that reasons for why an uid is blocked changed.
771 * arg1 = uid
772 * arg2 = blockedReasons
773 */
774 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
775
776 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900777 * Event to register a new network offer
778 * obj = NetworkOffer
779 */
780 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
781
782 /**
783 * Event to unregister an existing network offer
784 * obj = INetworkOfferCallback
785 */
786 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
787
788 /**
paulhu51f77dc2021-06-07 02:34:20 +0000789 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
790 */
791 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
792
793 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800794 * Event to set temporary allow bad wifi within a limited time to override
795 * {@code config_networkAvoidBadWifi}.
796 */
797 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
798
799 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100800 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
801 */
802 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
803
804 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900805 * The initial evaluation period is over for this network.
806 *
807 * If no form of connectivity has been found on this network (valid, partial, captive portal)
808 * then the stack will now consider it to have been determined bad.
809 */
810 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
811
812 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000813 * Used internally when the user does not want the network from captive portal app.
814 * obj = Network
815 */
816 private static final int EVENT_USER_DOES_NOT_WANT = 58;
817
818 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000819 * Event to set VPN as preferred network for specific apps.
820 * obj = VpnNetworkPreferenceInfo
821 */
822 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
823
824 /**
chiachangwange0192a72023-02-06 13:25:01 +0000825 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
826 */
827 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
828
829 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000830 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
831 */
832 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
833
834 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900835 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
836 * should be shown.
837 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900838 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900839
840 /**
841 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
842 * should be hidden.
843 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900844 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900845
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800846 /**
847 * The maximum alive time to allow bad wifi configuration for testing.
848 */
849 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
850
Patrick Rohr2857ac42022-01-21 14:58:16 +0100851 /**
chiachangwange0192a72023-02-06 13:25:01 +0000852 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
853 * testing.
854 */
855 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
856
857 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100858 * The priority of the tc police rate limiter -- smaller value is higher priority.
859 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
860 */
861 private static final short TC_PRIO_POLICE = 1;
862
863 /**
864 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
865 */
866 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700867 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100868
Hugo Benichi47011212017-03-30 10:46:05 +0900869 private static String eventName(int what) {
870 return sMagicDecoderRing.get(what, Integer.toString(what));
871 }
872
paulhua10d8212020-11-10 15:32:56 +0800873 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900874 final DnsResolverServiceManager dsm = context.getSystemService(
875 DnsResolverServiceManager.class);
876 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800877 }
878
Cody Kesting73708bf2019-12-18 10:57:50 -0800879 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900880 @VisibleForTesting
881 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700882 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700883 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700884 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700885 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800886 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
887 @VisibleForTesting
888 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
889
Erik Kline32120082017-12-13 19:40:49 +0900890 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900891 @VisibleForTesting
892 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700893
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400894 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800895 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400896
Chalard Jean46bfbf02022-02-02 00:56:25 +0900897 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800898 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700899
Chalard Jean5d70ba42018-06-07 16:44:04 +0900900 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
901 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800902 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400903
Erik Kline05f2b402015-04-30 12:58:40 +0900904 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700905
Chalard Jean46bfbf02022-02-02 00:56:25 +0900906 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400907
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700908 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900909 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700910
Valentin Iftime9fa35092019-09-24 13:32:13 +0200911 private Set<String> mWolSupportedInterfaces;
912
Roshan Pius08c94fb2020-01-16 12:17:17 -0800913 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800914 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800915 private final AppOpsManager mAppOpsManager;
916
917 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400918
chiachangwang3d60bac2023-01-17 14:38:08 +0000919 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900920 private final QosCallbackTracker mQosCallbackTracker;
921 private final NetworkNotificationManager mNotifier;
922 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900923
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700924 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800925 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700926
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900927 // Sequence number for NetworkProvider IDs.
928 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
929 NetworkProvider.FIRST_PROVIDER_ID);
930
Erik Klineedf878b2015-07-09 18:24:03 +0900931 // NetworkRequest activity String log entries.
932 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
933 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
934
Hugo Benichid159fdd2016-07-11 11:05:12 +0900935 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900936 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900937 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
938
Hugo Benichi47011212017-03-30 10:46:05 +0900939 private static final int MAX_WAKELOCK_LOGS = 20;
940 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900941 private int mTotalWakelockAcquisitions = 0;
942 private int mTotalWakelockReleases = 0;
943 private long mTotalWakelockDurationMs = 0;
944 private long mMaxWakelockDurationMs = 0;
945 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900946
Hugo Benichi208c0102016-07-28 17:53:06 +0900947 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900948
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700949 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900950 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700951
Erik Kline95ecfee2016-10-02 18:02:14 +0900952 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900953 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900954
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900955 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800956 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
957 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800958
Patrick Rohr2857ac42022-01-21 14:58:16 +0100959 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
960 // configured via {@link
961 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
962 // Only the handler thread is allowed to access this field.
963 private long mIngressRateLimit = -1;
964
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900965 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
966 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900967 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900968 @GuardedBy("mSelfCertifiedCapabilityCache")
969 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
970 mSelfCertifiedCapabilityCache = new HashMap<>();
971
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900972 // Flag to enable the feature of closing frozen app sockets.
973 private final boolean mDestroyFrozenSockets;
974
975 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
976 private final boolean mDelayDestroyFrozenSockets;
977
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900978 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
979 private final boolean mAllowSysUiConnectivityReports;
980
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900981 // Uids that ConnectivityService is pending to close sockets of.
982 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
983
Robert Greenwalt802c1102014-06-02 15:32:02 -0700984 /**
985 * Implements support for the legacy "one network per network type" model.
986 *
987 * We used to have a static array of NetworkStateTrackers, one for each
988 * network type, but that doesn't work any more now that we can have,
989 * for example, more that one wifi network. This class stores all the
990 * NetworkAgentInfo objects that support a given type, but the legacy
991 * API will only see the first one.
992 *
993 * It serves two main purposes:
994 *
995 * 1. Provide information about "the network for a given type" (since this
996 * API only supports one).
997 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
998 * the first network for a given type changes, or if the default network
999 * changes.
1000 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001001 @VisibleForTesting
1002 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001003
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09001004 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001005 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001006
Robert Greenwalt802c1102014-06-02 15:32:02 -07001007 /**
1008 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1009 * Each list holds references to all NetworkAgentInfos that are used to
1010 * satisfy requests for that network type.
1011 *
1012 * This array is built out at startup such that an unsupported network
1013 * doesn't get an ArrayList instance, making this a tristate:
1014 * unsupported, supported but not active and active.
1015 *
1016 * The actual lists are populated when we scan the network types that
1017 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001018 *
1019 * Threading model:
1020 * - addSupportedType() is only called in the constructor
1021 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1022 * They are therefore not thread-safe with respect to each other.
1023 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1024 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001025 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001026 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001027 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001028 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001029 @NonNull
1030 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001031
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001032 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1033 // an entry have no timer (equivalent to -1). Lazily loaded.
1034 @NonNull
1035 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1036
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001037 LegacyTypeTracker(@NonNull ConnectivityService service) {
1038 mService = service;
1039 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001040 }
1041
Chiachang Wang3bc52762021-11-25 14:17:57 +08001042 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1043 // addressed.
1044 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001045 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1046 final PackageManager pm = ctx.getPackageManager();
1047 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1048 addSupportedType(TYPE_WIFI);
1049 }
1050 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1051 addSupportedType(TYPE_WIFI_P2P);
1052 }
1053 if (tm.isDataCapable()) {
1054 // Telephony does not have granular support for these types: they are either all
1055 // supported, or none is supported
1056 addSupportedType(TYPE_MOBILE);
1057 addSupportedType(TYPE_MOBILE_MMS);
1058 addSupportedType(TYPE_MOBILE_SUPL);
1059 addSupportedType(TYPE_MOBILE_DUN);
1060 addSupportedType(TYPE_MOBILE_HIPRI);
1061 addSupportedType(TYPE_MOBILE_FOTA);
1062 addSupportedType(TYPE_MOBILE_IMS);
1063 addSupportedType(TYPE_MOBILE_CBS);
1064 addSupportedType(TYPE_MOBILE_IA);
1065 addSupportedType(TYPE_MOBILE_EMERGENCY);
1066 }
1067 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1068 addSupportedType(TYPE_BLUETOOTH);
1069 }
1070 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1071 // TYPE_PROXY is only used on Wear
1072 addSupportedType(TYPE_PROXY);
1073 }
1074 // Ethernet is often not specified in the configs, although many devices can use it via
1075 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001076 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001077 addSupportedType(TYPE_ETHERNET);
1078 }
1079
1080 // Always add TYPE_VPN as a supported type
1081 addSupportedType(TYPE_VPN);
1082 }
1083
1084 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001085 if (mTypeLists[type] != null) {
1086 throw new IllegalStateException(
1087 "legacy list for type " + type + "already initialized");
1088 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001089 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001090 }
1091
Robert Greenwalt802c1102014-06-02 15:32:02 -07001092 public boolean isTypeSupported(int type) {
1093 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1094 }
1095
1096 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001097 synchronized (mTypeLists) {
1098 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1099 return mTypeLists[type].get(0);
1100 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001101 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001102 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001103 }
1104
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001105 public int getRestoreTimerForType(int type) {
1106 synchronized (mTypeLists) {
1107 if (mRestoreTimers == null) {
1108 mRestoreTimers = loadRestoreTimers();
1109 }
1110 return mRestoreTimers.getOrDefault(type, -1);
1111 }
1112 }
1113
1114 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1115 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001116 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001117 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1118 for (final String config : configs) {
1119 final String[] splits = TextUtils.split(config, ",");
1120 if (splits.length != 2) {
1121 logwtf("Invalid restore timer token count: " + config);
1122 continue;
1123 }
1124 try {
1125 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1126 } catch (NumberFormatException e) {
1127 logwtf("Invalid restore timer number format: " + config, e);
1128 }
1129 }
1130 return ret;
1131 }
1132
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001133 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001134 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001135 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001136 log("Sending " + state
1137 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001138 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001139 }
1140 }
1141
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001142 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1143 // network type, to preserve previous behaviour.
1144 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1145 if (vpnNai != mService.getLegacyLockdownNai()) return;
1146
1147 if (vpnNai.declaredUnderlyingNetworks == null
1148 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1149 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1150 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1151 return;
1152 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001153 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001154 vpnNai.declaredUnderlyingNetworks[0]);
1155 if (underlyingNai == null) return;
1156
1157 final int type = underlyingNai.networkInfo.getType();
1158 final DetailedState state = DetailedState.CONNECTED;
1159 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1160 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1161 }
1162
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001163 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001164 public void add(int type, NetworkAgentInfo nai) {
1165 if (!isTypeSupported(type)) {
1166 return; // Invalid network type.
1167 }
1168 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1169
1170 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1171 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001172 return;
1173 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001174 synchronized (mTypeLists) {
1175 list.add(nai);
1176 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001177
Chalard Jean5b409c72021-02-04 13:12:59 +09001178 // Send a broadcast if this is the first network of its type or if it's the default.
1179 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001180
1181 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1182 // to preserve previous behaviour.
1183 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001184 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001185 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1186 mService.sendLegacyNetworkBroadcast(nai, state, type);
1187 }
1188
1189 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1190 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001191 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001192 }
1193
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001194 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001195 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001196 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1197 if (list == null || list.isEmpty()) {
1198 return;
1199 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001200 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001201
Hugo Benichi389633f2016-06-21 09:48:07 +09001202 synchronized (mTypeLists) {
1203 if (!list.remove(nai)) {
1204 return;
1205 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001206 }
1207
Lorenzo Colitti49767722015-05-01 00:30:10 +09001208 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001209 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1210 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001211 }
1212
1213 if (!list.isEmpty() && wasFirstNetwork) {
1214 if (DBG) log("Other network available for type " + type +
1215 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001216 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001217 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001218 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001219 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001220 }
1221 }
1222
1223 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001224 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1225 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001226 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001227 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001228 }
1229 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001230
Chalard Jean46bfbf02022-02-02 00:56:25 +09001231 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001232 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001233 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001234 final DetailedState state = nai.networkInfo.getDetailedState();
1235 for (int type = 0; type < mTypeLists.length; type++) {
1236 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001237 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001238 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001239 if (isFirst || contains && isDefault) {
1240 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001241 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001242 }
1243 }
1244 }
1245
Robert Greenwalt94e22142014-07-30 16:31:24 -07001246 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001247 pw.println("mLegacyTypeTracker:");
1248 pw.increaseIndent();
1249 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001250 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001251 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001252 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001253 pw.println();
1254 pw.println("Current state:");
1255 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001256 synchronized (mTypeLists) {
1257 for (int type = 0; type < mTypeLists.length; type++) {
1258 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1259 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001260 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001261 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001262 }
1263 }
1264 pw.decreaseIndent();
1265 pw.decreaseIndent();
1266 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001267 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001268 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001269 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001270
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001271 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001272 /**
1273 * Helper class which parses out priority arguments and dumps sections according to their
1274 * priority. If priority arguments are omitted, function calls the legacy dump command.
1275 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001276 private class LocalPriorityDump {
1277 private static final String PRIORITY_ARG = "--dump-priority";
1278 private static final String PRIORITY_ARG_HIGH = "HIGH";
1279 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001280 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001281
1282 LocalPriorityDump() {}
1283
1284 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001285 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> {
Junyu Laif8dba342023-10-12 17:01:03 +08001286 doDump(fd, pw, new String[]{DIAG_ARG});
1287 doDump(fd, pw, new String[]{SHORT_ARG});
1288 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1289 pw.println("dumpHigh timeout");
1290 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001291 }
1292
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001293 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001294 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> doDump(fd, pw, args),
Junyu Laif8dba342023-10-12 17:01:03 +08001295 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1296 pw.println("dumpNormal timeout");
1297 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001298 }
1299
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001300 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1301 if (args == null) {
1302 dumpNormal(fd, pw, args);
1303 return;
1304 }
1305
1306 String priority = null;
1307 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1308 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1309 argIndex++;
1310 priority = args[argIndex];
1311 }
1312 }
1313
1314 if (PRIORITY_ARG_HIGH.equals(priority)) {
1315 dumpHigh(fd, pw);
1316 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1317 dumpNormal(fd, pw, args);
1318 } else {
1319 // ConnectivityService publishes binder service using publishBinderService() with
1320 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001321 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1322 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001323 // TODO: Integrate into signal dump.
1324 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001325 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001326 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001327 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001328
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001329 /**
1330 * Dependencies of ConnectivityService, for injection in tests.
1331 */
1332 @VisibleForTesting
1333 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001334 public int getCallingUid() {
1335 return Binder.getCallingUid();
1336 }
1337
Chalard Jeandf29a852023-05-29 17:02:43 +09001338 public boolean isAtLeastS() {
1339 return SdkLevel.isAtLeastS();
1340 }
1341
1342 public boolean isAtLeastT() {
1343 return SdkLevel.isAtLeastT();
1344 }
1345
1346 public boolean isAtLeastU() {
1347 return SdkLevel.isAtLeastU();
1348 }
1349
Chalard Jeaneb663892023-10-07 15:17:07 +09001350 public boolean isAtLeastV() {
1351 return SdkLevel.isAtLeastV();
1352 }
1353
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001354 /**
1355 * Get system properties to use in ConnectivityService.
1356 */
1357 public MockableSystemProperties getSystemProperties() {
1358 return new MockableSystemProperties();
1359 }
1360
1361 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001362 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1363 */
1364 public ConnectivityResources getResources(@NonNull Context ctx) {
1365 return new ConnectivityResources(ctx);
1366 }
1367
1368 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001369 * Create a HandlerThread to use in ConnectivityService.
1370 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001371 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1372 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001373 }
1374
1375 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001376 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001377 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001378 public NetworkStackClientBase getNetworkStack() {
1379 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001380 }
1381
1382 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001383 * @see ProxyTracker
1384 */
1385 public ProxyTracker makeProxyTracker(@NonNull Context context,
1386 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001387 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001388 }
1389
1390 /**
1391 * @see NetIdManager
1392 */
1393 public NetIdManager makeNetIdManager() {
1394 return new NetIdManager();
1395 }
1396
1397 /**
1398 * @see NetworkUtils#queryUserAccess(int, int)
1399 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001400 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1401 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001402 }
1403
1404 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001405 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1406 * requires CAP_NET_ADMIN, which the unit tests do not have.
1407 */
1408 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1409 InetSocketAddress remote) {
1410 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1411 }
1412
1413 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001414 * @see MultinetworkPolicyTracker
1415 */
1416 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1417 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1418 return new MultinetworkPolicyTracker(c, h, r);
1419 }
1420
Aaron Huang330a4c02020-10-27 03:36:19 +08001421 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001422 * @see AutomaticOnOffKeepaliveTracker
1423 */
1424 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1425 @NonNull Context c, @NonNull Handler h) {
1426 return new AutomaticOnOffKeepaliveTracker(c, h);
1427 }
1428
Yang Sun29037f62023-12-04 10:31:58 +08001429 public MulticastRoutingCoordinatorService makeMulticastRoutingCoordinatorService(
1430 @NonNull Handler h) {
1431 try {
1432 return new MulticastRoutingCoordinatorService(h);
1433 } catch (UnsupportedOperationException e) {
1434 // Multicast routing is not supported by the kernel
1435 Log.i(TAG, "Skipping unsupported MulticastRoutingCoordinatorService");
1436 return null;
1437 }
1438 }
1439
chiachangwang7c17c282023-02-02 05:58:59 +00001440 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001441 * @see BatteryStatsManager
1442 */
1443 public void reportNetworkInterfaceForTransports(Context context, String iface,
1444 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001445 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001446 context.getSystemService(BatteryStatsManager.class);
1447 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1448 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001449
1450 public boolean getCellular464XlatEnabled() {
1451 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1452 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001453
1454 /**
1455 * @see PendingIntent#intentFilterEquals
1456 */
1457 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1458 return a.intentFilterEquals(b);
1459 }
1460
1461 /**
1462 * @see LocationPermissionChecker
1463 */
1464 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1465 return new LocationPermissionChecker(context);
1466 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001467
1468 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001469 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001470 *
1471 * This method returns null in versions before T, where carrier privilege
1472 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001473 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001474 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001475 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1476 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001477 if (isAtLeastT()) {
Chalard Jean96ff9542023-11-02 14:24:47 +09001478 return new CarrierPrivilegeAuthenticator(context, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001479 } else {
1480 return null;
1481 }
1482 }
1483
1484 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001485 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001486 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001487 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001488 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001489 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001490
1491 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001492 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1493 */
1494 public boolean isFeatureNotChickenedOut(Context context, String name) {
1495 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1496 }
1497
1498 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001499 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001500 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001501 * @return BpfNetMaps implementation.
1502 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001503 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1504 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001505 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001506
1507 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001508 * @see ClatCoordinator
1509 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001510 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001511 public ClatCoordinator getClatCoordinator(INetd netd) {
1512 return new ClatCoordinator(
1513 new ClatCoordinator.Dependencies() {
1514 @NonNull
1515 public INetd getNetd() {
1516 return netd;
1517 }
1518 });
1519 }
1520
1521 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001522 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1523 */
1524 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1525 final InterfaceParams params = InterfaceParams.getByName(iface);
1526 if (params == null) {
1527 // the interface might have disappeared.
1528 logw("Failed to get interface params for interface " + iface);
1529 return;
1530 }
1531 try {
1532 // converting rateInBytesPerSecond from long to int is safe here because the
1533 // setting's range is limited to INT_MAX.
1534 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001535 Log.i(TAG,
1536 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001537 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1538 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1539 } catch (IOException e) {
1540 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1541 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1542 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1543 + ") failure: ", e);
1544 }
1545 }
1546
1547 /**
1548 * Wraps {@link TcUtils#tcFilterDelDev}
1549 */
1550 public void disableIngressRateLimit(String iface) {
1551 final InterfaceParams params = InterfaceParams.getByName(iface);
1552 if (params == null) {
1553 // the interface might have disappeared.
1554 logw("Failed to get interface params for interface " + iface);
1555 return;
1556 }
1557 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001558 Log.i(TAG,
1559 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001560 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1561 } catch (IOException e) {
1562 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1563 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1564 }
1565 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001566
1567 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001568 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1569 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001570 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001571 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001572 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001573 }
1574
1575 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001576 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1577 */
1578 // TODO: when available in all active branches:
1579 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1580 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1581 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1582 return BroadcastOptionsShimImpl.newInstance(options);
1583 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001584
1585 /**
1586 * Wrapper method for
1587 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1588 *
1589 * @param changeId The ID of the compatibility change in question.
1590 * @param packageName The package name of the app in question.
1591 * @param user The user that the operation is done for.
1592 * @return {@code true} if the change is enabled for the specified package.
1593 */
1594 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1595 @NonNull final UserHandle user) {
1596 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1597 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001598
1599 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001600 * As above but with a UID.
1601 * @see CompatChanges#isChangeEnabled(long, int)
1602 */
1603 public boolean isChangeEnabled(final long changeId, final int uid) {
1604 return CompatChanges.isChangeEnabled(changeId, uid);
1605 }
1606
1607 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001608 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1609 *
1610 * @param ranges target uid ranges
1611 * @param exemptUids uids to skip close socket
1612 */
1613 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1614 @NonNull final Set<Integer> exemptUids)
1615 throws SocketException, InterruptedIOException, ErrnoException {
1616 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1617 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001618
1619 /**
1620 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1621 *
1622 * @param ownerUids target uids to close sockets
1623 */
1624 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1625 throws SocketException, InterruptedIOException, ErrnoException {
1626 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1627 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001628
1629 /**
1630 * Schedule the evaluation timeout.
1631 *
1632 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1633 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1634 * of these events happen, this time will run out, after which the network is considered
1635 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1636 * on this network and considers it won't provide connectivity. In particular, that means
1637 * it's when the system prefers it to cell if it's wifi and configuration says it should
1638 * prefer bad wifi to cell.
1639 */
1640 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1641 @NonNull final Network network, final long delayMs) {
1642 handler.sendMessageDelayed(
1643 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1644 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001645 }
1646
junyulaie7c7d2a2021-01-26 15:29:15 +08001647 public ConnectivityService(Context context) {
1648 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001649 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1650 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001651 }
1652
1653 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001654 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1655 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001656 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001657
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001658 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001659 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001660 mSystemProperties = mDeps.getSystemProperties();
1661 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001662 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001663 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001664 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1665 // Pass limit - 1 to maintain backward compatibility.
1666 // TODO: Remove the workaround.
1667 mNetworkRequestCounter =
1668 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1669 mSystemNetworkRequestCounter =
1670 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001671
Hugo Benichi208c0102016-07-28 17:53:06 +09001672 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001673 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1674 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001675 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001676 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001677 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001678 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1679 mDefaultNetworkRequests.add(mDefaultRequest);
1680 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001681
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001682 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001683 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001684
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001685 // The default WiFi request is a background request so that apps using WiFi are
1686 // migrated to a better network (typically ethernet) when one comes up, instead
1687 // of staying on WiFi forever.
1688 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1689 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1690
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001691 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1692 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1693 NetworkRequest.Type.BACKGROUND_REQUEST);
1694
Chalard Jean0702f982021-09-16 21:50:07 +09001695 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1696 // TODO: Consider making the timer customizable.
1697 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1698 mCellularRadioTimesharingCapable =
1699 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1700
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001701 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1702 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1703
1704 if (SdkLevel.isAtLeastU()) {
1705 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1706 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1707 final int defaultUMarkMask = 0x80000000; // u32
1708
1709 if ((mark == 0) || (mask == 0)) {
1710 // simply treat unset/disabled as the default U value
1711 mark = defaultUMarkMask;
1712 mask = defaultUMarkMask;
1713 }
1714 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1715 // invalid device overlay settings
1716 throw new IllegalArgumentException(
1717 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1718 }
1719 }
1720
1721 mWakeUpMark = mark;
1722 mWakeUpMask = mask;
1723
Paul Hu51f816b2022-08-11 14:43:47 +00001724 mNetd = netd;
1725 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Chalard Jean96ff9542023-11-02 14:24:47 +09001726 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Paul Hu51f816b2022-08-11 14:43:47 +00001727 mPermissionMonitor =
1728 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001729 mHandlerThread.start();
1730 mHandler = new InternalHandler(mHandlerThread.getLooper());
1731 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001732 mConnectivityDiagnosticsHandler =
1733 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001734
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001735 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001736 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001737
junyulaie7c7d2a2021-01-26 15:29:15 +08001738 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001739 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001740 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001741 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001742
Wink Saville32506bc2013-06-29 21:10:57 -07001743 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001744 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001745 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001746 mCarrierPrivilegeAuthenticator =
1747 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001748
Sudheer Shanka9967d462021-03-18 19:09:25 +00001749 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001750 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1751 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001752 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001753
1754 final PowerManager powerManager = (PowerManager) context.getSystemService(
1755 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001756 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001757 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001758
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001759 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1760 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001761 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001762 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001763 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001764 mProtectedNetworks.add(p);
1765 } else {
1766 if (DBG) loge("Ignoring protectedNetwork " + p);
1767 }
1768 }
1769
soma, kawata29444ae2019-05-23 09:30:40 +09001770 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1771
James Mattis02220e22021-03-13 19:27:21 -08001772 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001773 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001774 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001775 final IntentFilter userIntentFilter = new IntentFilter();
1776 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1777 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1778 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1779 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001780
James Mattis02220e22021-03-13 19:27:21 -08001781 // Listen to package add/removes for netd
1782 final IntentFilter packageIntentFilter = new IntentFilter();
1783 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1784 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1785 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1786 packageIntentFilter.addDataScheme("package");
1787 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001788 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001789
Junyu Lai38c75032023-12-04 07:52:19 +00001790 // This is needed for pre-V devices to propagate the data saver status
1791 // to the BPF map. This isn't supported before Android T because BPF maps are
1792 // unsupported, and it's also unnecessary on Android V and later versions,
1793 // as the platform code handles data saver bit updates. Additionally, checking
1794 // the initial data saver status here is superfluous because the intent won't
1795 // be sent until the system is ready.
1796 if (mDeps.isAtLeastT() && !mDeps.isAtLeastV()) {
1797 final IntentFilter dataSaverIntentFilter =
1798 new IntentFilter(ACTION_RESTRICT_BACKGROUND_CHANGED);
1799 mUserAllContext.registerReceiver(mDataSaverReceiver, dataSaverIntentFilter,
1800 null /* broadcastPermission */, mHandler);
1801 }
1802
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09001803 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
1804 // But reading the trunk stable flags from mainline modules is not supported yet.
1805 // So enabling this feature on V+ release.
1806 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
1807 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
1808 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001809
Chalard Jean46bfbf02022-02-02 00:56:25 +09001810 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001811 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001812 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001813 } catch (RemoteException | ServiceSpecificException e) {
1814 loge("Error registering event listener :" + e);
1815 }
1816
Erik Kline05f2b402015-04-30 12:58:40 +09001817 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1818 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001819
chiachangwang7c17c282023-02-02 05:58:59 +00001820 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001821 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001822 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001823
1824 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001825 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001826 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1827 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001828 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001829 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1830 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001831
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001832 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001833 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001834 mNetworkRanker =
1835 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1836
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001837 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001838
Chiachang Wangc1215d32020-10-20 15:38:58 +08001839 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001840 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001841
Chalard Jean28018572020-12-21 18:36:52 +09001842 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1843 // request that doesn't allow fallback to the default network. It should never be visible
1844 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1845 // arguments like the handler or the DnsResolver.
1846 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001847 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001848 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001849 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001850 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001851 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001852 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1853 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001854
1855 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001856 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1857 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1858 // Even if it could, running on S would at least require mocking out the BPF map,
1859 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1860 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001861 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001862 mDscpPolicyTracker = new DscpPolicyTracker();
1863 }
Tyler Wear72388212021-09-09 14:49:02 -07001864 } catch (ErrnoException e) {
1865 loge("Unable to create DscpPolicyTracker");
1866 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001867
1868 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1869 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001870
Chalard Jeandf29a852023-05-29 17:02:43 +09001871 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001872 mCdmps = new CompanionDeviceManagerProxyService(context);
1873 } else {
1874 mCdmps = null;
1875 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001876
Chalard Jean2fb66f12023-08-25 12:50:37 +09001877 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
Yang Sun29037f62023-12-04 10:31:58 +08001878 mMulticastRoutingCoordinatorService =
1879 mDeps.makeMulticastRoutingCoordinatorService(mHandler);
Chalard Jean2fb66f12023-08-25 12:50:37 +09001880
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001881 mDestroyFrozenSockets = mDeps.isAtLeastU()
1882 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1883 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1884 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001885 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1886 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001887 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001888 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1889 new UidFrozenStateChangedCallback() {
1890 @Override
1891 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1892 if (uids.length != frozenStates.length) {
1893 Log.wtf(TAG, "uids has length " + uids.length
1894 + " but frozenStates has length " + frozenStates.length);
1895 return;
1896 }
1897
1898 final UidFrozenStateChangedArgs args =
1899 new UidFrozenStateChangedArgs(uids, frozenStates);
1900
1901 mHandler.sendMessage(
1902 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1903 }
1904 };
1905
1906 final ActivityManager activityManager =
1907 mContext.getSystemService(ActivityManager.class);
1908 activityManager.registerUidFrozenStateChangedCallback(
1909 (Runnable r) -> r.run(), frozenStateChangedCallback);
1910 }
Yuyang Huang41557552023-11-28 12:47:22 +09001911
1912 if (mDeps.isFeatureNotChickenedOut(mContext, LOG_BPF_RC)) {
1913 mHandler.post(BpfLoaderRcUtils::checkBpfLoaderRc);
1914 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001915 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001916
Xiao Ma0a171c02022-01-23 16:14:51 +00001917 /**
1918 * Check whether or not the device supports Ethernet transport.
1919 */
1920 public static boolean deviceSupportsEthernet(final Context context) {
1921 final PackageManager pm = context.getPackageManager();
1922 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1923 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1924 }
1925
Chalard Jean46adcf32018-04-18 20:18:38 +09001926 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001927 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1928 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001929 }
1930
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001931 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1932 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001933 final NetworkCapabilities netCap = new NetworkCapabilities();
1934 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001935 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001936 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001937 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001938 return netCap;
1939 }
1940
James Mattis45d81842021-01-10 14:24:24 -08001941 private NetworkRequest createDefaultRequest() {
1942 return createDefaultInternetRequestForTransport(
1943 TYPE_NONE, NetworkRequest.Type.REQUEST);
1944 }
1945
lucaslin3ba7cc22022-12-19 02:35:33 +00001946 private NetworkRequest createVpnRequest() {
1947 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1948 .withoutDefaultCapabilities()
1949 .addTransportType(TRANSPORT_VPN)
1950 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1951 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1952 .build();
1953 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1954 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1955 }
1956
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001957 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001958 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001959 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001960 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001961 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001962 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001963 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001964 netCap.addTransportType(transportType);
1965 }
James Mattis45d81842021-01-10 14:24:24 -08001966 return createNetworkRequest(type, netCap);
1967 }
1968
1969 private NetworkRequest createNetworkRequest(
1970 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001971 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001972 }
1973
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001974 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1975 NetworkRequest.Type type) {
1976 final NetworkCapabilities netCap = new NetworkCapabilities();
1977 netCap.clearAll();
1978 netCap.addCapability(capability);
1979 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1980 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1981 }
1982
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001983 // Used only for testing.
1984 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001985 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001986 // changing ContentResolver to make registerContentObserver non-final).
1987 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1988 // by subclassing SettingsObserver.
1989 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001990 void updateAlwaysOnNetworks() {
1991 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001992 }
1993
Erik Kline9a62f012018-03-21 07:18:33 -07001994 // See FakeSettingsProvider comment above.
1995 @VisibleForTesting
1996 void updatePrivateDnsSettings() {
1997 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1998 }
1999
paulhu51f77dc2021-06-07 02:34:20 +00002000 @VisibleForTesting
2001 void updateMobileDataPreferredUids() {
2002 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
2003 }
2004
Patrick Rohr2857ac42022-01-21 14:58:16 +01002005 @VisibleForTesting
2006 void updateIngressRateLimit() {
2007 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
2008 }
2009
Aaron Huang40b52442021-06-08 04:34:24 +08002010 @VisibleForTesting
2011 void simulateUpdateProxyInfo(@Nullable final Network network,
2012 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08002013 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08002014 new Pair<>(network, proxyInfo)).sendToTarget();
2015 }
2016
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002017 private void handleAlwaysOnNetworkRequest(
2018 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002019 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002020 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002021 handleAlwaysOnNetworkRequest(networkRequest, enable);
2022 }
2023
2024 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002025 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002026 if (enable == isEnabled) {
2027 return; // Nothing to do.
2028 }
2029
2030 if (enable) {
2031 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002032 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002033 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002034 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002035 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002036 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2037 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002038 }
2039 }
2040
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002041 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002042 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2043 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2044 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2045 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002046 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2047 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002048 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002049 }
2050
paulhu51f77dc2021-06-07 02:34:20 +00002051 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002052 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002053 private void registerSettingsCallbacks() {
2054 // Watch for global HTTP proxy changes.
2055 mSettingsObserver.observe(
2056 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2057 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2058
Chalard Jean46bfbf02022-02-02 00:56:25 +09002059 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002060 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002061 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002062 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2063
Chalard Jean46bfbf02022-02-02 00:56:25 +09002064 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002065 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002066 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002067 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002068
2069 // Watch for mobile data preferred uids changes.
2070 mSettingsObserver.observe(
2071 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2072 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002073
2074 // Watch for ingress rate limit changes.
2075 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002076 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002077 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2078 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002079 }
2080
Erik Kline31b4a9e2018-01-11 21:07:29 +09002081 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002082 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2083 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002084 }
2085 }
2086
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002087 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002088 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2089 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002090 return mNextNetworkRequestId++;
2091 }
2092
junyulai74f9a8b2018-06-13 15:00:37 +08002093 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002094 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002095 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002096 if (network == null) {
2097 return null;
2098 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002099 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002100 }
2101
2102 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002103 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002104 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002105 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002106 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002107
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002108 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002109 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002110 private NetworkAgentInfo getVpnForUid(int uid) {
2111 synchronized (mNetworkForNetId) {
2112 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2113 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002114 if (nai.isVPN() && nai.everConnected()
2115 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002116 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002117 }
2118 }
2119 }
2120 return null;
2121 }
2122
Chalard Jean46bfbf02022-02-02 00:56:25 +09002123 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002124 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002125 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002126 final NetworkAgentInfo nai = getVpnForUid(uid);
2127 if (nai != null) return nai.declaredUnderlyingNetworks;
2128 return null;
2129 }
2130
Lorenzo Colittia7574052021-01-19 01:33:05 +09002131 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002132 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002133
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002134 final Network[] networks = getVpnUnderlyingNetworks(uid);
2135 if (networks != null) {
2136 // getUnderlyingNetworks() returns:
2137 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2138 // empty array => the VPN explicitly said "no default network".
2139 // non-empty array => the VPN specified one or more default networks; we use the
2140 // first one.
2141 if (networks.length > 0) {
2142 nai = getNetworkAgentInfoForNetwork(networks[0]);
2143 } else {
2144 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002145 }
2146 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002147 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002148 }
2149
2150 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002151 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002152 */
paulhu7aeba372020-12-30 00:42:19 +08002153 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2154 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002155 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002156 if (ignoreBlocked) {
2157 return false;
2158 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002159 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002160 final long ident = Binder.clearCallingIdentity();
2161 try {
2162 final boolean metered = nc == null ? true : nc.isMetered();
2163 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2164 } finally {
2165 Binder.restoreCallingIdentity(ident);
2166 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002167 }
2168
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002169 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002170 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2171 return;
2172 }
Hugo Benichi47011212017-03-30 10:46:05 +09002173 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002174 synchronized (mBlockedAppUids) {
2175 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002176 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002177 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002178 blocked = false;
2179 } else {
2180 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002181 }
2182 }
Hugo Benichi47011212017-03-30 10:46:05 +09002183 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2184 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2185 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002186 }
2187
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002188 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002189 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2190 return;
2191 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002192 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002193 final int requestId = nri.getActiveRequest() != null
2194 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002195 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002196 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002197 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002198 }
2199
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002200 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002201 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002202 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002203 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002204 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002205 @NonNull
2206 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2207 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002208 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2209 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2210 // but only exists if an app asks about them or requests them. Ensure the requesting app
2211 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002212 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002213 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2214 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2215 null /* extraInfo */);
2216 }
2217 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002218 return filtered;
2219 }
2220
2221 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2222 boolean ignoreBlocked) {
2223 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2224 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002225 }
2226
2227 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002228 * Return NetworkInfo for the active (i.e., connected) network interface.
2229 * It is assumed that at most one network is active at a time. If more
2230 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002231 * @return the info for the active network, or {@code null} if none is
2232 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002233 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002234 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002235 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002236 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002237 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002238 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002239 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2240 if (nai == null) return null;
2241 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2242 maybeLogBlockedNetworkInfo(networkInfo, uid);
2243 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002244 }
2245
Paul Jensen1f567382015-02-13 14:18:39 -05002246 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002247 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002248 public Network getActiveNetwork() {
2249 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002250 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002251 }
2252
2253 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002254 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002255 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002256 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002257 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002258 }
2259
Chalard Jean46bfbf02022-02-02 00:56:25 +09002260 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002261 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002262 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2263 if (vpnNai != null) {
2264 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2265 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2266 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002267 }
Paul Jensen1f567382015-02-13 14:18:39 -05002268 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002269
James Mattis2516da32021-01-31 17:06:19 -08002270 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002271 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2272 ignoreBlocked)) {
2273 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002274 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002275 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002276 }
2277
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002278 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002279 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002280 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002281 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002282 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2283 if (nai == null) return null;
2284 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002285 }
2286
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002287 /** Returns a NetworkInfo object for a network that doesn't exist. */
2288 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2289 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2290 getNetworkTypeName(networkType), "" /* subtypeName */);
2291 info.setIsAvailable(true);
2292 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2293 // background data is restricted.
2294 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2295 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2296 ? DetailedState.BLOCKED
2297 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002298 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2299 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002300 return info;
2301 }
2302
Lorenzo Colittia7574052021-01-19 01:33:05 +09002303 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002304 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2305 return null;
2306 }
2307 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002308 if (nai == null) {
2309 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002310 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002311 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2312 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002313 }
2314
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002315 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002316 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002317 public NetworkInfo getNetworkInfo(int networkType) {
2318 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002319 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002320 if (getVpnUnderlyingNetworks(uid) != null) {
2321 // A VPN is active, so we may need to return one of its underlying networks. This
2322 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002323 // getNetworkAgentInfoForUid.
2324 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2325 if (nai == null) return null;
2326 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2327 if (networkInfo.getType() == networkType) {
2328 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002329 }
2330 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002331 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002332 }
2333
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002334 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002335 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002336 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002337 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002338 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002339 if (nai == null) return null;
2340 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002341 }
2342
2343 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002344 public NetworkInfo[] getAllNetworkInfo() {
2345 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002346 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002347 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2348 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002349 NetworkInfo info = getNetworkInfo(networkType);
2350 if (info != null) {
2351 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002352 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002353 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002354 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002355 }
2356
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002357 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002358 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002359 public Network getNetworkForType(int networkType) {
2360 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002361 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2362 return null;
2363 }
2364 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2365 if (nai == null) {
2366 return null;
2367 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002368 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002369 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2370 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002371 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002372 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002373 }
2374
2375 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002376 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002377 public Network[] getAllNetworks() {
2378 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002379 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002380 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002381 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002382 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002383 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002384 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002385 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002386 }
2387
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002388 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002389 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002390 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002391 // The basic principle is: if an app's traffic could possibly go over a
2392 // network, without the app doing anything multinetwork-specific,
2393 // (hence, by "default"), then include that network's capabilities in
2394 // the array.
2395 //
2396 // In the normal case, app traffic only goes over the system's default
2397 // network connection, so that's the only network returned.
2398 //
2399 // With a VPN in force, some app traffic may go into the VPN, and thus
2400 // over whatever underlying networks the VPN specifies, while other app
2401 // traffic may go over the system default network (e.g.: a split-tunnel
2402 // VPN, or an app disallowed by the VPN), so the set of networks
2403 // returned includes the VPN's underlying networks and the system
2404 // default.
2405 enforceAccessPermission();
2406
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002407 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002408
James Mattis2516da32021-01-31 17:06:19 -08002409 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2410 if (!nri.isBeingSatisfied()) {
2411 continue;
2412 }
2413 final NetworkAgentInfo nai = nri.getSatisfier();
2414 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2415 if (null != nc
2416 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2417 && !result.containsKey(nai.network)) {
2418 result.put(
2419 nai.network,
2420 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002421 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002422 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2423 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002424 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002425 }
2426
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002427 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002428 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002429 if (null != networks) {
2430 for (final Network network : networks) {
2431 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2432 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002433 result.put(
2434 network,
2435 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002436 nc,
2437 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002438 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002439 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002440 }
2441 }
2442 }
2443
2444 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2445 out = result.values().toArray(out);
2446 return out;
2447 }
2448
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002449 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2450 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2451 // can call sampleConnectivityState and make the checks on it.
2452 @NonNull
2453 private StatsEvent sampleConnectivityStateToStatsEvent() {
2454 final ConnectivityStateSample sample = sampleConnectivityState();
2455 return ConnectivityStatsLog.buildStatsEvent(
2456 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2457 sample.getNetworkCountPerTransports().toByteArray(),
2458 sample.getConnectionDurationPerTransports().toByteArray(),
2459 sample.getNetworkRequestCount().toByteArray(),
2460 sample.getNetworks().toByteArray());
2461 }
2462
2463 /**
2464 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2465 *
2466 * This is used for metrics. These snapshots will be sampled and constitute a base for
2467 * statistics about connectivity state of devices.
2468 */
2469 @VisibleForTesting
2470 @NonNull
2471 public ConnectivityStateSample sampleConnectivityState() {
2472 ensureRunningOnConnectivityServiceThread();
2473 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2474 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2475 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2476 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2477 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2478 return builder.build();
2479 }
2480
2481 private static NetworkCountPerTransports sampleNetworkCount(
2482 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2483 final SparseIntArray countPerTransports = new SparseIntArray();
2484 for (final NetworkAgentInfo nai : nais) {
2485 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2486 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2487 }
2488 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2489 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2490 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2491 c.setTransportTypes(countPerTransports.keyAt(i));
2492 c.setNetworkCount(countPerTransports.valueAt(i));
2493 builder.addNetworkCountForTransports(c);
2494 }
2495 return builder.build();
2496 }
2497
2498 private static ConnectionDurationPerTransports sampleConnectionDuration(
2499 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2500 final ConnectionDurationPerTransports.Builder builder =
2501 ConnectionDurationPerTransports.newBuilder();
2502 for (final NetworkAgentInfo nai : nais) {
2503 final ConnectionDurationForTransports.Builder c =
2504 ConnectionDurationForTransports.newBuilder();
2505 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2506 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2507 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2508 // Add millisPerSecond/2 to round up or down to the nearest value
2509 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2510 builder.addConnectionDurationForTransports(c);
2511 }
2512 return builder.build();
2513 }
2514
2515 private static NetworkRequestCount sampleNetworkRequestCount(
2516 @NonNull final Collection<NetworkRequestInfo> nris) {
2517 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2518 final SparseIntArray countPerType = new SparseIntArray();
2519 for (final NetworkRequestInfo nri : nris) {
2520 final int type;
2521 if (Process.SYSTEM_UID == nri.mAsUid) {
2522 // The request is filed "as" the system, so it's the system on its own behalf.
2523 type = RequestType.RT_SYSTEM.getNumber();
2524 } else if (Process.SYSTEM_UID == nri.mUid) {
2525 // The request is filed by the system as some other app, so it's the system on
2526 // behalf of an app.
2527 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2528 } else {
2529 // Not the system, so it's an app requesting on its own behalf.
2530 type = RequestType.RT_APP.getNumber();
2531 }
2532 countPerType.put(type, countPerType.get(type, 0));
2533 }
2534 for (int i = countPerType.size() - 1; i >= 0; --i) {
2535 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2536 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2537 r.setRequestCount(countPerType.valueAt(i));
2538 builder.addRequestCountForType(r);
2539 }
2540 return builder.build();
2541 }
2542
2543 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2544 final NetworkList.Builder builder = NetworkList.newBuilder();
2545 for (final NetworkAgentInfo nai : nais) {
2546 final NetworkCapabilities nc = nai.networkCapabilities;
2547 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2548 d.setTransportTypes((int) nc.getTransportTypesInternal());
2549 final MeteredState meteredState;
2550 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2551 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2552 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2553 meteredState = MeteredState.METERED_NO;
2554 } else {
2555 meteredState = MeteredState.METERED_YES;
2556 }
2557 d.setMeteredState(meteredState);
2558 final ValidatedState validatedState;
2559 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2560 validatedState = ValidatedState.VS_PORTAL;
2561 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2562 validatedState = ValidatedState.VS_PARTIAL;
2563 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2564 validatedState = ValidatedState.VS_VALID;
2565 } else {
2566 validatedState = ValidatedState.VS_INVALID;
2567 }
2568 d.setValidatedState(validatedState);
2569 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2570 d.setCapabilities(nc.getCapabilitiesInternal());
2571 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2572 builder.addNetworkDescription(d);
2573 }
2574 return builder.build();
2575 }
2576
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002577 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002578 public boolean isNetworkSupported(int networkType) {
2579 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002580 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002581 }
2582
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002583 /**
2584 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002585 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002586 * @return the ip properties for the active network, or {@code null} if
2587 * none is active
2588 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002589 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002590 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002591 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002592 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002593 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2594 if (nai == null) return null;
2595 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002596 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002597 }
2598
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002599 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002600 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002601 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002602 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002603 final LinkProperties lp = getLinkProperties(nai);
2604 if (lp == null) return null;
2605 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002606 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002607 }
2608
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002609 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002610 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002611 public LinkProperties getLinkProperties(Network network) {
2612 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002613 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2614 if (lp == null) return null;
2615 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002616 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002617 }
2618
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002619 @Nullable
2620 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002621 if (nai == null) {
2622 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002623 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002624 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002625 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002626 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002627 }
2628
lucaslinc582d502022-01-27 09:07:00 +08002629 @Override
2630 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002631 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002632 @NonNull String packageName, @Nullable String callingAttributionTag) {
2633 Objects.requireNonNull(packageName);
2634 Objects.requireNonNull(lp);
2635 enforceNetworkStackOrSettingsPermission();
2636 if (!checkAccessPermission(-1 /* pid */, uid)) {
2637 return null;
2638 }
2639 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2640 }
2641
Qingxi Lib2748102020-01-08 12:51:49 -08002642 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2643 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2644 }
2645
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002646 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002647 if (nai == null) return null;
2648 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002649 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002650 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002651 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002652 }
2653
2654 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002655 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2656 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002657 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002658 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002659 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002660 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002661 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002662 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002663 }
2664
lucaslinc582d502022-01-27 09:07:00 +08002665 @Override
lucaslind2b06132022-03-02 10:56:57 +08002666 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2667 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2668 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002669 Objects.requireNonNull(nc);
2670 Objects.requireNonNull(packageName);
2671 enforceNetworkStackOrSettingsPermission();
2672 if (!checkAccessPermission(-1 /* pid */, uid)) {
2673 return null;
2674 }
2675 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2676 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2677 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2678 callingAttributionTag);
2679 }
2680
lucaslin69e1aa92022-03-22 18:15:09 +08002681 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2682 if (nc.getUnderlyingNetworks() != null
2683 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2684 nc.setUnderlyingNetworks(null);
2685 }
2686 }
2687
Chalard Jean53017782022-11-24 17:13:44 +09002688 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
2689 return Process.SYSTEM_UID == uid
Chalard Jean53017782022-11-24 17:13:44 +09002690 || checkAnyPermissionOf(mContext, pid, uid,
2691 android.Manifest.permission.NETWORK_FACTORY);
2692 }
2693
Qingxi Libb8da982020-01-17 17:54:27 -08002694 @VisibleForTesting
2695 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002696 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002697 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2698 // this would be expensive (one more permission check every time any NC callback is
2699 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2700 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2701 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002702 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002703 if (!checkSettingsPermission(callerPid, callerUid)) {
2704 newNc.setUids(null);
2705 newNc.setSSID(null);
2706 }
Etan Cohen107ae952018-12-30 17:59:59 -08002707 if (newNc.getNetworkSpecifier() != null) {
2708 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2709 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002710 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2711 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002712 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2713 newNc.setAdministratorUids(new int[0]);
2714 }
Chalard Jean53017782022-11-24 17:13:44 +09002715 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09002716 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002717 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002718 }
lucaslin69e1aa92022-03-22 18:15:09 +08002719 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002720
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002721 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002722 }
2723
Roshan Pius98f59ec2021-02-23 08:47:39 -08002724 /**
2725 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002726 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002727 * NetworkCapabilities.
2728 * Note: This wrapper does not support any sort of invalidation and thus must not be
2729 * persistent or long-lived. It may only be used for the time necessary to
2730 * compute the redactions required by one particular NetworkCallback or
2731 * synchronous call.
2732 */
2733 private class RedactionPermissionChecker {
2734 private final int mCallingPid;
2735 private final int mCallingUid;
2736 @NonNull private final String mCallingPackageName;
2737 @Nullable private final String mCallingAttributionTag;
2738
2739 private Boolean mHasLocationPermission = null;
2740 private Boolean mHasLocalMacAddressPermission = null;
2741 private Boolean mHasSettingsPermission = null;
2742
2743 RedactionPermissionChecker(int callingPid, int callingUid,
2744 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2745 mCallingPid = callingPid;
2746 mCallingUid = callingUid;
2747 mCallingPackageName = callingPackageName;
2748 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002749 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002750
2751 private boolean hasLocationPermissionInternal() {
2752 final long token = Binder.clearCallingIdentity();
2753 try {
2754 return mLocationPermissionChecker.checkLocationPermission(
2755 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2756 null /* message */);
2757 } finally {
2758 Binder.restoreCallingIdentity(token);
2759 }
2760 }
2761
2762 /**
2763 * Returns whether the app holds location permission or not (might return cached result
2764 * if the permission was already checked before).
2765 */
2766 public boolean hasLocationPermission() {
2767 if (mHasLocationPermission == null) {
2768 // If there is no cached result, perform the check now.
2769 mHasLocationPermission = hasLocationPermissionInternal();
2770 }
2771 return mHasLocationPermission;
2772 }
2773
2774 /**
2775 * Returns whether the app holds local mac address permission or not (might return cached
2776 * result if the permission was already checked before).
2777 */
2778 public boolean hasLocalMacAddressPermission() {
2779 if (mHasLocalMacAddressPermission == null) {
2780 // If there is no cached result, perform the check now.
2781 mHasLocalMacAddressPermission =
2782 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2783 }
2784 return mHasLocalMacAddressPermission;
2785 }
2786
2787 /**
2788 * Returns whether the app holds settings permission or not (might return cached
2789 * result if the permission was already checked before).
2790 */
2791 public boolean hasSettingsPermission() {
2792 if (mHasSettingsPermission == null) {
2793 // If there is no cached result, perform the check now.
2794 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2795 }
2796 return mHasSettingsPermission;
2797 }
2798 }
2799
2800 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2801 @NetworkCapabilities.NetCapability long redaction) {
2802 return (redactions & redaction) != 0;
2803 }
2804
2805 /**
2806 * Use the provided |applicableRedactions| to check the receiving app's
2807 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2808 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2809 * before being sent to the corresponding app.
2810 */
2811 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2812 @NetworkCapabilities.RedactionType long applicableRedactions,
2813 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2814 boolean includeLocationSensitiveInfo) {
2815 long redactions = applicableRedactions;
2816 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2817 if (includeLocationSensitiveInfo
2818 && redactionPermissionChecker.hasLocationPermission()) {
2819 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2820 }
2821 }
2822 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2823 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2824 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2825 }
2826 }
2827 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2828 if (redactionPermissionChecker.hasSettingsPermission()) {
2829 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2830 }
2831 }
2832 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002833 }
2834
Qingxi Lib2748102020-01-08 12:51:49 -08002835 @VisibleForTesting
2836 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002837 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002838 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002839 int callingPid, int callingUid, @NonNull String callingPkgName,
2840 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002841 if (nc == null) {
2842 return null;
2843 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002844 // Avoid doing location permission check if the transport info has no location sensitive
2845 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002846 final RedactionPermissionChecker redactionPermissionChecker =
2847 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2848 callingAttributionTag);
2849 final long redactions = retrieveRequiredRedactions(
2850 nc.getApplicableRedactions(), redactionPermissionChecker,
2851 includeLocationSensitiveInfo);
2852 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002853 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002854 // TODO : calling UID is redacted because apps should generally not know what UID is
2855 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002856 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002857 newNc.setOwnerUid(INVALID_UID);
2858 return newNc;
2859 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002860 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2861 if (nc.hasTransport(TRANSPORT_VPN)) {
2862 // Owner UIDs already checked above. No need to re-check.
2863 return newNc;
2864 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002865 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2866 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002867 // compatibility for older apps.
2868 if (!includeLocationSensitiveInfo
2869 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002870 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002871 newNc.setOwnerUid(INVALID_UID);
2872 return newNc;
2873 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002874 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002875 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002876 newNc.setOwnerUid(INVALID_UID);
2877 }
Qingxi Lib2748102020-01-08 12:51:49 -08002878 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002879 }
2880
lucaslinc582d502022-01-27 09:07:00 +08002881 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002882 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2883 LinkProperties lp, int callerPid, int callerUid) {
2884 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002885 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2886 // this would be expensive (one more permission check every time any LP callback is
2887 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2888 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2889 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002890
2891 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2892 final boolean needsSanitization =
2893 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2894 if (!needsSanitization) {
2895 return new LinkProperties(lp);
2896 }
2897
2898 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002899 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002900 }
2901
2902 final LinkProperties newLp = new LinkProperties(lp);
2903 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2904 // object gets parceled.
2905 newLp.setCaptivePortalApiUrl(null);
2906 newLp.setCaptivePortalData(null);
2907 return newLp;
2908 }
2909
Roshan Pius08c94fb2020-01-16 12:17:17 -08002910 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2911 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002912 // There is no need to track the effective UID of the request here. If the caller
2913 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002914 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002915 // Unprivileged apps can only pass in null or their own UID.
2916 if (nc.getUids() == null) {
2917 // If the caller passes in null, the callback will also match networks that do not
2918 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2919 // In this case, redact everything in the request immediately. This ensures that the
2920 // app is not able to get any redacted information by filing an unredacted request
2921 // and observing whether the request matches something.
2922 if (nc.getNetworkSpecifier() != null) {
2923 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2924 }
2925 } else {
2926 nc.setSingleUid(callerUid);
2927 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002928 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002929 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002930 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002931
2932 // Clear owner UID; this can never come from an app.
2933 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002934 }
2935
Chalard Jean38354d12018-03-20 19:13:57 +09002936 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002937 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002938 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2939 }
2940 }
2941
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002942 @Override
2943 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2944 enforceAccessPermission();
2945 final int callerUid = Binder.getCallingUid();
2946 final long token = Binder.clearCallingIdentity();
2947 try {
2948 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2949 } finally {
2950 Binder.restoreCallingIdentity(token);
2951 }
2952 }
2953
junyulaiebd15162021-03-03 12:09:05 +08002954 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002955 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002956 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002957 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002958 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002959
Serik Beketayev05130302021-01-15 16:47:25 -08002960 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002961 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002962 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2963 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002964 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002965 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002966 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002967 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2968 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002969 }
2970 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002971 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002972 }
2973
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002974 @Override
junyulaiebd15162021-03-03 12:09:05 +08002975 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002976 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002977 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002978 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002979
2980 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2981 for (Network network : getAllNetworks()) {
2982 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002983 final boolean includeNetwork = (nai != null) && nai.isCreated();
2984 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002985 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2986 // NetworkCapabilities, which may contain UIDs of apps to which the
2987 // network applies. Should the UIDs be cleared so as not to leak or
2988 // interfere ?
2989 result.add(nai.getNetworkStateSnapshot());
2990 }
2991 }
2992 return result;
2993 }
2994
2995 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002996 public boolean isActiveNetworkMetered() {
2997 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002998
Qingxi Lib2748102020-01-08 12:51:49 -08002999 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06003000 if (caps != null) {
3001 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3002 } else {
3003 // Always return the most conservative value
3004 return true;
3005 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07003006 }
3007
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003008 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09003009 * Ensures that the system cannot call a particular method.
3010 */
3011 private boolean disallowedBecauseSystemCaller() {
3012 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07003013 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
3014 // for devices launched with Q and above. However, existing devices upgrading to Q and
3015 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003016 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07003017 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003018 log("This method exists only for app backwards compatibility"
3019 + " and must not be called by system services.");
3020 return true;
3021 }
3022 return false;
3023 }
3024
paulhub2c28682021-08-18 18:35:54 +08003025 private int getAppUid(final String app, final UserHandle user) {
3026 final PackageManager pm =
3027 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
3028 final long token = Binder.clearCallingIdentity();
3029 try {
3030 return pm.getPackageUid(app, 0 /* flags */);
3031 } catch (PackageManager.NameNotFoundException e) {
3032 return -1;
3033 } finally {
3034 Binder.restoreCallingIdentity(token);
3035 }
3036 }
3037
3038 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
3039 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
3040 if (getAppUid(packageName, user) != callingUid) {
3041 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
3042 }
3043 }
3044
Lorenzo Colitti23862912018-09-28 11:31:55 +09003045 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003046 * Ensure that a network route exists to deliver traffic to the specified
3047 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003048 * @param networkType the type of the network over which traffic to the
3049 * specified host is to be routed
3050 * @param hostAddress the IP address of the host to which the route is
3051 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003052 * @return {@code true} on success, {@code false} on failure
3053 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003054 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003055 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3056 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003057 if (disallowedBecauseSystemCaller()) {
3058 return false;
3059 }
paulhub2c28682021-08-18 18:35:54 +08003060 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003061 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003062 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003063 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003064 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003065
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003066 InetAddress addr;
3067 try {
3068 addr = InetAddress.getByAddress(hostAddress);
3069 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003070 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003071 return false;
3072 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003073
The Android Open Source Project28527d22009-03-03 19:31:44 -08003074 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003075 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003076 return false;
3077 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003078
3079 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3080 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003081 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003082 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3083 } else {
3084 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3085 }
3086 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003087 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003088
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003089 DetailedState netState;
3090 synchronized (nai) {
3091 netState = nai.networkInfo.getDetailedState();
3092 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003093
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003094 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003095 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003096 log("requestRouteToHostAddress on down network "
3097 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003098 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003099 }
3100 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003101 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003102
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003103 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003104 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003105 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003106 LinkProperties lp;
3107 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003108 synchronized (nai) {
3109 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003110 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003111 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003112 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003113 if (DBG) {
3114 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3115 }
Wink Saville32506bc2013-06-29 21:10:57 -07003116 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003117 } finally {
3118 Binder.restoreCallingIdentity(token);
3119 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003120 }
3121
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003122 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003123 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003124 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003125 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003126 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003127 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003128 if (bestRoute.getGateway().equals(addr)) {
3129 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003130 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003131 } else {
3132 // if we will connect to this through another route, add a direct route
3133 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003134 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003135 }
3136 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003137 if (DBG) log("Adding legacy route " + bestRoute +
3138 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003139
3140 final String dst = bestRoute.getDestinationLinkAddress().toString();
3141 final String nextHop = bestRoute.hasGateway()
3142 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003143 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003144 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3145 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003146 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003147 return false;
3148 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003149 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003150 }
3151
paulhu7c0a2e62021-01-08 00:51:49 +08003152 class DnsResolverUnsolicitedEventCallback extends
3153 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003154 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003155 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003156 try {
3157 mHandler.sendMessage(mHandler.obtainMessage(
3158 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003159 new PrivateDnsValidationUpdate(event.netId,
3160 InetAddresses.parseNumericAddress(event.ipAddress),
3161 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003162 } catch (IllegalArgumentException e) {
3163 loge("Error parsing ip address in validation event");
3164 }
3165 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003166
3167 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003168 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3169 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003170 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3171 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3172 // event callback for certain nai. e.g. cellular. Register here to pass to
3173 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003174 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003175 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3176 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003177 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003178 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003179 }
3180 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003181
3182 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003183 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3184 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3185 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003186 }
dalyk1720e542018-03-05 12:42:22 -05003187
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003188 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003189 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003190 return this.VERSION;
3191 }
3192
3193 @Override
3194 public String getInterfaceHash() {
3195 return this.HASH;
3196 }
paulhu7c0a2e62021-01-08 00:51:49 +08003197 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003198
3199 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003200 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3201 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003202
paulhu7c0a2e62021-01-08 00:51:49 +08003203 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003204 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003205 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003206 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003207 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003208 }
3209 }
3210
Sudheer Shanka9967d462021-03-18 19:09:25 +00003211 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003212 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003213 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003214 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3215 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003216 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003217 };
3218
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003219 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003220 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003221 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003222 }
3223
Mark Fasheh7c999d82023-05-04 20:23:11 +00003224 static final class UidFrozenStateChangedArgs {
3225 final int[] mUids;
3226 final int[] mFrozenStates;
3227
3228 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3229 mUids = uids;
3230 mFrozenStates = frozenStates;
3231 }
3232 }
3233
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003234 /**
3235 * Check if the cell network is idle.
3236 * @return true if the cell network state is idle
3237 * false if the cell network state is active or unknown
3238 */
3239 private boolean isCellNetworkIdle() {
3240 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3241 if (defaultNai == null
3242 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3243 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3244 // cell network is not the default network, cell network state is unknown.
3245 // TODO(b/279380356): Track cell network state when the cell is not the default network
3246 return false;
3247 }
3248
3249 return !mNetworkActivityTracker.isDefaultNetworkActive();
3250 }
3251
Mark Fasheh7c999d82023-05-04 20:23:11 +00003252 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003253 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003254
3255 for (int i = 0; i < uids.length; i++) {
3256 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003257 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003258 } else {
3259 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003260 }
3261 }
3262
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003263 if (ownerUids.isEmpty()) {
3264 return;
3265 }
3266
3267 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3268 // Delay closing sockets to avoid waking the cell modem up.
3269 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3270 // than waking cell modem up.
3271 mPendingFrozenUids.addAll(ownerUids);
3272 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003273 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003274 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003275 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003276 loge("Exception in socket destroy: " + e);
3277 }
3278 }
3279 }
3280
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003281 private void closePendingFrozenSockets() {
3282 ensureRunningOnConnectivityServiceThread();
3283
3284 try {
3285 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3286 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3287 loge("Failed to close pending frozen app sockets: " + e);
3288 }
3289 mPendingFrozenUids.clear();
3290 }
3291
3292 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3293 mNetworkActivityTracker.handleReportNetworkActivity(params);
3294
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003295 final boolean isCellNetworkActivity;
3296 if (mTrackMultiNetworkActivities) {
3297 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3298 // nai could be null if netd receives a netlink message and calls the network
3299 // activity change callback after the network is unregistered from ConnectivityService.
3300 isCellNetworkActivity = nai != null
3301 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3302 } else {
3303 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3304 }
3305
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003306 if (mDelayDestroyFrozenSockets
3307 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003308 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003309 && !mPendingFrozenUids.isEmpty()) {
3310 closePendingFrozenSockets();
3311 }
3312 }
3313
3314 /**
3315 * If the cellular network is no longer the default network, close pending frozen sockets.
3316 *
3317 * @param newNetwork new default network
3318 * @param oldNetwork old default network
3319 */
3320 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3321 NetworkAgentInfo oldNetwork) {
3322 final boolean isOldNetworkCellular = oldNetwork != null
3323 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3324 final boolean isNewNetworkCellular = newNetwork != null
3325 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3326
3327 if (isOldNetworkCellular
3328 && !isNewNetworkCellular
3329 && !mPendingFrozenUids.isEmpty()) {
3330 closePendingFrozenSockets();
3331 }
3332 }
3333
3334 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3335 pw.println("CloseFrozenAppSockets:");
3336 pw.increaseIndent();
3337 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3338 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3339 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3340 pw.decreaseIndent();
3341 }
3342
Junyu Lai155760b2023-10-05 14:51:00 +08003343 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3344 pw.println("Bpf Program Status:");
3345 pw.increaseIndent();
3346 try {
3347 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003348 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003349 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003350 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003351 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003352 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003353 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003354 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003355 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003356 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003357 } catch (IOException e) {
3358 pw.println(" IOException");
3359 }
3360 pw.decreaseIndent();
3361 }
3362
Mark Fasheh7c999d82023-05-04 20:23:11 +00003363 @VisibleForTesting
3364 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003365 @VisibleForTesting
3366 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3367 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003368
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003369 @VisibleForTesting
3370 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3371 "allow_sysui_connectivity_reports";
3372
Yuyang Huang41557552023-11-28 12:47:22 +09003373 public static final String LOG_BPF_RC = "log_bpf_rc_force_disable";
3374
Paul Jensen83f5d572014-08-29 09:54:01 -04003375 private void enforceInternetPermission() {
3376 mContext.enforceCallingOrSelfPermission(
3377 android.Manifest.permission.INTERNET,
3378 "ConnectivityService");
3379 }
3380
The Android Open Source Project28527d22009-03-03 19:31:44 -08003381 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003382 mContext.enforceCallingOrSelfPermission(
3383 android.Manifest.permission.ACCESS_NETWORK_STATE,
3384 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003385 }
3386
lucaslinc582d502022-01-27 09:07:00 +08003387 private boolean checkAccessPermission(int pid, int uid) {
3388 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3389 == PERMISSION_GRANTED;
3390 }
3391
paulhua6ee2122021-02-22 15:40:43 +08003392 /**
3393 * Performs a strict and comprehensive check of whether a calling package is allowed to
3394 * change the state of network, as the condition differs for pre-M, M+, and
3395 * privileged/preinstalled apps. The caller is expected to have either the
3396 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3397 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3398 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3399 * permission and cannot be revoked. See http://b/23597341
3400 *
3401 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3402 * of this app will be updated to the current time.
3403 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003404 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003405 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3406 == PackageManager.PERMISSION_GRANTED) {
3407 return;
3408 }
3409
3410 if (callingPkg == null) {
3411 throw new SecurityException("Calling package name is null.");
3412 }
3413
3414 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3415 final int uid = mDeps.getCallingUid();
3416 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3417 callingPkg, callingAttributionTag, null /* message */);
3418
3419 if (mode == AppOpsManager.MODE_ALLOWED) {
3420 return;
3421 }
3422
3423 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3424 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3425 return;
3426 }
3427
3428 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3429 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3430 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003431 }
3432
Charles He9369e612017-05-15 17:07:18 +01003433 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003434 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003435 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003436 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003437 }
3438
Quang Luong98858d62023-02-11 00:25:24 +00003439 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003440 enforceAnyPermissionOf(mContext,
3441 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003442 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003443 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3444 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3445 }
3446
paulhu8e96a752019-08-12 16:25:11 +08003447 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003448 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003449 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003450 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003451 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003452 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003453 }
3454
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003455 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003456 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003457 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003458 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003459 android.Manifest.permission.NETWORK_SETTINGS,
3460 android.Manifest.permission.NETWORK_FACTORY,
3461 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3462 }
3463
3464 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003465 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003466 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003467 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003468 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3469 android.Manifest.permission.NETWORK_FACTORY,
3470 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3471 }
3472
lucaslin69e1aa92022-03-22 18:15:09 +08003473 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3474 return PERMISSION_GRANTED == mContext.checkPermission(
3475 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3476 || PERMISSION_GRANTED == mContext.checkPermission(
3477 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3478 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003479 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003480 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003481 }
3482
Chalard Jean9a396cc2018-02-21 18:43:54 +09003483 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003484 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003485 android.Manifest.permission.NETWORK_SETTINGS,
3486 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003487 }
3488
3489 private boolean checkSettingsPermission(int pid, int uid) {
3490 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003491 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3492 || PERMISSION_GRANTED == mContext.checkPermission(
3493 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003494 }
3495
paulhu8e96a752019-08-12 16:25:11 +08003496 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003497 enforceNetworkStackPermissionOr(mContext,
3498 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003499 }
3500
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003501 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003502 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003503 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003504 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003505 }
3506
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003507 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003508 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003509 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3510 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003511 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003512 }
3513
James Mattis8378aec2021-01-26 14:05:36 -08003514 private void enforceOemNetworkPreferencesPermission() {
3515 mContext.enforceCallingOrSelfPermission(
3516 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3517 "ConnectivityService");
3518 }
3519
James Mattisfa270db2021-05-31 17:11:10 -07003520 private void enforceManageTestNetworksPermission() {
3521 mContext.enforceCallingOrSelfPermission(
3522 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3523 "ConnectivityService");
3524 }
3525
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003526 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003527 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003528 android.Manifest.permission.NETWORK_STACK,
3529 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003530 }
3531
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003532 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003533 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003534 android.Manifest.permission.NETWORK_STACK,
3535 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3536 }
3537
Chris Göllnercc962022023-12-26 09:55:32 +00003538 private boolean checkSystemBarServicePermission(int pid, int uid) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003539 return checkAnyPermissionOf(mContext, pid, uid,
3540 android.Manifest.permission.STATUS_BAR_SERVICE);
3541 }
3542
paulhu1a407652019-03-22 16:35:06 +08003543 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003544 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003545 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003546 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3547 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003548 }
3549
Paul Hu8fc2a552022-05-04 18:44:42 +08003550 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3551 boolean checkUidsAllowedList) {
3552 if (PermissionUtils.checkAnyPermissionOf(mContext,
3553 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3554 return true;
3555 }
3556
3557 // fallback to ConnectivityInternalPermission
3558 // TODO: Remove this fallback check after all apps have declared
3559 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3560 if (PermissionUtils.checkAnyPermissionOf(mContext,
3561 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3562 return true;
3563 }
3564
3565 // Check whether uid is in allowed on restricted networks list.
3566 if (checkUidsAllowedList
3567 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3568 return true;
3569 }
3570 return false;
3571 }
3572
3573 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3574 final int callingUid = mDeps.getCallingUid();
3575 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3576 throw new SecurityException("ConnectivityService: user " + callingUid
3577 + " has no permission to access restricted network.");
3578 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003579 }
3580
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003581 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003582 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003583 }
3584
Roshan Pius98f59ec2021-02-23 08:47:39 -08003585 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3586 return PERMISSION_GRANTED == mContext.checkPermission(
3587 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3588 }
3589
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003590 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003591 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003592 }
3593
3594 private void sendInetConditionBroadcast(NetworkInfo info) {
3595 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3596 }
3597
Wink Saville4f0de1e2011-08-04 15:01:58 -07003598 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003599 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003600 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003601 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003602 if (info.isFailover()) {
3603 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3604 info.setFailover(false);
3605 }
3606 if (info.getReason() != null) {
3607 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3608 }
3609 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003610 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3611 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003612 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003613 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003614 return intent;
3615 }
3616
3617 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3618 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3619 }
3620
Michael Groover73f69482023-01-27 11:01:25 -06003621 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3622 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003623 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3624 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003625 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003626 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003627 if (!mSystemReady
3628 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003629 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003630 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003631 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003632 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003633 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003634 }
3635
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003636 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003637 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003638 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003639 final NetworkInfo ni = intent.getParcelableExtra(
3640 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003641 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3642 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003643 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003644 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003645 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003646 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003647 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003648 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003649 } finally {
3650 Binder.restoreCallingIdentity(ident);
3651 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003652 }
3653 }
3654
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003655 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3656 NetworkInfo info) {
3657 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003658 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003659
3660 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3661 try {
3662 // This allows us to discard older broadcasts still waiting to be delivered
3663 // which have the same namespace and key.
3664 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3665 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3666 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003667 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003668 } catch (UnsupportedApiLevelException e) {
3669 Log.wtf(TAG, "Using unsupported API" + e);
3670 }
3671 }
3672
3673 @VisibleForTesting
3674 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3675 final StringBuilder sb = new StringBuilder();
3676 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3677 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3678 sb.append(info.getExtraInfo());
3679 return sb.toString();
3680 }
3681
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003682 /**
Aaron Huang96011892020-06-27 07:18:23 +08003683 * Called by SystemServer through ConnectivityManager when the system is ready.
3684 */
3685 @Override
3686 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003687 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003688 throw new SecurityException("Calling Uid is not system uid.");
3689 }
3690 systemReadyInternal();
3691 }
3692
3693 /**
3694 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003695 */
3696 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003697 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003698 // Load flags after PackageManager is ready to query module version
3699 mFlags.loadFlags(mDeps, mContext);
3700
Aaron Huang9a57acf2020-12-08 10:03:29 +08003701 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3702 // listening network request which is sent by MultipathPolicyTracker won't be added
3703 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3704 // be called after PermissionMonitor#startMonitoring().
3705 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3706 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3707 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003708 final ConditionVariable startMonitoringDone = new ConditionVariable();
3709 mHandler.post(() -> {
3710 mPermissionMonitor.startMonitoring();
3711 startMonitoringDone.open();
3712 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003713 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003714 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003715
Hugo Benichie5220992017-04-26 14:53:28 +09003716 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003717 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003718 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003719 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003720 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003721 }
3722 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003723
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003724 // Create network requests for always-on networks.
3725 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003726
3727 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003728 // Note that updating can be skipped here if the list is empty only because no uid
3729 // rules are applied before system ready. Normally, the empty uid list means to clear
3730 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003731 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3732 updateMobileDataPreferredUids();
3733 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003734
3735 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003736 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003737 mBpfNetMaps.setPullAtomCallback(mContext);
3738 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003739 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3740 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003741 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3742 // have permission problem. While CV#block() is unbounded in time and can in principle block
3743 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3744 // could have blocked forever too.
3745 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003746 }
3747
The Android Open Source Project28527d22009-03-03 19:31:44 -08003748 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003749 * Start listening for default data network activity state changes.
3750 */
3751 @Override
3752 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003753 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003754 }
3755
3756 /**
3757 * Stop listening for default data network activity state changes.
3758 */
3759 @Override
3760 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003761 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003762 }
3763
3764 /**
3765 * Check whether the default network radio is currently active.
3766 */
3767 @Override
3768 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003769 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003770 }
3771
3772 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003773 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003774 * and set it on it's iface.
3775 */
Junyu Lai970963e2022-10-25 15:46:47 +08003776 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003777 final String iface = newLp.getInterfaceName();
3778 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003779 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003780 // Silently ignore unset MTU value.
3781 return;
3782 }
Hansen Kurli04252032022-12-07 11:21:49 +00003783 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3784 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3785 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003786 return;
3787 }
Hansen Kurli04252032022-12-07 11:21:49 +00003788 // Cannot set MTU without interface name
3789 if (TextUtils.isEmpty(iface)) {
3790 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003791 return;
3792 }
sy.yun4aa73922013-09-02 05:24:09 +09003793
Hansen Kurli04252032022-12-07 11:21:49 +00003794 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3795 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003796 return;
3797 }
3798
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003799 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003800 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003801 mNetd.interfaceSetMtu(iface, mtu);
3802 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003803 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003804 }
3805 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003806
Chenbo Feng15416292018-11-08 17:36:21 -08003807 @VisibleForTesting
3808 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003809
Junyu Lai970963e2022-10-25 15:46:47 +08003810 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003811 String[] values = null;
3812 if (tcpBufferSizes != null) {
3813 values = tcpBufferSizes.split(",");
3814 }
3815
3816 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003817 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003818 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3819 values = tcpBufferSizes.split(",");
3820 }
3821
3822 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3823
3824 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003825 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003826
Chenbo Feng15416292018-11-08 17:36:21 -08003827 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3828 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3829 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003830 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003831 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003832 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003833 }
3834 }
3835
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003836 @Override
3837 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003838 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003839 NETWORK_RESTORE_DELAY_PROP_NAME);
3840 if(restoreDefaultNetworkDelayStr != null &&
3841 restoreDefaultNetworkDelayStr.length() != 0) {
3842 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003843 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003844 } catch (NumberFormatException e) {
3845 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003846 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003847 // if the system property isn't set, use the value for the apn type
3848 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3849
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003850 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3851 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003852 }
3853 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003854 }
3855
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003856 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003857 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003858 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003859 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003860 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003861 // Start gathering diagnostic information.
3862 netDiags.add(new NetworkDiagnostics(
3863 nai.network,
3864 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003865 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003866 DIAG_TIME_MS));
3867 }
3868
3869 for (NetworkDiagnostics netDiag : netDiags) {
3870 pw.println();
3871 netDiag.waitForMeasurements();
3872 netDiag.dump(pw);
3873 }
3874 }
3875
The Android Open Source Project28527d22009-03-03 19:31:44 -08003876 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003877 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3878 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003879 if (!checkDumpPermission(mContext, TAG, writer)) return;
3880
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003881 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003882 }
3883
lucaslin99473f62020-12-10 15:10:54 +08003884 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3885 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3886 != PackageManager.PERMISSION_GRANTED) {
3887 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003888 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003889 + " due to missing android.permission.DUMP permission");
3890 return false;
3891 } else {
3892 return true;
3893 }
3894 }
3895
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003896 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003897 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003898
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003899 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003900 dumpNetworkDiagnostics(pw);
3901 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003902 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003903 dumpNetworks(pw);
3904 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003905 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003906 dumpNetworkRequests(pw);
3907 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003908 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3909 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3910 dumpTrafficController(pw, fd, verbose);
3911 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003912 }
Erik Kline9647f382015-06-05 17:47:34 +09003913
Junyu Lai0da479b2022-04-20 15:06:29 +08003914 pw.println("NetworkProviders for:");
3915 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003916 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003917 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003918 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003919 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003920 pw.println();
3921
Chalard Jean5b409c72021-02-04 13:12:59 +09003922 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003923 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003924 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003925 pw.println("none");
3926 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003927 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003928 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003929 pw.println();
3930
James Mattis8b298a02021-06-01 22:34:04 -07003931 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003932 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003933 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003934 pw.decreaseIndent();
3935 pw.println();
3936
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003937 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003938 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003939 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003940 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003941 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003942
junyulaif2c67e42018-08-07 19:50:45 +08003943 pw.println("Status for known UIDs:");
3944 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003945 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003946 for (int i = 0; i < size; i++) {
3947 // Don't crash if the array is modified while dumping in bugreports.
3948 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003949 final int uid = mUidBlockedReasons.keyAt(i);
3950 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3951 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003952 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003953 } catch (ArrayIndexOutOfBoundsException e) {
3954 pw.println(" ArrayIndexOutOfBoundsException");
3955 } catch (ConcurrentModificationException e) {
3956 pw.println(" ConcurrentModificationException");
3957 }
3958 }
3959 pw.println();
3960 pw.decreaseIndent();
3961
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003962 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003963 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003964 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003965 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003966 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003967
Junyu Lai0da479b2022-04-20 15:06:29 +08003968 pw.println("Network Offers:");
3969 pw.increaseIndent();
3970 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3971 pw.println(offerInfo.offer);
3972 }
3973 pw.decreaseIndent();
3974 pw.println();
3975
Robert Greenwalt94e22142014-07-30 16:31:24 -07003976 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003977
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003978 pw.println();
markchien5e866652019-09-30 14:40:57 +08003979 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003980
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003981 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003982 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003983
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003984 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003985 dumpCloseFrozenAppSockets(pw);
3986
3987 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003988 dumpBpfProgramStatus(pw);
3989
Chalard Jean53017782022-11-24 17:13:44 +09003990 if (null != mCarrierPrivilegeAuthenticator) {
3991 pw.println();
3992 mCarrierPrivilegeAuthenticator.dump(pw);
3993 }
3994
Junyu Lai155760b2023-10-05 14:51:00 +08003995 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003996
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003997 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003998 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003999 pw.println("mNetworkRequestInfoLogs (most recent first):");
4000 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004001 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09004002 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09004003
4004 pw.println();
4005 pw.println("mNetworkInfoBlockingLogs (most recent first):");
4006 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004007 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09004008 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09004009
4010 pw.println();
4011 pw.println("NetTransition WakeLock activity (most recent first):");
4012 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004013 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
4014 pw.println("total releases: " + mTotalWakelockReleases);
4015 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
4016 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
4017 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
4018 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4019 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
4020 }
James Mattiscb1e0362021-04-06 17:07:42 -07004021 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004022
4023 pw.println();
4024 pw.println("bandwidth update requests (by uid):");
4025 pw.increaseIndent();
4026 synchronized (mBandwidthRequests) {
4027 for (int i = 0; i < mBandwidthRequests.size(); i++) {
4028 pw.println("[" + mBandwidthRequests.keyAt(i)
4029 + "]: " + mBandwidthRequests.valueAt(i));
4030 }
4031 }
4032 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004033 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004034
James Mattiscb1e0362021-04-06 17:07:42 -07004035 pw.println();
4036 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4037 pw.increaseIndent();
4038 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004039 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004040 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004041
4042 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004043
4044 pw.println();
4045 pw.println("Permission Monitor:");
4046 pw.increaseIndent();
4047 mPermissionMonitor.dump(pw);
4048 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004049
4050 pw.println();
4051 pw.println("Legacy network activity:");
4052 pw.increaseIndent();
4053 mNetworkActivityTracker.dump(pw);
4054 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08004055 }
4056
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004057 private void dumpNetworks(IndentingPrintWriter pw) {
4058 for (NetworkAgentInfo nai : networksSortedById()) {
4059 pw.println(nai.toString());
4060 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004061 pw.println("Nat464Xlat:");
4062 pw.increaseIndent();
4063 nai.dumpNat464Xlat(pw);
4064 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004065 pw.println(String.format(
4066 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4067 nai.numForegroundNetworkRequests(),
4068 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4069 nai.numBackgroundNetworkRequests(),
4070 nai.numNetworkRequests()));
4071 pw.increaseIndent();
4072 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4073 pw.println(nai.requestAt(i).toString());
4074 }
4075 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004076 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004077 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004078 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004079 pw.decreaseIndent();
4080 pw.decreaseIndent();
4081 }
4082 }
4083
James Mattis8b298a02021-06-01 22:34:04 -07004084 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4085 if (!mProfileNetworkPreferences.isEmpty()) {
4086 pw.println("Profile preferences:");
4087 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004088 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004089 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004090 }
James Mattis8b298a02021-06-01 22:34:04 -07004091 if (!mOemNetworkPreferences.isEmpty()) {
4092 pw.println("OEM preferences:");
4093 pw.increaseIndent();
4094 pw.println(mOemNetworkPreferences);
4095 pw.decreaseIndent();
4096 }
4097 if (!mMobileDataPreferredUids.isEmpty()) {
4098 pw.println("Mobile data preferred UIDs:");
4099 pw.increaseIndent();
4100 pw.println(mMobileDataPreferredUids);
4101 pw.decreaseIndent();
4102 }
James Mattis45d81842021-01-10 14:24:24 -08004103
James Mattis8b298a02021-06-01 22:34:04 -07004104 pw.println("Default requests:");
4105 pw.increaseIndent();
4106 dumpPerAppDefaultRequests(pw);
4107 pw.decreaseIndent();
4108 }
4109
4110 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004111 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4112 if (mDefaultRequest == defaultRequest) {
4113 continue;
4114 }
4115
James Mattis8b298a02021-06-01 22:34:04 -07004116 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4117 final String networkOutput;
4118 if (null == satisfier) {
4119 networkOutput = "null";
4120 } else if (mNoServiceNetwork.equals(satisfier)) {
4121 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004122 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004123 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004124 }
James Mattis8b298a02021-06-01 22:34:04 -07004125 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4126 ? "" : " asUid: " + defaultRequest.mAsUid;
4127 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4128 + defaultRequest.mPid + asUidString + "]";
4129 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4130 + " Preference order: " + defaultRequest.mPreferenceOrder
4131 + " Tracked UIDs: " + defaultRequest.getUids();
4132 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004133 }
4134 }
4135
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004136 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004137 NetworkRequestInfo[] infos = null;
4138 while (infos == null) {
4139 try {
4140 infos = requestsSortedById();
4141 } catch (ConcurrentModificationException e) {
4142 // mNetworkRequests should only be accessed from handler thread, except dump().
4143 // As dump() is never called in normal usage, it would be needlessly expensive
4144 // to lock the collection only for its benefit. Instead, retry getting the
4145 // requests if ConcurrentModificationException is thrown during dump().
4146 }
4147 }
4148 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004149 pw.println(nri.toString());
4150 }
4151 }
4152
Ken Chene6d511f2022-01-25 11:10:42 +08004153 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4154 boolean verbose) {
4155 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004156 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004157 } catch (ServiceSpecificException e) {
4158 pw.println(e.getMessage());
4159 } catch (IOException e) {
4160 loge("Dump BPF maps failed, " + e);
4161 }
4162 }
4163
Chalard Jean524f0b12021-10-25 21:11:56 +09004164 private void dumpAllRequestInfoLogsToLogcat() {
4165 try (PrintWriter logPw = new PrintWriter(new Writer() {
4166 @Override
4167 public void write(final char[] cbuf, final int off, final int len) {
4168 // This method is called with 0-length and 1-length arrays for empty strings
4169 // or strings containing only the DEL character.
4170 if (len <= 1) return;
4171 Log.e(TAG, new String(cbuf, off, len));
4172 }
4173 @Override public void flush() {}
4174 @Override public void close() {}
4175 })) {
4176 mNetworkRequestInfoLogs.dump(logPw);
4177 }
4178 }
4179
Hugo Benichia480ba52018-09-03 08:19:02 +09004180 /**
4181 * Return an array of all current NetworkAgentInfos sorted by network id.
4182 */
4183 private NetworkAgentInfo[] networksSortedById() {
4184 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004185 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004186 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004187 return networks;
4188 }
4189
4190 /**
4191 * Return an array of all current NetworkRequest sorted by request id.
4192 */
James Mattis258ea3c2020-11-15 15:04:40 -08004193 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004194 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004195 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004196 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004197 // Sort the array based off the NRI containing the min requestId in its requests.
4198 Arrays.sort(requests,
4199 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4200 Comparator.comparingInt(req -> req.requestId)).requestId
4201 )
4202 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004203 return requests;
4204 }
4205
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004206 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004207 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004208 if (officialNai != null && officialNai.equals(nai)) return true;
4209 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004210 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004211 " - " + nai);
4212 }
4213 return false;
4214 }
4215
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004216 private boolean isDisconnectRequest(Message msg) {
4217 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4218 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4219 return info.getState() == NetworkInfo.State.DISCONNECTED;
4220 }
4221
Robert Greenwalt2034b912009-08-12 16:08:25 -07004222 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004223 private class NetworkStateTrackerHandler extends Handler {
4224 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004225 super(looper);
4226 }
4227
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004228 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004229 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4230 final NetworkAgentInfo nai = arg.first;
4231 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004232 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004233 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004234 }
4235 return;
4236 }
4237
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004238 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004239 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004240 return;
4241 }
4242
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004243 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004244 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004245 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4246 if (!nai.respectsNcStructuralConstraints(proposed)) {
4247 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4248 + nai.networkCapabilities + " -> " + proposed);
4249 disconnectAndDestroyNetwork(nai);
4250 return;
4251 }
4252 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004253 final NetworkCapabilities sanitized =
4254 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004255 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004256 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004257 break;
4258 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004259 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004260 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004261 processLinkPropertiesFromAgent(nai, newLp);
4262 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004263 break;
4264 }
4265 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004266 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004267 updateNetworkInfo(nai, info);
4268 break;
4269 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004270 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4271 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004272 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004273 break;
4274 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004275 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004276 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004277 break;
4278 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004279 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004280 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004281 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004282 // Note that if the NAI had been connected, this would affect the
4283 // score, and therefore would require re-mixing the score and performing
4284 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004285 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004286 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4287 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004288 // Mark the network as temporarily accepting partial connectivity so that it
4289 // will be validated (and possibly become default) even if it only provides
4290 // partial internet access. Note that if user connects to partial connectivity
4291 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4292 // out of wifi coverage) and if the same wifi is available again, the device
4293 // will auto connect to this wifi even though the wifi has "no internet".
4294 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004295 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004296 break;
4297 }
junyulai011b1f12019-01-03 18:50:15 +08004298 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004299 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004300 break;
4301 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004302 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004303 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004304 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004305
4306 if (isLegacyLockdownNai(nai)
4307 && (underlying == null || underlying.size() != 1)) {
4308 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4309 + " must have exactly one underlying network: " + underlying);
4310 }
4311
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004312 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4313 nai.declaredUnderlyingNetworks = (underlying != null)
4314 ? underlying.toArray(new Network[0]) : null;
4315
4316 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4317 if (DBG) {
4318 log(nai.toShortString() + " changed underlying networks to "
4319 + Arrays.toString(nai.declaredUnderlyingNetworks));
4320 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004321 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004322 notifyIfacesChangedForNetworkStats();
4323 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004324 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004325 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004326 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4327 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4328 nai.teardownDelayMs = msg.arg1;
4329 } else {
4330 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4331 }
Chalard Jean550b5212021-03-05 23:07:53 +09004332 break;
4333 }
4334 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4335 nai.setLingerDuration((int) arg.second);
4336 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004337 }
Tyler Wear72388212021-09-09 14:49:02 -07004338 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4339 DscpPolicy policy = (DscpPolicy) arg.second;
4340 if (mDscpPolicyTracker != null) {
4341 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4342 }
4343 break;
4344 }
4345 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4346 if (mDscpPolicyTracker != null) {
4347 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4348 }
4349 break;
4350 }
4351 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4352 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004353 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004354 }
4355 break;
4356 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004357 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004358 if (!nai.everConnected()) {
4359 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4360 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004361 teardownUnneededNetwork(nai);
4362 break;
4363 }
4364
4365 if (nai.isDestroyed()) {
4366 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4367 + ", ignoring");
4368 break;
4369 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004370
4371 final int timeoutMs = (int) arg.second;
4372 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4373 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4374 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4375 }
4376
4377 // Marking a network awaiting replacement is used to ensure that any requests
4378 // satisfied by the network do not switch to another network until a
4379 // replacement is available or the wait for a replacement times out.
4380 // If the network is inactive (i.e., nascent or lingering), then there are no
4381 // such requests, and there is no point keeping it. Just tear it down.
4382 // Note that setLingerDuration(0) cannot be used to do this because the network
4383 // could be nascent.
4384 nai.clearInactivityState();
4385 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4386 Log.d(TAG, nai.toShortString()
4387 + " marked awaiting replacement is unneeded, tearing down instead");
4388 teardownUnneededNetwork(nai);
4389 break;
4390 }
4391
4392 Log.d(TAG, "Marking " + nai.toShortString()
4393 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4394 destroyNativeNetwork(nai);
4395
4396 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4397 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4398 // consider the fact that the network could already have disconnected or been
4399 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4400 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4401 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4402 mKeepaliveTracker.handleStopAllKeepalives(nai,
4403 SocketKeepalive.ERROR_INVALID_NETWORK);
4404
4405 nai.updateScoreForNetworkAgentUpdate();
4406 // This rematch is almost certainly not going to result in any changes, because
4407 // the destroyed flag is only just above the "current satisfier wins"
4408 // tie-breaker. But technically anything that affects scoring should rematch.
4409 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004410 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004411 break;
4412 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004413 }
4414 }
4415
4416 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004417 final int netId = msg.arg2;
4418 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004419 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004420 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004421 switch (msg.what) {
4422 default:
4423 return false;
lucasline117e2e2019-10-22 18:27:33 +08004424 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004425 if (nai == null) {
4426 break;
4427 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004428 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4429 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004430 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004431 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004432 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004433 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004434 if (probePrivateDnsCompleted) {
4435 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4436 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004437 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004438 }
4439 // Only show the notification when the private DNS is broken and the
4440 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004441 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004442 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4443 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004444 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004445 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4446 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4447 // private DNS is broken, it means this network is being reevaluated.
4448 // Either probing private DNS is not necessary any more or it hasn't been
4449 // done yet. In either case, the networkCapabilities should be updated to
4450 // reflect the new status.
4451 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004452 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004453 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004454 }
4455 break;
4456 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004457 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004458 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4459
Erik Kline31b4a9e2018-01-11 21:07:29 +09004460 if (nai == null) break;
4461
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004462 handleNetworkTested(nai, results.mTestResult,
4463 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004464 break;
4465 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004466 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004467 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004468 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004469 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004470 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004471 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004472 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4473 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004474 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004475 if (nai == null) {
4476 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4477 break;
4478 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004479 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004480 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004481 (PendingIntent) msg.obj,
4482 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004483 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004484 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004485 break;
4486 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004487 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004488 if (nai == null) break;
4489
Erik Kline9a62f012018-03-21 07:18:33 -07004490 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004491 break;
4492 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004493 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004494 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004495 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004496 break;
4497 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004498 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004499 return true;
4500 }
4501
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004502 private void handleNetworkTested(
4503 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004504 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4505 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004506 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004507
4508 // If there is any kind of working networking, then the NAI has been evaluated
4509 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4510 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004511 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004512 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004513 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4514 // any callback that receives onAvailable for that rematch receives an extra caps
4515 // callback. To prevent that, update the score in the agent so the updates below won't
4516 // see an update to both caps and score at the same time.
4517 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004518 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4519
he_won.hwang881307a2022-03-15 21:23:52 +09004520 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4521 // Assume the validation failure is due to a temporary failure after roaming
4522 // and ignore it. NetworkMonitor will continue to retry validation. If it
4523 // continues to fail after the block timeout expires, the network will be
4524 // marked unvalidated. If it succeeds, then validation state will not change.
4525 return;
4526 }
4527
Chalard Jean254bd162022-08-25 13:04:51 +09004528 final boolean wasValidated = nai.isValidated();
4529 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004530 final boolean wasPortal = nai.captivePortalDetected();
4531 nai.setPartialConnectivity(partial);
4532 nai.setCaptivePortalDetected(portal);
4533 nai.updateScoreForNetworkAgentUpdate();
4534 final boolean partialConnectivityChanged = (wasPartial != partial);
4535 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004536
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004537 if (DBG) {
4538 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4539 ? " with redirect to " + redirectUrl
4540 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004541 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004542 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004543 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004544 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004545 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004546 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004547 if (valid) {
4548 handleFreshlyValidatedNetwork(nai);
4549 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4550 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004551 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004552 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004553 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004554 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004555 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004556 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004557 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004558 NotificationType.PRIVATE_DNS_BROKEN);
4559 // If network becomes valid, the hasShownBroken should be reset for
4560 // that network so that the notification will be fired when the private
4561 // DNS is broken again.
4562 nai.networkAgentConfig.hasShownBroken = false;
4563 }
4564 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004565 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004566 } else if (portalChanged) {
4567 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004568 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004569 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4570 nai.onPreventAutomaticReconnect();
4571 teardownUnneededNetwork(nai);
4572 return;
4573 } else {
4574 updateCapabilitiesForNetwork(nai);
4575 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004576 } else if (becameEvaluated) {
4577 // If valid or partial connectivity changed, updateCapabilities* has
4578 // done the rematch.
4579 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004580 }
4581 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004582
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004583 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004584 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004585 nai.onValidationStatusChanged(
4586 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4587 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004588
4589 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004590 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004591 // immediately. Re-notify partial connectivity silently if no internet
4592 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004593 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004594 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004595 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4596 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004597 }
4598
Chalard Jean254bd162022-08-25 13:04:51 +09004599 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004600 handleNetworkUnvalidated(nai);
4601 }
4602 }
4603
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004604 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4605 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4606 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4607 // Do not avoid captive portal when network is wear proxy.
4608 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4609 }
4610
Calvin Ondada1452016-10-11 15:10:46 -07004611 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004612 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4613 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004614 }
4615
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004616 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4617 switch (msg.what) {
4618 default:
4619 return false;
4620 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4621 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4622 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4623 handleLingerComplete(nai);
4624 }
4625 break;
4626 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004627 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4628 handleNetworkAgentRegistered(msg);
4629 break;
4630 }
4631 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4632 handleNetworkAgentDisconnected(msg);
4633 break;
4634 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004635 }
4636 return true;
4637 }
4638
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004639 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004640 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004641 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004642 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004643 maybeHandleNetworkAgentMessage(msg);
4644 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004645 }
4646 }
4647
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004648 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004649 private final int mNetId;
4650 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004651
4652 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004653 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004654 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004655 }
4656
4657 @Override
4658 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4659 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004660 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004661 }
4662
4663 @Override
4664 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004665 // Legacy version of notifyNetworkTestedWithExtras.
4666 // Would only be called if the system has a NetworkStack module older than the
4667 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004668 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004669 }
4670
4671 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004672 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004673 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4674 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004675 final Message msg = mTrackerHandler.obtainMessage(
4676 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004677 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004678 new NetworkTestedResults(
4679 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004680 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004681
4682 // Invoke ConnectivityReport generation for this Network test event.
4683 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4684 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004685
Cody Kestingf1120be2020-08-03 18:01:40 -07004686 // NetworkMonitor reports the network validation result as a bitmask while
4687 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4688 // logical value for ConnectivityDiagnostics.
4689 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4690 p.result);
4691
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004692 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004693 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004694 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4695 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4696
Aaron Huang959d3642021-01-21 15:47:41 +08004697 ConnectivityReportEvent reportEvent =
4698 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4699 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004700 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004701 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004702 }
4703
4704 @Override
4705 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4706 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4707 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004708 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004709 }
4710
4711 @Override
lucasline117e2e2019-10-22 18:27:33 +08004712 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4713 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4714 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004715 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004716 }
4717
4718 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004719 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4720 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4721 EVENT_CAPPORT_DATA_CHANGED,
4722 0, mNetId, data));
4723 }
4724
4725 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004726 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004727 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004728 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004729
4730 final PendingIntent pendingIntent;
4731 // Only the system server can register notifications with package "android"
4732 final long token = Binder.clearCallingIdentity();
4733 try {
paulhu7746e4e2020-06-09 19:07:03 +08004734 pendingIntent = PendingIntent.getBroadcast(
4735 mContext,
4736 0 /* requestCode */,
4737 intent,
4738 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004739 } finally {
4740 Binder.restoreCallingIdentity(token);
4741 }
4742 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4743 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004744 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004745 }
4746
4747 @Override
4748 public void hideProvisioningNotification() {
4749 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004750 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004751 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004752
4753 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004754 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004755 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004756 }
4757
4758 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004759 public int getInterfaceVersion() {
4760 return this.VERSION;
4761 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004762
4763 @Override
4764 public String getInterfaceHash() {
4765 return this.HASH;
4766 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004767 }
4768
Cody Kestingf1120be2020-08-03 18:01:40 -07004769 /**
4770 * Converts the given NetworkMonitor-specific validation result bitmask to a
4771 * ConnectivityDiagnostics-specific validation result int.
4772 */
4773 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4774 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4775 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4776 }
4777 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4778 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4779 }
4780 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4781 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4782 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4783 }
4784
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004785 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004786 log("Data stall detected with methods: " + p.detectionMethod);
4787
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004788 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004789 int detectionMethod = 0;
4790 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4791 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4792 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4793 }
4794 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4795 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4796 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4797 p.tcpMetricsCollectionPeriodMillis);
4798 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004799 }
4800
Cody Kestingf53a0752020-04-15 12:33:28 -07004801 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004802 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004803 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004804
4805 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4806 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4807 // the cost of going through two handlers.
4808 mConnectivityDiagnosticsHandler.sendMessage(msg);
4809 }
4810
Cody Kestingb37958e2020-05-15 10:36:01 -07004811 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4812 return (p.detectionMethod & detectionMethod) != 0;
4813 }
4814
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004815 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4816 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004817 }
4818
Erik Klinea73af002018-06-26 18:53:43 +09004819 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4820 if (nai == null) return;
4821 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4822 // in order to restart a validation pass from within netd.
4823 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00004824 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004825 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004826 }
4827 }
4828
Erik Kline31b4a9e2018-01-11 21:07:29 +09004829 private void handlePrivateDnsSettingsChanged() {
4830 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4831
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004832 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004833 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004834 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004835 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4836 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004837 }
4838 }
4839
Erik Kline9a62f012018-03-21 07:18:33 -07004840 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4841 // Private DNS only ever applies to networks that might provide
4842 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004843 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004844
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004845 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004846 // schedule DNS resolutions. If a DNS resolution is required the
4847 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004848 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004849
4850 // With Private DNS bypass support, we can proceed to update the
4851 // Private DNS config immediately, even if we're in strict mode
4852 // and have not yet resolved the provider name into a set of IPs.
4853 updatePrivateDns(nai, cfg);
4854 }
4855
4856 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4857 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004858 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004859 }
4860
dalyk1720e542018-03-05 12:42:22 -05004861 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4862 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4863 if (nai == null) {
4864 return;
4865 }
4866 mDnsManager.updatePrivateDnsValidation(update);
4867 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4868 }
4869
paulhu7c0a2e62021-01-08 00:51:49 +08004870 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004871 int prefixLength) {
4872 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4873 if (nai == null) return;
4874
paulhu7c0a2e62021-01-08 00:51:49 +08004875 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4876 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004877
4878 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004879 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004880 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004881 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004882 prefixLength);
4883 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004884 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004885 return;
4886 }
4887 }
4888
Lorenzo Colittid523d142020-04-01 20:16:30 +09004889 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004890 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4891 }
4892
Hai Shalome58bdc62021-01-11 18:45:34 -08004893 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004894 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004895 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004896 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4897 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4898 }
4899
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004900 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004901 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004902 * @param nai the agent info to update
4903 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004904 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004905 */
junyulai2b6f0c22021-02-03 20:15:30 +08004906 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4907 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4908 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004909 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004910 // one lingered request, set inactive.
4911 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004912 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004913 if (DBG) log("Unsetting inactive " + nai.toShortString());
4914 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004915 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004916 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004917 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004918 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4919 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004920 }
junyulai2b6f0c22021-02-03 20:15:30 +08004921 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004922 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004923 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004924 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004925 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004926 }
4927
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004928 private void handleNetworkAgentRegistered(Message msg) {
4929 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4930 if (!mNetworkAgentInfos.contains(nai)) {
4931 return;
4932 }
4933
4934 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4935 if (VDBG) log("NetworkAgent registered");
4936 } else {
4937 loge("Error connecting NetworkAgent");
4938 mNetworkAgentInfos.remove(nai);
4939 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004940 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004941 synchronized (mNetworkForNetId) {
4942 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004943 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004944 mNetIdManager.releaseNetId(nai.network.getNetId());
4945 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004946 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004947 }
4948 }
4949 }
Paul Jensend5f53392014-11-25 15:26:53 -05004950
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004951 @VisibleForTesting
4952 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004953 // The feature of creating the networks immediately was slated for U, but race conditions
4954 // detected late required this was flagged off.
4955 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4956 // in NetworkAgentTest.
4957 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004958 }
4959
4960 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4961 @NonNull NetworkInfo.State state) {
4962 if (nai.isCreated()) return false;
4963 if (state == NetworkInfo.State.CONNECTED) return true;
4964 if (state != NetworkInfo.State.CONNECTING) {
4965 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004966 if (shouldCreateNetworksImmediately()) {
4967 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4968 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004969 return false;
4970 }
4971 return nai.isVPN() || shouldCreateNetworksImmediately();
4972 }
4973
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004974 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004975 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004976 }
4977
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004978 @VisibleForTesting
4979 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004980 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004981 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004982
4983 // If the network never roamed, return false. The check below is not sufficient if time
4984 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4985 if (nai.lastRoamTime == 0) return false;
4986
he_won.hwang881307a2022-03-15 21:23:52 +09004987 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4988 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004989 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004990 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004991 final long currentTimeMs = SystemClock.elapsedRealtime();
4992 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004993 if (timeSinceLastRoam <= blockTimeOut) {
4994 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4995 return true;
4996 }
4997 }
4998 return false;
4999 }
5000
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005001 private void handleNetworkAgentDisconnected(Message msg) {
5002 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07005003 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005004 }
5005
Chalard Jeand9fffc32018-05-11 20:19:20 +09005006 // Destroys a network, remove references to it from the internal state managed by
5007 // ConnectivityService, free its interfaces and clean up.
5008 // Must be called on the Handler thread.
5009 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005010 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07005011
5012 if (!mNetworkAgentInfos.contains(nai)) return;
5013
Chalard Jeand9fffc32018-05-11 20:19:20 +09005014 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09005015 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005016 }
lucaslinb25c9a62019-02-12 15:30:13 +08005017 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005018 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005019 // A network agent has disconnected.
5020 // TODO - if we move the logic to the network agent (have them disconnect
5021 // because they lost all their requests or because their score isn't good)
5022 // then they would disconnect organically, report their new state and then
5023 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08005024 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005025 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
5026 null, null);
5027 }
Chalard Jean5b409c72021-02-04 13:12:59 +09005028 final boolean wasDefault = isDefaultNetwork(nai);
5029 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005030 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09005031 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005032 if (mTrackMultiNetworkActivities) {
5033 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
5034 // the network becomes no longer the default network.
5035 mNetworkActivityTracker.removeDataActivityTracking(nai);
5036 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005037 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005038 // If this was a local network forwarded to some upstream, or if some local network was
5039 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005040 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005041 // If this is a local network with an upstream selector, remove the associated network
5042 // request.
5043 if (nai.isLocalNetwork()) {
5044 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5045 if (null != selector) {
5046 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5047 }
5048 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005049 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5050 // by other networks that are already connected. Perhaps that can be done by
5051 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5052 // of rematchAllNetworksAndRequests
5053 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005054 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005055
5056 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005057 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5058 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005059 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005060 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005061 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005062 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005063 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005064 synchronized (mNetworkForNetId) {
5065 // Remove the NetworkAgent, but don't mark the netId as
5066 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005067 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005068 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005069 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005070 // Update allowed network lists in netd. This should be called after removing nai
5071 // from mNetworkAgentInfos.
5072 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005073 // Remove all previously satisfied requests.
5074 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005075 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005076 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005077 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005078 if (currentNetwork != null
5079 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005080 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005081 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5082 // rematch not to keep disconnected agents instead of setting it here ; this
5083 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005084 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005085 for (final NetworkOfferInfo noi : mNetworkOffers) {
5086 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005087 }
James Mattise3ef1912020-12-20 11:09:58 -08005088
Chalard Jean5b409c72021-02-04 13:12:59 +09005089 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005090 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005091 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005092 ensureNetworkTransitionWakelock(nai.toShortString());
5093 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005094 }
5095 }
junyulai2b6f0c22021-02-03 20:15:30 +08005096 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005097 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005098 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005099 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005100 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005101 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005102 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005103
Aaron Huang9fe47be2021-06-08 13:11:45 +08005104 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5105 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5106 // not called by the rematch in this case. This is because the code above unset
5107 // this network from the default request's satisfier, and that is what the rematch
5108 // is using as its source data to know what the old satisfier was. So as far as the
5109 // rematch above is concerned, the old default network was null.
5110 // Therefore if there is no new default, the default network was null and is still
5111 // null, thus there was no change so makeDefault() is not called. So if the old
5112 // network had a proxy and there is no new default, the proxy tracker should be told
5113 // that there is no longer a default proxy.
5114 // Strictly speaking this is not essential because having a proxy setting when
5115 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5116 mProxyTracker.setDefaultProxy(null);
5117 }
5118
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005119 // Immediate teardown.
5120 if (nai.teardownDelayMs == 0) {
5121 destroyNetwork(nai);
5122 return;
5123 }
5124
5125 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005126 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305127 try {
5128 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5129 } catch (RemoteException e) {
5130 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5131 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005132 }
5133 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5134 }
5135
5136 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005137 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005138 // Tell netd to clean up the configuration for this network
5139 // (routing rules, DNS, etc).
5140 // This may be slow as it requires a lot of netd shelling out to ip and
5141 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005142 // after we've rematched networks with requests (which might change the default
5143 // network or service a new request from an app), so network traffic isn't interrupted
5144 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005145 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005146 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005147 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005148 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5149 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5150 // false if the network was never created.
5151 // TODO: delete when S is no longer supported.
5152 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005153 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005154 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005155 }
5156
Chalard Jean1e4c2182023-10-06 18:45:53 +09005157 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005158 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005159 // Step 1 : maybe this network was the upstream for one or more local networks.
5160 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5161 if (!local.isLocalNetwork()) continue;
5162 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5163 if (null == selector) continue;
5164 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5165 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5166 // called after removing all associated NRIs from mNetworkRequests.
5167 if (null == nri) continue;
5168 final NetworkAgentInfo satisfier = nri.getSatisfier();
5169 if (disconnecting != satisfier) continue;
5170 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005171 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5172 // correctly contains null as an upstream.
5173 if (sendCallbacks) {
5174 nri.setSatisfier(null, null);
5175 notifyNetworkCallbacks(local,
5176 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5177 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005178 }
5179
5180 // Step 2 : maybe this is a local network that had an upstream.
5181 if (!disconnecting.isLocalNetwork()) return;
5182 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5183 if (null == selector) return;
5184 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5185 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5186 // is called after removing all associated NRIs from mNetworkRequests.
5187 if (null == nri) return;
5188 final NetworkAgentInfo satisfier = nri.getSatisfier();
5189 if (null == satisfier) return;
5190 removeLocalNetworkUpstream(disconnecting, satisfier);
5191 }
5192
5193 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5194 @NonNull final NetworkAgentInfo upstream) {
5195 try {
Yang Sun29037f62023-12-04 10:31:58 +08005196 final String localNetworkInterfaceName = localAgent.linkProperties.getInterfaceName();
5197 final String upstreamNetworkInterfaceName = upstream.linkProperties.getInterfaceName();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005198 mRoutingCoordinatorService.removeInterfaceForward(
Yang Sun29037f62023-12-04 10:31:58 +08005199 localNetworkInterfaceName,
5200 upstreamNetworkInterfaceName);
5201 disableMulticastRouting(localNetworkInterfaceName, upstreamNetworkInterfaceName);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005202 } catch (RemoteException e) {
5203 loge("Couldn't remove interface forward for "
5204 + localAgent.linkProperties.getInterfaceName() + " to "
5205 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5206 }
5207 }
5208
Ken Chen6df7a902021-04-09 15:08:42 +08005209 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005210 try {
5211 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005212 final NativeNetworkConfig config;
5213 if (nai.isVPN()) {
5214 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005215 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005216 return false;
5217 }
5218 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5219 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005220 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005221 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005222 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005223 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005224 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5225 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005226 getNetworkPermission(nai.networkCapabilities),
5227 false /* secure */,
5228 VpnManager.TYPE_VPN_NONE,
5229 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005230 }
Ken Chen6df7a902021-04-09 15:08:42 +08005231 mNetd.networkCreate(config);
5232 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005233 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5234 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005235 return true;
5236 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005237 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005238 return false;
5239 }
5240 }
5241
Ken Chen6df7a902021-04-09 15:08:42 +08005242 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005243 if (mDscpPolicyTracker != null) {
5244 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5245 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005246 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005247 // the interface is going to go away. Don't send the callbacks however ; if the network
5248 // was is being disconnected the callbacks have already been sent, and if it is being
5249 // destroyed pending replacement they will be sent when it is disconnected.
5250 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005251 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005252 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005253 } catch (RemoteException | ServiceSpecificException e) {
5254 loge("Exception destroying network(networkDestroy): " + e);
5255 }
5256 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005257 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005258 } catch (RemoteException | ServiceSpecificException e) {
5259 loge("Exception destroying network: " + e);
5260 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005261 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5262 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5263 // gets created, could add data to DnsManager data structures that will never get deleted.
5264 mDnsManager.removeNetwork(nai.network);
5265
5266 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005267 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005268 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5269 }
5270
Chalard Jean254bd162022-08-25 13:04:51 +09005271 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005272 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005273 }
5274
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005275 // If this method proves to be too slow then we can maintain a separate
5276 // pendingIntent => NetworkRequestInfo map.
5277 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5278 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005279 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5280 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5281 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005282 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005283 return entry.getValue();
5284 }
5285 }
5286 return null;
5287 }
5288
Chalard Jean524f0b12021-10-25 21:11:56 +09005289 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005290 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005291 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5292 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5293 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5294 // bug is fixed.
5295 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005296 throw new IllegalStateException("This NRI is already registered. New : " + nri
5297 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005298 }
5299 }
5300 }
5301 }
5302
Chalard Jeanac9ace02022-01-26 16:54:05 +09005303 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5304 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005305 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09005306 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09005307 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005308 }
5309 return false;
5310 }
5311
James Mattisf7027322020-12-13 16:28:14 -08005312 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005313 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005314 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5315 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5316 final NetworkRequestInfo existingRequest =
5317 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005318 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005319 if (DBG) {
5320 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5321 + nri.mRequests.get(0) + " because their intents matched.");
5322 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005323 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005324 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005325 }
Erik Kline05f2b402015-04-30 12:58:40 +09005326 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005327 }
5328
James Mattisf7027322020-12-13 16:28:14 -08005329 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005330 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005331 }
5332
James Mattis3ce3d3c2021-02-09 18:18:28 -08005333 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005334 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005335 for (final NetworkRequestInfo nri : nris) {
5336 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005337 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005338 for (final NetworkRequest req : nri.mRequests) {
5339 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005340 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005341 if (req.isListen()) {
5342 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5343 if (req.networkCapabilities.hasSignalStrength()
5344 && network.satisfiesImmutableCapabilitiesOf(req)) {
5345 updateSignalStrengthThresholds(network, "REGISTER", req);
5346 }
James Mattisf7027322020-12-13 16:28:14 -08005347 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005348 }
5349 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005350
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005351 // If this NRI has a satisfier already, it is replacing an older request that
5352 // has been removed. Track it.
5353 final NetworkRequest activeRequest = nri.getActiveRequest();
5354 if (null != activeRequest) {
5355 // If there is an active request, then for sure there is a satisfier.
5356 nri.getSatisfier().addRequest(activeRequest);
5357 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005358 }
James Mattisf7027322020-12-13 16:28:14 -08005359
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005360 if (mFlags.noRematchAllRequestsOnRegister()) {
5361 rematchNetworksAndRequests(nris);
5362 } else {
5363 rematchAllNetworksAndRequests();
5364 }
James Mattis45d81842021-01-10 14:24:24 -08005365
Chalard Jean0354d8c2021-01-12 10:58:56 +09005366 // Requests that have not been matched to a network will not have been sent to the
5367 // providers, because the old satisfier and the new satisfier are the same (null in this
5368 // case). Send these requests to the providers.
5369 for (final NetworkRequestInfo nri : nris) {
5370 for (final NetworkOfferInfo noi : mNetworkOffers) {
5371 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005372 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005373 }
5374 }
5375
James Mattisf7027322020-12-13 16:28:14 -08005376 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5377 final int callingUid) {
5378 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005379 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005380 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5381 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5382 handleReleaseNetworkRequest(
5383 nri.mRequests.get(0),
5384 callingUid,
5385 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005386 }
5387 }
5388
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005389 // Determines whether the network is the best (or could become the best, if it validated), for
5390 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5391 // on the value of reason:
5392 //
5393 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5394 // then it should be torn down.
5395 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5396 // then it should be lingered.
5397 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005398 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005399
Chalard Jean254bd162022-08-25 13:04:51 +09005400 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005401 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5402 return false;
5403 }
5404
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005405 final int numRequests;
5406 switch (reason) {
5407 case TEARDOWN:
5408 numRequests = nai.numRequestNetworkRequests();
5409 break;
5410 case LINGER:
5411 numRequests = nai.numForegroundNetworkRequests();
5412 break;
5413 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005414 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005415 return true;
5416 }
5417
Chalard Jean947acd42021-03-08 22:29:27 +09005418 if (numRequests > 0) return false;
5419
Paul Jensende49eb12015-06-25 15:30:08 -04005420 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005421 if (reason == UnneededFor.LINGER
5422 && !nri.isMultilayerRequest()
5423 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005424 // Background requests don't affect lingering.
5425 continue;
5426 }
5427
James Mattis3d229892020-11-16 16:46:28 -08005428 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005429 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005430 }
5431 }
Paul Jensende49eb12015-06-25 15:30:08 -04005432 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005433 }
5434
James Mattis3d229892020-11-16 16:46:28 -08005435 private boolean isNetworkPotentialSatisfier(
5436 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005437 // While destroyed network sometimes satisfy requests (including occasionally newly
5438 // satisfying requests), *potential* satisfiers are networks that might beat a current
5439 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5440 // because it's never a good idea to keep a destroyed network in case it validates.
5441 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5442 // candidate after it's been replaced by another unvalidated network.
5443 if (candidate.isDestroyed()) return false;
5444 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005445 // request, return immediately. For multilayer requests, check to see if any of the
5446 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005447 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5448 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005449 return false;
5450 }
5451 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005452 // This multilayer listen request is satisfied therefore no further requests need to be
5453 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005454 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005455 return false;
5456 }
James Mattis3d229892020-11-16 16:46:28 -08005457 // As non-multilayer listen requests have already returned, the below would only happen
5458 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005459 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005460 continue;
5461 }
Chalard Jean80685f42023-10-30 18:31:27 +09005462 // If there is hope for this network might validate and subsequently become the best
5463 // network for that request, then it is needed. Note that this network can't already
5464 // be the best for this request, or it would be the current satisfier, and therefore
5465 // there would be no need to call this method to find out if it is a *potential*
5466 // satisfier ("unneeded", the only caller, only calls this if this network currently
5467 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005468 if (candidate.satisfies(req)) {
5469 // As soon as a network is found that satisfies a request, return. Specifically for
5470 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5471 // is important so as to not evaluate lower priority requests further in
5472 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005473 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5474 ? nri.getSatisfier() : null;
5475 // Note that this catches two important cases:
5476 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5477 // is currently satisfying the request. This is desirable when
5478 // cellular ends up validating but WiFi does not.
5479 // 2. Unvalidated WiFi will not be reaped when validated cellular
5480 // is currently satisfying the request. This is desirable when
5481 // WiFi ends up validating and out scoring cellular.
5482 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005483 }
5484 }
5485
5486 return false;
5487 }
5488
Erik Kline0c04b742016-07-07 16:50:58 +09005489 private NetworkRequestInfo getNriForAppRequest(
5490 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005491 // Looking up the app passed param request in mRequests isn't possible since it may return
5492 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5493 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005494 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5495 // to avoid potential race conditions when validating a package->uid mapping when sending
5496 // the callback on the very low-chance that an application shuts down prior to the callback
5497 // being sent.
5498 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5499 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005500
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005501 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005502 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005503 log(String.format("UID %d attempted to %s for unowned request %s",
5504 callingUid, requestedOperation, nri));
5505 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005506 }
Erik Kline0c04b742016-07-07 16:50:58 +09005507 }
5508
5509 return nri;
5510 }
5511
James Mattisf7027322020-12-13 16:28:14 -08005512 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5513 final String callingMethod) {
5514 if (nri.isMultilayerRequest()) {
5515 throw new IllegalStateException(
5516 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005517 }
5518 }
5519
James Mattisf7027322020-12-13 16:28:14 -08005520 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005521 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005522 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5523 // single NetworkRequest and thus does not apply to multilayer requests.
5524 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5525 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005526 return;
5527 }
James Mattis2516da32021-01-31 17:06:19 -08005528 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005529 return;
5530 }
James Mattisf7027322020-12-13 16:28:14 -08005531 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5532 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005533 }
5534 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005535 callCallbackForRequest(
5536 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005537 }
5538
James Mattisf7027322020-12-13 16:28:14 -08005539 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5540 final int callingUid,
5541 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005542 final NetworkRequestInfo nri =
5543 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5544 if (nri == null) {
5545 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005546 }
James Mattisf7027322020-12-13 16:28:14 -08005547 if (VDBG || (DBG && request.isRequest())) {
5548 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005549 }
5550 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005551 if (callOnUnavailable) {
5552 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5553 }
Erik Kline155a59a2015-11-25 12:49:38 +09005554 }
Erik Kline0c04b742016-07-07 16:50:58 +09005555
James Mattisa076c532020-12-02 14:12:41 -08005556 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005557 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005558 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005559 if (null == mNetworkRequests.remove(req)) {
5560 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5561 continue;
5562 }
James Mattisa076c532020-12-02 14:12:41 -08005563 if (req.isListen()) {
5564 removeListenRequestFromNetworks(req);
5565 }
5566 }
James Mattis8f036802021-06-20 16:26:01 -07005567 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005568 if (mDefaultNetworkRequests.remove(nri)) {
5569 // If this request was one of the defaults, then the UID rules need to be updated
5570 // WARNING : if the app(s) for which this network request is the default are doing
5571 // traffic, this will kill their connected sockets, even if an equivalent request
5572 // is going to be reinstated right away ; unconnected traffic will go on the default
5573 // until the new default is set, which will happen very soon.
5574 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5575 // remove ranges for those requests that won't have a replacement
5576 final NetworkAgentInfo satisfier = nri.getSatisfier();
5577 if (null != satisfier) {
5578 try {
paulhu0e79d952021-06-09 16:11:35 +08005579 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5580 satisfier.network.getNetId(),
5581 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005582 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005583 } catch (RemoteException e) {
5584 loge("Exception setting network preference default network", e);
5585 }
5586 }
5587 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005588
Junyu Lai00d92df2022-07-05 11:01:52 +08005589 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005590 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005591 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005592
5593 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005594 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005595 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005596 }
5597 }
5598
Chalard Jean0354d8c2021-01-12 10:58:56 +09005599 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5600 // needed for this offer.
5601 for (final NetworkOfferInfo noi : mNetworkOffers) {
5602 for (final NetworkRequest req : nri.mRequests) {
5603 if (req.isRequest() && noi.offer.neededFor(req)) {
5604 noi.offer.onNetworkUnneeded(req);
5605 }
5606 }
5607 }
James Mattisa076c532020-12-02 14:12:41 -08005608 }
5609
James Mattis3ce3d3c2021-02-09 18:18:28 -08005610 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5611 for (final NetworkRequestInfo nri : nris) {
5612 if (mDefaultRequest == nri) {
5613 // Make sure we never remove the default request.
5614 continue;
5615 }
5616 handleRemoveNetworkRequest(nri);
5617 }
5618 }
5619
James Mattisa076c532020-12-02 14:12:41 -08005620 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5621 // listens don't have a singular affected Network. Check all networks to see
5622 // if this listen request applies and remove it.
5623 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5624 nai.removeRequest(req.requestId);
5625 if (req.networkCapabilities.hasSignalStrength()
5626 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5627 updateSignalStrengthThresholds(nai, "RELEASE", req);
5628 }
5629 }
5630 }
5631
5632 /**
5633 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5634 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5635 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5636 */
5637 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5638 boolean wasKept = false;
5639 final NetworkAgentInfo nai = nri.getSatisfier();
5640 if (nai != null) {
5641 final int requestLegacyType = nri.getActiveRequest().legacyType;
5642 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5643 nai.removeRequest(nri.getActiveRequest().requestId);
5644 if (VDBG || DDBG) {
5645 log(" Removing from current network " + nai.toShortString()
5646 + ", leaving " + nai.numNetworkRequests() + " requests.");
5647 }
5648 // If there are still lingered requests on this network, don't tear it down,
5649 // but resume lingering instead.
5650 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005651 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005652 notifyNetworkLosing(nai, now);
5653 }
5654 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5655 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5656 teardownUnneededNetwork(nai);
5657 } else {
5658 wasKept = true;
5659 }
James Mattisa076c532020-12-02 14:12:41 -08005660 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5661 // Went from foreground to background.
5662 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005663 }
5664
Erik Kline0c04b742016-07-07 16:50:58 +09005665 // Maintain the illusion. When this request arrived, we might have pretended
5666 // that a network connected to serve it, even though the network was already
5667 // connected. Now that this request has gone away, we might have to pretend
5668 // that the network disconnected. LegacyTypeTracker will generate that
5669 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005670 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005671 boolean doRemove = true;
5672 if (wasKept) {
5673 // check if any of the remaining requests for this network are for the
5674 // same legacy type - if so, don't remove the nai
5675 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5676 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005677 if (otherRequest.legacyType == requestLegacyType
5678 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005679 if (DBG) log(" still have other legacy request - leaving");
5680 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005681 }
5682 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005683 }
5684
Erik Kline0c04b742016-07-07 16:50:58 +09005685 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005686 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005687 }
5688 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005689 }
5690 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005691
Junyu Lai00d92df2022-07-05 11:01:52 +08005692 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005693 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005694 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5695 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5696 }
5697
Lorenzo Colittid6459092016-07-04 12:55:44 +09005698 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005699 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005700 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005701 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005702 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005703 }
5704
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005705 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005706 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5707 enforceNetworkStackSettingsOrSetup();
5708 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5709 encodeBool(accept), encodeBool(always), network));
5710 }
5711
5712 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005713 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005714 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005715 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5716 }
5717
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005718 @Override
5719 public void setTestAllowBadWifiUntil(long timeMs) {
5720 enforceSettingsPermission();
5721 if (!Build.isDebuggable()) {
5722 throw new IllegalStateException("Does not support in non-debuggable build");
5723 }
5724
5725 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5726 throw new IllegalArgumentException("It should not exceed "
5727 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5728 }
5729
5730 mHandler.sendMessage(
5731 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5732 }
5733
chiachangwange0192a72023-02-06 13:25:01 +00005734 @Override
5735 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5736 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005737
5738 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5739 throw new IllegalArgumentException("Argument should not exceed "
5740 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5741 }
5742
5743 mHandler.sendMessage(
5744 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5745 }
5746
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005747 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5748 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5749 " accept=" + accept + " always=" + always);
5750
5751 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5752 if (nai == null) {
5753 // Nothing to do.
5754 return;
5755 }
5756
Chalard Jean254bd162022-08-25 13:04:51 +09005757 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005758 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005759 return;
5760 }
5761
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005762 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005763 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005764 }
5765
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005766 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5767 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005768 // If network becomes partial connectivity and user already accepted to use this
5769 // network, we should respect the user's option and don't need to popup the
5770 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005771 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005772 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005773 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005774 }
5775
5776 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005777 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005778 }
5779
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005780 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005781 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005782 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005783 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005784 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005785 }
5786
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005787 }
5788
lucaslin2240ef62019-03-12 13:08:03 +08005789 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5790 boolean always) {
5791 if (DBG) {
5792 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5793 + " always=" + always);
5794 }
5795
5796 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5797 if (nai == null) {
5798 // Nothing to do.
5799 return;
5800 }
5801
Chalard Jean254bd162022-08-25 13:04:51 +09005802 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005803 // The network validated while the dialog box was up. Take no action.
5804 return;
5805 }
5806
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005807 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5808 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005809 }
5810
5811 // TODO: Use the current design or save the user choice into IpMemoryStore.
5812 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005813 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005814 }
5815
5816 if (!accept) {
5817 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005818 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005819 // Tear down the network.
5820 teardownUnneededNetwork(nai);
5821 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005822 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5823 // result in a partial connectivity result which will be processed by
5824 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005825 //
5826 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5827 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005828 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005829 }
5830 }
5831
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005832 private void handleSetAvoidUnvalidated(Network network) {
5833 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005834 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005835 // Nothing to do. The network either disconnected or revalidated.
5836 return;
5837 }
Chalard Jean254bd162022-08-25 13:04:51 +09005838 if (0L == nai.getAvoidUnvalidated()) {
5839 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005840 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005841 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005842 }
5843 }
5844
Chalard Jean5fb43c72022-09-08 19:03:14 +09005845 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005846 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005847 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005848 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005849 }
5850
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005851 @Override
5852 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005853 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005854 mHandler.post(() -> {
5855 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5856 if (nai == null) return;
5857 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005858 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005859 });
5860 }
5861
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005862 /**
5863 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5864 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005865 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005866 * @param appExtras Bundle to use as intent extras for the captive portal application.
5867 * Must be treated as opaque to avoid preventing the captive portal app to
5868 * update its arguments.
5869 */
5870 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005871 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005872 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5873 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005874
5875 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5876 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005877 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5878 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005879 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5880
lucaslin75ff7022020-12-17 04:14:35 +08005881 final long token = Binder.clearCallingIdentity();
5882 try {
5883 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5884 } finally {
5885 Binder.restoreCallingIdentity(token);
5886 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005887 }
5888
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005889 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5890 private final Network mNetwork;
5891
5892 private CaptivePortalImpl(Network network) {
5893 mNetwork = network;
5894 }
5895
5896 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005897 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005898 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5899 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005900 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5901 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5902 // Since the network will be disconnected, skip notifying NetworkMonitor
5903 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005904 }
5905
Chiachang Wang938bfba2020-01-09 13:50:55 +08005906 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005907 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005908 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005909 }
5910
5911 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005912 public void appRequest(final int request) {
5913 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5914 if (nm == null) return;
5915
5916 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005917 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005918 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005919 }
5920 }
5921
5922 @Nullable
5923 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5924 // getNetworkAgentInfoForNetwork is thread-safe
5925 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5926 if (nai == null) return null;
5927
5928 // nai.networkMonitor() is thread-safe
5929 return nai.networkMonitor();
5930 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005931 }
5932
Hugo Benichic9048bc2016-09-14 23:23:08 +00005933 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005934 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005935 }
5936
Chalard Jean020b93a2022-09-01 13:20:14 +09005937 private boolean activelyPreferBadWifi() {
5938 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5939 }
5940
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005941 /**
5942 * Return whether the device should maintain continuous, working connectivity by switching away
5943 * from WiFi networks having no connectivity.
5944 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5945 */
5946 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005947 if (!checkNetworkStackPermission()) {
5948 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5949 }
5950 return avoidBadWifi();
5951 }
5952
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005953 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005954 ensureRunningOnConnectivityServiceThread();
5955 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005956 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005957 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005958 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005959 if (avoidBadWifi) {
5960 // If the device is now avoiding bad wifi, remove notifications that might have
5961 // been put up when the device didn't.
5962 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5963 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005964 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005965 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5966 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5967 for (final NetworkOfferInfo noi : offersToUpdate) {
5968 updateOfferScore(noi.offer);
5969 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005970 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005971 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005972 }
5973
Erik Kline95ecfee2016-10-02 18:02:14 +09005974 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005975 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005976 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005977 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005978 if (!configRestrict) {
5979 pw.println("Bad Wi-Fi avoidance: unrestricted");
5980 return;
5981 }
5982
5983 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5984 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005985 pw.println("Config restrict: " + configRestrict);
5986 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005987
Chalard Jeane0fdea32022-09-14 21:44:22 +09005988 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005989 String description;
5990 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005991 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005992 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005993 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005994 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005995 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005996 description = "avoid";
5997 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005998 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005999 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09006000 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00006001
6002 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
6003 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09006004 if (null == configValue) {
6005 description = "unset";
6006 } else if (configValue) {
6007 description = "force true";
6008 } else {
6009 description = "force false";
6010 }
6011 pw.println("Actively prefer bad wifi conf: " + description);
6012 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006013 pw.println("Network overrides:");
6014 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09006015 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09006016 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09006017 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006018 }
6019 }
6020 pw.decreaseIndent();
6021 pw.decreaseIndent();
6022 }
6023
paulhu7746e4e2020-06-09 19:07:03 +08006024 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
6025 // unify the method.
6026 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
6027 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
6028 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
6029 return settingsComponent != null
6030 ? settingsComponent.getPackageName() : "com.android.settings";
6031 }
6032
lucaslinb1e8e382019-01-24 15:55:30 +08006033 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006034 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006035 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006036 switch (type) {
6037 case NO_INTERNET:
6038 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006039 // High priority because it is only displayed for explicitly selected networks.
6040 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006041 break;
lucasline117e2e2019-10-22 18:27:33 +08006042 case PRIVATE_DNS_BROKEN:
6043 action = Settings.ACTION_WIRELESS_SETTINGS;
6044 // High priority because we should let user know why there is no internet.
6045 highPriority = true;
6046 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006047 case LOST_INTERNET:
6048 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006049 // High priority because it could help the user avoid unexpected data usage.
6050 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006051 break;
lucaslin2240ef62019-03-12 13:08:03 +08006052 case PARTIAL_CONNECTIVITY:
6053 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006054 // Don't bother the user with a high-priority notification if the network was not
6055 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006056 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006057 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006058 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006059 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006060 return;
6061 }
6062
6063 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006064 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006065 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006066 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006067 // Some OEMs have their own Settings package. Thus, need to get the current using
6068 // Settings package name instead of just use default name "com.android.settings".
6069 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6070 intent.setClassName(settingsPkgName,
6071 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006072 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006073
paulhu2af50222020-10-11 22:52:27 +08006074 PendingIntent pendingIntent = PendingIntent.getActivity(
6075 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006076 0 /* requestCode */,
6077 intent,
paulhu2af50222020-10-11 22:52:27 +08006078 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006079
Serik Beketayevec8ad212020-12-07 22:43:07 -08006080 mNotifier.showNotification(
6081 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006082 }
6083
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006084 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6085 // Don't prompt if the network is validated, and don't prompt on captive portals
6086 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006087 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006088 return false;
6089 }
6090
6091 // If a network has partial connectivity, always prompt unless the user has already accepted
6092 // partial connectivity and selected don't ask again. This ensures that if the device
6093 // automatically connects to a network that has partial Internet access, the user will
6094 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006095 // because we have prompted them.
6096 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006097 return true;
6098 }
6099
6100 // If a network has no Internet access, only prompt if the network was explicitly selected
6101 // and if the user has not already told us to use the network regardless of whether it
6102 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006103 if (nai.networkAgentConfig.explicitlySelected
6104 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006105 return true;
6106 }
6107
6108 return false;
6109 }
6110
Chalard Jean5fb43c72022-09-08 19:03:14 +09006111 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6112 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006113
Chalard Jean5fb43c72022-09-08 19:03:14 +09006114 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6115 if (null == nai) return;
6116
6117 if (nai.setEvaluated()) {
6118 // If setEvaluated() returned true, the network never had any form of connectivity.
6119 // This may have an impact on request matching if bad WiFi avoidance is off and the
6120 // network was found not to have Internet access.
6121 nai.updateScoreForNetworkAgentUpdate();
6122 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006123
6124 // Also, if this is WiFi and it should be preferred actively, now is the time to
6125 // prompt the user that they walked past and connected to a bad WiFi.
6126 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6127 && !avoidBadWifi()
6128 && activelyPreferBadWifi()) {
6129 // The notification will be removed if the network validates or disconnects.
6130 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6131 return;
6132 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006133 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006134
Chalard Jean5fb43c72022-09-08 19:03:14 +09006135 if (!shouldPromptUnvalidated(nai)) return;
6136
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006137 // Stop automatically reconnecting to this network in the future. Automatically connecting
6138 // to a network that provides no or limited connectivity is not useful, because the user
6139 // cannot use that network except through the notification shown by this method, and the
6140 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006141 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006142
Chalard Jean254bd162022-08-25 13:04:51 +09006143 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006144 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006145 } else {
6146 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6147 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006148 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006149
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006150 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6151 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006152 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006153
lucaslin2240ef62019-03-12 13:08:03 +08006154 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6155 return;
6156 }
6157
6158 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006159 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006160 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006161 }
6162
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006163 @Override
6164 public int getMultipathPreference(Network network) {
6165 enforceAccessPermission();
6166
6167 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006168 if (nai != null && nai.networkCapabilities
6169 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006170 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6171 }
6172
Aaron Huang9a57acf2020-12-08 10:03:29 +08006173 final NetworkPolicyManager netPolicyManager =
6174 mContext.getSystemService(NetworkPolicyManager.class);
6175
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006176 final long token = Binder.clearCallingIdentity();
6177 final int networkPreference;
6178 try {
6179 networkPreference = netPolicyManager.getMultipathPreference(network);
6180 } finally {
6181 Binder.restoreCallingIdentity(token);
6182 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006183 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006184 return networkPreference;
6185 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006186 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6187 }
6188
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006189 @Override
6190 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006191 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006192 }
6193
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006194 private class InternalHandler extends Handler {
6195 public InternalHandler(Looper looper) {
6196 super(looper);
6197 }
6198
6199 @Override
6200 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006201 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006202 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006203 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006204 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006205 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006206 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006207 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006208 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006209 break;
6210 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006211 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006212 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006213 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006214 break;
6215 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006216 case EVENT_REGISTER_NETWORK_PROVIDER: {
6217 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006218 break;
6219 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006220 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6221 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006222 break;
6223 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006224 case EVENT_REGISTER_NETWORK_OFFER: {
6225 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6226 break;
6227 }
6228 case EVENT_UNREGISTER_NETWORK_OFFER: {
6229 final NetworkOfferInfo offer =
6230 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6231 if (null != offer) {
6232 handleUnregisterNetworkOffer(offer);
6233 }
6234 break;
6235 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006236 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006237 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6238 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6239 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006240 break;
6241 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006242 case EVENT_REGISTER_NETWORK_REQUEST:
6243 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006244 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006245 break;
6246 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006247 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6248 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006249 handleRegisterNetworkRequestWithIntent(msg);
6250 break;
6251 }
Erik Kline155a59a2015-11-25 12:49:38 +09006252 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6253 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6254 handleTimedOutNetworkRequest(nri);
6255 break;
6256 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006257 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6258 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6259 break;
6260 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006261 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006262 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6263 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006264 break;
6265 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006266 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006267 Network network = (Network) msg.obj;
6268 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006269 break;
6270 }
lucaslin2240ef62019-03-12 13:08:03 +08006271 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6272 Network network = (Network) msg.obj;
6273 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6274 toBool(msg.arg2));
6275 break;
6276 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006277 case EVENT_SET_AVOID_UNVALIDATED: {
6278 handleSetAvoidUnvalidated((Network) msg.obj);
6279 break;
6280 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006281 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6282 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006283 break;
6284 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006285 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6286 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006287 break;
6288 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006289 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6290 // handler thread.
6291 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006292 mKeepaliveTracker.handleStartKeepalive(msg);
6293 break;
6294 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006295 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006296 final AutomaticOnOffKeepalive ki =
6297 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6298 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006299
chiachangwang676c84e2023-02-14 09:22:05 +00006300 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006301 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006302 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006303 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006304 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6305 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006306 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6307 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006308 }
6309 }
6310
6311 // If the network no longer exists, then the keepalive should have been
6312 // cleaned up already. There is no point trying to resume keepalives.
6313 if (!networkFound) return;
6314
chiachangwang676c84e2023-02-14 09:22:05 +00006315 if (underpinnedNetworkFound) {
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006316 final NetworkCapabilities underpinnedNc =
6317 getNetworkCapabilitiesInternal(underpinnedNetwork);
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006318 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006319 underpinnedNetwork.netId, underpinnedNc.getUids());
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006320 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006321 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006322 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006323 }
6324 break;
6325 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006326 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006327 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006328 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6329 (IBinder) msg.obj);
6330 if (ki == null) {
6331 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006332 return;
6333 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006334 final int reason = msg.arg2;
6335 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006336 break;
6337 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006338 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6339 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6340 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006341 break;
6342 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006343 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6344 handlePrivateDnsSettingsChanged();
6345 break;
dalyk1720e542018-03-05 12:42:22 -05006346 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6347 handlePrivateDnsValidationUpdate(
6348 (PrivateDnsValidationUpdate) msg.obj);
6349 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006350 case EVENT_UID_BLOCKED_REASON_CHANGED:
6351 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006352 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006353 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6354 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6355 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006356 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006357 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6358 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006359 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006360 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006361 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006362 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006363 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6364 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006365 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006366 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006367 }
lucaslin1193a5d2021-01-21 02:04:15 +08006368 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006369 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006370 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006371 break;
paulhu51f77dc2021-06-07 02:34:20 +00006372 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6373 handleMobileDataPreferredUidsChanged();
6374 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006375 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6376 final long timeMs = ((Long) msg.obj).longValue();
6377 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6378 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006379 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6380 handleIngressRateLimitChanged();
6381 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006382 case EVENT_USER_DOES_NOT_WANT:
6383 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6384 if (nai == null) break;
6385 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006386 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006387 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006388 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6389 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6390 break;
chiachangwange0192a72023-02-06 13:25:01 +00006391 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6392 final long time = ((Long) msg.obj).longValue();
6393 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6394 break;
6395 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006396 case EVENT_UID_FROZEN_STATE_CHANGED:
6397 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6398 handleFrozenUids(args.mUids, args.mFrozenStates);
6399 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006400 }
6401 }
6402 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006403
Lorenzo Colittid6459092016-07-04 12:55:44 +09006404 @Override
markchien5776f962019-12-16 20:15:20 +08006405 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006406 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006407 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006408 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6409 Context.TETHERING_SERVICE);
6410 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006411 }
6412
Lorenzo Colittid6459092016-07-04 12:55:44 +09006413 @Override
markchien5776f962019-12-16 20:15:20 +08006414 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006415 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006416 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006417 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6418 Context.TETHERING_SERVICE);
6419 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006420 }
6421
Lorenzo Colittid6459092016-07-04 12:55:44 +09006422 @Override
markchien5776f962019-12-16 20:15:20 +08006423 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006424 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006425 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006426 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6427 Context.TETHERING_SERVICE);
6428 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006429 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006430
markchien5776f962019-12-16 20:15:20 +08006431
Lorenzo Colittid6459092016-07-04 12:55:44 +09006432 @Override
markchien5776f962019-12-16 20:15:20 +08006433 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006434 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006435 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006436 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6437 Context.TETHERING_SERVICE);
6438
6439 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006440 }
6441
Lorenzo Colittid6459092016-07-04 12:55:44 +09006442 @Override
markchien5776f962019-12-16 20:15:20 +08006443 @Deprecated
6444 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006445 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006446 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6447 Context.TETHERING_SERVICE);
6448
6449 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006450 }
6451
Udam Saini8f7d6a72017-06-07 12:06:28 -07006452 @Override
markchien5776f962019-12-16 20:15:20 +08006453 @Deprecated
6454 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006455 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006456 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6457 Context.TETHERING_SERVICE);
6458 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006459 }
6460
Robert Greenwalte0b00512014-07-02 09:59:16 -07006461 // Called when we lose the default network and have no replacement yet.
6462 // This will automatically be cleared after X seconds or a new default network
6463 // becomes CONNECTED, whichever happens first. The timer is started by the
6464 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006465 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006466 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006467 if (mNetTransitionWakeLock.isHeld()) {
6468 return;
6469 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006470 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006471 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6472 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006473 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006474 mWakelockLogs.log("ACQUIRE for " + forWhom);
6475 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006476 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006477 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006478 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006479 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006480
Hugo Benichi471b62a2017-03-30 23:18:10 +09006481 // Called when we gain a new default network to release the network transition wakelock in a
6482 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6483 // message is cancelled.
6484 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006485 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006486 if (!mNetTransitionWakeLock.isHeld()) {
6487 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006488 }
6489 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006490 // Cancel self timeout on wakelock hold.
6491 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6492 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6493 mHandler.sendMessageDelayed(msg, 1000);
6494 }
6495
6496 // Called when either message of ensureNetworkTransitionWakelock or
6497 // scheduleReleaseNetworkTransitionWakelock is processed.
6498 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6499 String event = eventName(eventId);
6500 synchronized (this) {
6501 if (!mNetTransitionWakeLock.isHeld()) {
6502 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006503 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006504 return;
6505 }
6506 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006507 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6508 mTotalWakelockDurationMs += lockDuration;
6509 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6510 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006511 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006512 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006513 }
6514
Robert Greenwalt986c7412010-09-08 15:24:47 -07006515 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006516 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006517 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006518 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006519 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006520 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006521 }
6522
Lorenzo Colittid6459092016-07-04 12:55:44 +09006523 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006524 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006525 enforceAccessPermission();
6526 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006527 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006528 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006529
6530 final NetworkAgentInfo nai;
6531 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006532 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006533 } else {
6534 nai = getNetworkAgentInfoForNetwork(network);
6535 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006536
6537 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006538 mHandler.obtainMessage(
6539 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006540 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006541
Hugo Benichid6b510a2017-04-06 17:22:18 +09006542 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006543 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006544 if (nai == null
6545 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006546 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006547 return;
6548 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006549 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006550 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006551 mConnectivityDiagnosticsHandler.sendMessage(
6552 mConnectivityDiagnosticsHandler.obtainMessage(
6553 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6554 new ReportedNetworkConnectivityInfo(
6555 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006556 return;
6557 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006558 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006559 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006560 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006561 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006562 // Validating a network that has not yet connected could result in a call to
6563 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006564 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006565 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006566 }
paulhu7aeba372020-12-30 00:42:19 +08006567 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6568 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006569 return;
6570 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006571
6572 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6573 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6574 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6575 // completed.
6576 mConnectivityDiagnosticsHandler.sendMessage(
6577 mConnectivityDiagnosticsHandler.obtainMessage(
6578 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6579 new ReportedNetworkConnectivityInfo(
6580 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006581 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006582 }
6583
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006584 // TODO: call into netd.
6585 private boolean queryUserAccess(int uid, Network network) {
6586 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6587 if (nai == null) return false;
6588
6589 // Any UID can use its default network.
6590 if (nai == getDefaultNetworkForUid(uid)) return true;
6591
6592 // Privileged apps can use any network.
6593 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6594 return true;
6595 }
6596
6597 // An unprivileged UID can use a VPN iff the VPN applies to it.
6598 if (nai.isVPN()) {
6599 return nai.networkCapabilities.appliesToUid(uid);
6600 }
6601
6602 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6603 // sockets, i.e., if it is the owner.
6604 final NetworkAgentInfo vpn = getVpnForUid(uid);
6605 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6606 && uid != vpn.networkCapabilities.getOwnerUid()) {
6607 return false;
6608 }
6609
6610 // The UID's permission must be at least sufficient for the network. Since the restricted
6611 // permission was already checked above, that just leaves background networks.
6612 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6613 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6614 }
6615
6616 // Unrestricted network. Anyone gets to use it.
6617 return true;
6618 }
6619
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006620 /**
6621 * Returns information about the proxy a certain network is using. If given a null network, it
6622 * it will return the proxy for the bound network for the caller app or the default proxy if
6623 * none.
6624 *
6625 * @param network the network we want to get the proxy information for.
6626 * @return Proxy information if a network has a proxy configured, or otherwise null.
6627 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006628 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006629 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006630 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006631 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006632 if (network == null) {
6633 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006634 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006635 true);
6636 if (activeNetwork == null) {
6637 return null;
6638 }
6639 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006640 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006641 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6642 // caller may not have.
6643 return getLinkPropertiesProxyInfo(network);
6644 }
6645 // No proxy info available if the calling UID does not have network access.
6646 return null;
6647 }
6648
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006649
6650 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006651 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6652 if (nai == null) return null;
6653 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006654 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6655 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006656 }
6657 }
6658
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006659 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006660 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006661 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006662 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006663 }
6664
Chalard Jean777e2e52018-06-07 18:02:37 +09006665 @Override
6666 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006667 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006668 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006669 }
6670
Aaron Huang9fe47be2021-06-08 13:11:45 +08006671 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006672 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006673 final NetworkAgentInfo nai = getDefaultNetwork();
6674 // TODO : this method should check that net == nai.network, unfortunately at this point
6675 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6676 // is only ever installed on the default network so in practice this is okay.
6677 if (null == nai) return;
6678 // PAC proxies only work on the default network. Therefore, only the default network
6679 // should have its link properties fixed up for PAC proxies.
6680 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6681 if (nai.everConnected()) {
6682 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6683 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006684 }
6685
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006686 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6687 // when any network changes proxy.
6688 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6689 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006690 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6691 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006692 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6693
Chalard Jean7d97afc2018-06-07 17:41:29 +09006694 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006695 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006696 }
6697 }
6698
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006699 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006700 final private HashMap<Uri, Integer> mUriEventMap;
6701 final private Context mContext;
6702 final private Handler mHandler;
6703
6704 SettingsObserver(Context context, Handler handler) {
6705 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006706 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006707 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006708 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006709 }
6710
Erik Kline05f2b402015-04-30 12:58:40 +09006711 void observe(Uri uri, int what) {
6712 mUriEventMap.put(uri, what);
6713 final ContentResolver resolver = mContext.getContentResolver();
6714 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006715 }
6716
6717 @Override
6718 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006719 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006720 }
6721
6722 @Override
6723 public void onChange(boolean selfChange, Uri uri) {
6724 final Integer what = mUriEventMap.get(uri);
6725 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006726 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006727 } else {
6728 loge("No matching event to send for URI=" + uri);
6729 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006730 }
6731 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006732
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006733 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006734 Log.d(TAG, s);
6735 }
6736
6737 private static void logw(String s) {
6738 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006739 }
6740
Daniel Brightf9e945b2020-06-15 16:10:01 -07006741 private static void logwtf(String s) {
6742 Log.wtf(TAG, s);
6743 }
6744
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006745 private static void logwtf(String s, Throwable t) {
6746 Log.wtf(TAG, s, t);
6747 }
6748
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006749 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006750 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006751 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006752
Hugo Benichi39621362017-02-11 17:04:43 +09006753 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006754 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006755 }
6756
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006757 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006758 * Return the information of all ongoing VPNs.
6759 *
6760 * <p>This method is used to update NetworkStatsService.
6761 *
6762 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006763 */
junyulai2050bed2021-01-23 09:46:34 +08006764 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006765 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006766 if (mLockdownEnabled) {
6767 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006768 }
junyulai2050bed2021-01-23 09:46:34 +08006769 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006770 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006771 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006772 if (info != null) {
6773 infoList.add(info);
6774 }
6775 }
junyulai2050bed2021-01-23 09:46:34 +08006776 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006777 }
6778
6779 /**
6780 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006781 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006782 */
junyulai2050bed2021-01-23 09:46:34 +08006783 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006784 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006785 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6786 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006787 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6788 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6789 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006790 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6791 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006792 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006793 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006794 }
6795 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006796
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006797 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006798
6799 List<String> interfaces = new ArrayList<>();
6800 for (Network network : underlyingNetworks) {
6801 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6802 if (underlyingNai == null) continue;
6803 LinkProperties lp = underlyingNai.linkProperties;
6804 for (String iface : lp.getAllInterfaceNames()) {
6805 if (!TextUtils.isEmpty(iface)) {
6806 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006807 }
6808 }
Benedict Wong34857f82019-06-12 17:46:15 +00006809 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006810
6811 if (interfaces.isEmpty()) return null;
6812
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006813 // Must be non-null or NetworkStatsService will crash.
6814 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6815 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006816 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006817 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006818
junyulai2050bed2021-01-23 09:46:34 +08006819 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6820 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006821 }
6822
James Mattisd31bdfa2020-12-23 16:37:26 -08006823 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006824 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6825 Network[] underlyingNetworks) {
6826 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006827 if (underlyingNetworks == null && defaultNetwork != null) {
6828 // null underlying networks means to track the default.
6829 underlyingNetworks = new Network[] { defaultNetwork };
6830 }
6831 return underlyingNetworks;
6832 }
6833
6834 // Returns true iff |network| is an underlying network of |nai|.
6835 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6836 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6837 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006838 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006839 final Network[] underlying = underlyingNetworksOrDefault(
6840 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006841 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006842 }
6843
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006844 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006845 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006846 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006847 * When underlying networks change, such networks may have to update capabilities to reflect
6848 * things like the metered bit, their transports, and so on. The capabilities are calculated
6849 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006850 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006851 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006852 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006853 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006854 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006855 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006856 }
6857 }
6858 }
6859
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006860 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6861 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6862 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6863 // a VPN is not up.
6864 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6865 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6866 for (UidRange range : blockedUidRanges) {
6867 if (range.contains(uid)) return true;
6868 }
6869 return false;
6870 }
6871
6872 @Override
6873 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006874 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006875 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6876 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6877 }
6878
6879 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6880 if (DBG) {
6881 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6882 + Arrays.toString(ranges));
6883 }
6884 // Cannot use a Set since the list of UID ranges might contain duplicates.
6885 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6886 for (int i = 0; i < ranges.length; i++) {
6887 if (requireVpn) {
6888 newVpnBlockedUidRanges.add(ranges[i]);
6889 } else {
6890 newVpnBlockedUidRanges.remove(ranges[i]);
6891 }
6892 }
6893
6894 try {
6895 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6896 } catch (RemoteException | ServiceSpecificException e) {
6897 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6898 + Arrays.toString(ranges) + "): netd command failed: " + e);
6899 }
6900
Chalard Jeandf29a852023-05-29 17:02:43 +09006901 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006902 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6903 }
6904
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006905 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6906 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006907 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6908 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006909 }
6910
6911 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6912 }
6913
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006914 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006915 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006916 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006917 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006918 }
6919
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006920 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6921 return mLockdownEnabled
6922 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6923 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006924 }
6925
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006926 private NetworkAgentInfo getLegacyLockdownNai() {
6927 if (!mLockdownEnabled) {
6928 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006929 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006930 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006931 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6932 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006933
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006934 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006935 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6936 // a local variable. There is no need to make a copy because its contents cannot change.
6937 final Network[] underlying = nai.declaredUnderlyingNetworks;
6938 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006939 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006940 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006941
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006942 // The legacy lockdown VPN always uses the default network.
6943 // If the VPN's underlying network is no longer the current default network, it means that
6944 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006945 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6946 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006947 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006948 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006949 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006950 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006951
6952 return nai;
6953 };
6954
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006955 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6956 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6957 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006958 private DetailedState getLegacyLockdownState(DetailedState origState) {
6959 if (origState != DetailedState.CONNECTED) {
6960 return origState;
6961 }
6962 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6963 ? DetailedState.CONNECTING
6964 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006965 }
6966
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006967 private void filterForLegacyLockdown(NetworkInfo ni) {
6968 if (!mLockdownEnabled || !ni.isConnected()) return;
6969 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6970 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6971 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6972 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6973 // network, this time with a state of CONNECTED.
6974 //
6975 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6976 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6977 // is not too far off the truth, since an always-on VPN, when not connected, is always
6978 // trying to reconnect.
6979 if (getLegacyLockdownNai() == null) {
6980 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6981 }
6982 }
6983
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006984 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006985 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006986 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006987 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006988 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6989 return;
6990 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006991 final long ident = Binder.clearCallingIdentity();
6992 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006993 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006994 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006995 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006996 } finally {
6997 Binder.restoreCallingIdentity(ident);
6998 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006999 }
Wink Savillecb117d32013-08-29 14:57:08 -07007000
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007001 @Override
7002 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01007003 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007004 final long ident = Binder.clearCallingIdentity();
7005 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007006 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09007007 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007008 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
7009 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08007010 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007011 } finally {
7012 Binder.restoreCallingIdentity(ident);
7013 }
7014 }
7015
James Mattis02220e22021-03-13 19:27:21 -08007016 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08007017 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7018 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7019 }
Chalard Jeane0abd522023-01-23 16:47:43 +09007020 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007021 }
7022
James Mattis02220e22021-03-13 19:27:21 -08007023 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09007024 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007025 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08007026 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
7027 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09007028 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08007029 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7030 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7031 }
junyulaid91e7052020-08-28 13:44:33 +08007032 }
7033
James Mattis02220e22021-03-13 19:27:21 -08007034 private void onPackageChanged(@NonNull final String packageName) {
7035 // This is necessary in case a package is added or removed, but also when it's replaced to
7036 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
7037 // as one in the preferences, then it should follow the same routing as that other package,
7038 // which means updating the rules is never to be needed in this case (whether it joins or
7039 // leaves a UID with a preference).
7040 if (isMappedInOemNetworkPreference(packageName)) {
7041 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7042 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007043
7044 // Invalidates cache entry when the package is updated.
7045 synchronized (mSelfCertifiedCapabilityCache) {
7046 mSelfCertifiedCapabilityCache.remove(packageName);
7047 }
James Mattis02220e22021-03-13 19:27:21 -08007048 }
7049
7050 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007051 @Override
7052 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007053 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007054 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007055 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007056
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007057 // User should be filled for below intents, check the existence.
7058 if (user == null) {
7059 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7060 return;
7061 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007062
Lorenzo Colitticd675292021-02-04 17:32:07 +09007063 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007064 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007065 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007066 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007067 } else {
junyulaid91e7052020-08-28 13:44:33 +08007068 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007069 }
7070 }
7071 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007072
James Mattis02220e22021-03-13 19:27:21 -08007073 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7074 @Override
7075 public void onReceive(Context context, Intent intent) {
7076 ensureRunningOnConnectivityServiceThread();
7077 switch (intent.getAction()) {
7078 case Intent.ACTION_PACKAGE_ADDED:
7079 case Intent.ACTION_PACKAGE_REMOVED:
7080 case Intent.ACTION_PACKAGE_REPLACED:
7081 onPackageChanged(intent.getData().getSchemeSpecificPart());
7082 break;
7083 default:
7084 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7085 }
7086 }
7087 };
7088
Junyu Lai38c75032023-12-04 07:52:19 +00007089 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
7090 private final BroadcastReceiver mDataSaverReceiver = new BroadcastReceiver() {
7091 @Override
7092 public void onReceive(Context context, Intent intent) {
7093 if (mDeps.isAtLeastV()) {
7094 throw new IllegalStateException(
7095 "data saver status should be updated from platform");
7096 }
7097 ensureRunningOnConnectivityServiceThread();
7098 switch (intent.getAction()) {
7099 case ACTION_RESTRICT_BACKGROUND_CHANGED:
7100 // If the uid is present in the deny list, the API will consistently
7101 // return ENABLED. To retrieve the global switch status, the system
7102 // uid is chosen because it will never be included in the deny list.
7103 final int dataSaverForSystemUid =
7104 mPolicyManager.getRestrictBackgroundStatus(Process.SYSTEM_UID);
7105 final boolean isDataSaverEnabled = (dataSaverForSystemUid
7106 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
7107 mBpfNetMaps.setDataSaverEnabled(isDataSaverEnabled);
7108 break;
7109 default:
7110 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7111 }
7112 }
7113 };
7114
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007115 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007116 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007117
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007118 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007119 public final String name;
7120 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007121 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007122 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007123
lifraf3a3492021-03-10 13:58:14 +08007124 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7125 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007126 this.name = name;
7127 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007128 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007129 mDeathRecipient = deathRecipient;
7130
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007131 if (mDeathRecipient == null) {
7132 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007133 }
7134 }
7135
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007136 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007137 try {
7138 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7139 } catch (RemoteException e) {
7140 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007141 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007142 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007143 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007144
James Mattis4fce5d12020-11-12 15:53:42 -08007145 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7146 for (int i = 0; i < requests.size(); i++) {
7147 ensureNetworkRequestHasType(requests.get(i));
7148 }
7149 }
7150
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007151 private void ensureNetworkRequestHasType(NetworkRequest request) {
7152 if (request.type == NetworkRequest.Type.NONE) {
7153 throw new IllegalArgumentException(
7154 "All NetworkRequests in ConnectivityService must have a type");
7155 }
7156 }
7157
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007158 /**
7159 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007160 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007161 */
James Mattis258ea3c2020-11-15 15:04:40 -08007162 @VisibleForTesting
7163 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007164 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7165 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007166 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007167
James Mattisa076c532020-12-02 14:12:41 -08007168 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7169 void setSatisfier(
7170 @Nullable final NetworkAgentInfo satisfier,
7171 @Nullable final NetworkRequest activeRequest) {
7172 mSatisfier = satisfier;
7173 mActiveRequest = activeRequest;
7174 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007175
James Mattisd31bdfa2020-12-23 16:37:26 -08007176 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007177 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007178 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007179 private NetworkAgentInfo mSatisfier;
7180 NetworkAgentInfo getSatisfier() {
7181 return mSatisfier;
7182 }
7183
7184 // The request in mRequests assigned to a network agent. This is null if none of the
7185 // requests in mRequests can be satisfied. This member has the constraint of only being
7186 // accessible on the handler thread.
7187 @Nullable
7188 private NetworkRequest mActiveRequest;
7189 NetworkRequest getActiveRequest() {
7190 return mActiveRequest;
7191 }
7192
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007193 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007194 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007195 @Nullable
7196 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007197
7198 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007199 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007200 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007201 final int mPid;
7202 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007203 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007204 @Nullable
7205 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007206
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007207 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007208 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007209
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007210 // Effective UID of this request. This is different from mUid when a privileged process
7211 // files a request on behalf of another UID. This UID is used to determine blocked status,
7212 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7213 // maximum limit of registered callbacks per UID.
7214 final int mAsUid;
7215
paulhu48291862021-07-14 14:53:57 +08007216 // Preference order of this request.
7217 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007218
James Mattis3ce3d3c2021-02-09 18:18:28 -08007219 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7220 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7221 // maintained for keying off of. This is only a concern when the original nri
7222 // mNetworkRequests changes which happens currently for apps that register callbacks to
7223 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7224 // that match the per-app default nri that currently tracks the calling app's uid so that
7225 // callbacks are fired at the appropriate time. When the callbacks fire,
7226 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7227 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7228 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7229 @NonNull
7230 private final NetworkRequest mNetworkRequestForCallback;
7231 NetworkRequest getNetworkRequestForCallback() {
7232 return mNetworkRequestForCallback;
7233 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007234
James Mattisd31bdfa2020-12-23 16:37:26 -08007235 /**
7236 * Get the list of UIDs this nri applies to.
7237 */
7238 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007239 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007240 // networkCapabilities.getUids() returns a defensive copy.
7241 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007242 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7243 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007244 }
7245
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007246 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7247 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007248 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007249 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007250 }
7251
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007252 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007253 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007254 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007255 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007256 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007257 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007258 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007259 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007260 mBinder = null;
7261 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007262 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007263 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007264 mPerUidCounter = getRequestCounter(this);
7265 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007266 /**
7267 * Location sensitive data not included in pending intent. Only included in
7268 * {@link NetworkCallback}.
7269 */
7270 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007271 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007272 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007273 }
7274
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007275 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007276 @Nullable final IBinder binder,
7277 @NetworkCallback.Flag int callbackFlags,
7278 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007279 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7280 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007281 }
7282
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007283 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007284 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007285 @Nullable final IBinder binder,
7286 @NetworkCallback.Flag int callbackFlags,
7287 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007288 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007289 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007290 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007291 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007292 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007293 mBinder = binder;
7294 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007295 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007296 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007297 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007298 mPerUidCounter = getRequestCounter(this);
7299 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007300 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007301 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007302 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007303 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007304 }
7305
James Mattis3ce3d3c2021-02-09 18:18:28 -08007306 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7307 @NonNull final List<NetworkRequest> r) {
7308 super();
7309 ensureAllNetworkRequestsHaveType(r);
7310 mRequests = initializeRequests(r);
7311 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007312 final NetworkAgentInfo satisfier = nri.getSatisfier();
7313 if (null != satisfier) {
7314 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7315 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007316 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007317 // As this code creates a new NRI with a new set of requests, figure out which of
7318 // the list of requests should be the active request. It is always the first
7319 // request of the list that can be satisfied by the satisfier since the order of
7320 // requests is a priority order.
7321 // Note even in the presence of a satisfier there may not be an active request,
7322 // when the satisfier is the no-service network.
7323 NetworkRequest activeRequest = null;
7324 for (final NetworkRequest candidate : r) {
7325 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7326 activeRequest = candidate;
7327 break;
7328 }
7329 }
7330 setSatisfier(satisfier, activeRequest);
7331 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007332 mMessenger = nri.mMessenger;
7333 mBinder = nri.mBinder;
7334 mPid = nri.mPid;
7335 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007336 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007337 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007338 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007339 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007340 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007341 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007342 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007343 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007344 }
7345
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007346 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007347 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007348 }
7349
paulhue9913722021-05-26 15:19:20 +08007350 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007351 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007352 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007353 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007354 }
7355
James Mattis2516da32021-01-31 17:06:19 -08007356 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7357 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7358 // false.
7359 boolean isBeingSatisfied() {
7360 return (null != mSatisfier && null != mActiveRequest);
7361 }
7362
James Mattis3d229892020-11-16 16:46:28 -08007363 boolean isMultilayerRequest() {
7364 return mRequests.size() > 1;
7365 }
7366
James Mattis45d81842021-01-10 14:24:24 -08007367 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7368 // Creating a defensive copy to prevent the sender from modifying the list being
7369 // reflected in the return value of this method.
7370 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007371 return Collections.unmodifiableList(tempRequests);
7372 }
7373
James Mattisb1392002021-03-31 13:57:52 -07007374 void linkDeathRecipient() {
7375 if (null != mBinder) {
7376 try {
7377 mBinder.linkToDeath(this, 0);
7378 } catch (RemoteException e) {
7379 binderDied();
7380 }
7381 }
7382 }
7383
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007384 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007385 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007386 try {
7387 mBinder.unlinkToDeath(this, 0);
7388 } catch (NoSuchElementException e) {
7389 // Temporary workaround for b/194394697 pending analysis of additional logs
7390 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7391 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007392 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007393 }
7394
paulhu48291862021-07-14 14:53:57 +08007395 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7396 // Compare two preference orders.
7397 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007398 }
7399
paulhu48291862021-07-14 14:53:57 +08007400 int getPreferenceOrderForNetd() {
7401 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7402 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7403 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007404 }
paulhu48291862021-07-14 14:53:57 +08007405 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007406 }
7407
James Mattis4fce5d12020-11-12 15:53:42 -08007408 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007409 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007410 // As an immutable collection, mRequests cannot change by the time the
7411 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7412 // is acceptable. Use handleReleaseNetworkRequest and not directly
7413 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7414 // the app already unregistered the request.
7415 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7416 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007417 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007418
James Mattis4fce5d12020-11-12 15:53:42 -08007419 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007420 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007421 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7422 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007423 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007424 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007425 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007426 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007427 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007428 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007429 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007430 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007431 }
7432
Junyu Lai00d92df2022-07-05 11:01:52 +08007433 // Keep backward compatibility since the ServiceSpecificException is used by
7434 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7435 public static class RequestInfoPerUidCounter extends PerUidCounter {
7436 RequestInfoPerUidCounter(int maxCountPerUid) {
7437 super(maxCountPerUid);
7438 }
7439
7440 @Override
7441 public synchronized void incrementCountOrThrow(int uid) {
7442 try {
7443 super.incrementCountOrThrow(uid);
7444 } catch (IllegalStateException e) {
7445 throw new ServiceSpecificException(
7446 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7447 "Uid " + uid + " exceeded its allotted requests limit");
7448 }
7449 }
7450
7451 @Override
7452 public synchronized void decrementCountOrThrow(int uid) {
7453 throw new UnsupportedOperationException("Use decrementCount instead.");
7454 }
7455
7456 public synchronized void decrementCount(int uid) {
7457 try {
7458 super.decrementCountOrThrow(uid);
7459 } catch (IllegalStateException e) {
7460 logwtf("Exception when decrement per uid request count: ", e);
7461 }
7462 }
7463 }
7464
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007465 // This checks that the passed capabilities either do not request a
7466 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007467 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007468 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007469 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007470 throw new SecurityException("Insufficient permissions to request a specific SSID");
7471 }
paulhu1a407652019-03-22 16:35:06 +08007472
7473 if (nc.hasSignalStrength()
7474 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7475 throw new SecurityException(
7476 "Insufficient permissions to request a specific signal strength");
7477 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007478 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007479
junyulai2217bec2021-04-14 23:33:31 +08007480 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007481 enforceNetworkFactoryPermission();
7482 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007483 }
7484
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007485 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007486 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007487 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007488 // mNetworkRequests may contain the same value multiple times in case of
7489 // multilayer requests. It won't matter in this case because the thresholds
7490 // will then be the same and be deduplicated as they enter the `thresholds` set.
7491 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007492 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7493 for (final NetworkRequest req : nri.mRequests) {
7494 if (req.networkCapabilities.hasSignalStrength()
7495 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7496 thresholds.add(req.networkCapabilities.getSignalStrength());
7497 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007498 }
7499 }
7500 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007501 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007502 }
7503
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007504 private void updateSignalStrengthThresholds(
7505 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007506 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007507
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007508 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007509 String detail;
7510 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7511 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7512 } else {
7513 detail = reason;
7514 }
7515 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007516 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007517 }
7518
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007519 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007520 }
7521
Chalard Jeandd421992021-12-16 23:16:02 +09007522 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007523 if (nc == null) {
7524 return;
7525 }
7526 NetworkSpecifier ns = nc.getNetworkSpecifier();
7527 if (ns == null) {
7528 return;
7529 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007530 if (ns instanceof MatchAllNetworkSpecifier) {
7531 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7532 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007533 }
7534
Chalard Jeandd421992021-12-16 23:16:02 +09007535 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007536 ensureValidNetworkSpecifier(nc);
7537 if (nc.isPrivateDnsBroken()) {
7538 throw new IllegalArgumentException("Can't request broken private DNS");
7539 }
Chalard Jeande665262022-02-25 16:12:12 +09007540 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007541 throw new IllegalArgumentException("Can't request access UIDs");
7542 }
lucasline117e2e2019-10-22 18:27:33 +08007543 }
7544
Chalard Jeandd421992021-12-16 23:16:02 +09007545 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7546 ensureListenableCapabilities(nc);
7547 final String badCapability = nc.describeFirstNonRequestableCapability();
7548 if (badCapability != null) {
7549 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7550 }
7551 }
7552
Chiachang Wang3bc52762021-11-25 14:17:57 +08007553 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7554 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007555 private boolean isTargetSdkAtleast(int version, int callingUid,
7556 @NonNull String callingPackageName) {
7557 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007558 final PackageManager pm =
7559 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007560 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007561 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007562 if (callingVersion < version) return false;
7563 } catch (PackageManager.NameNotFoundException e) { }
7564 return true;
7565 }
7566
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007567 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007568 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007569 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007570 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007571 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007572 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007573 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7574 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007575 throw new SecurityException("Insufficient permissions to specify legacy type");
7576 }
markchienfac84a22020-03-18 21:16:15 +08007577 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007578 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007579 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007580 // Privileged callers can track the default network of another UID by passing in a UID.
7581 if (asUid != Process.INVALID_UID) {
7582 enforceSettingsPermission();
7583 } else {
7584 asUid = callingUid;
7585 }
junyulaiad010792021-01-11 16:53:38 +08007586 final NetworkRequest.Type reqType;
7587 try {
7588 reqType = NetworkRequest.Type.values()[reqTypeInt];
7589 } catch (ArrayIndexOutOfBoundsException e) {
7590 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7591 }
7592 switch (reqType) {
7593 case TRACK_DEFAULT:
7594 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007595 // is unused and will be replaced by ones appropriate for the UID (usually, the
7596 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007597 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007598 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007599 enforceAccessPermission();
7600 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007601 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007602 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007603 networkCapabilities = new NetworkCapabilities(defaultNc);
7604 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007605 case BACKGROUND_REQUEST:
7606 enforceNetworkStackOrSettingsPermission();
7607 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007608 case REQUEST:
7609 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7610 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007611 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007612 // TODO: this is incorrect. We mark the request as metered or not depending on
7613 // the state of the app when the request is filed, but we never change the
7614 // request if the app changes network state. http://b/29964605
7615 enforceMeteredApnPolicy(networkCapabilities);
7616 break;
junyulai1b1c8742021-03-12 20:05:08 +08007617 case LISTEN_FOR_BEST:
7618 enforceAccessPermission();
7619 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7620 break;
junyulaiad010792021-01-11 16:53:38 +08007621 default:
7622 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007623 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007624 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007625 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007626 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007627
junyulai1b1c8742021-03-12 20:05:08 +08007628 // Enforce FOREGROUND if the caller does not have permission to use background network.
7629 if (reqType == LISTEN_FOR_BEST) {
7630 restrictBackgroundRequestForCaller(networkCapabilities);
7631 }
7632
7633 // Set the UID range for this request to the single UID of the requester, unless the
7634 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007635 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7636 // are no visible methods to set the UIDs, an app could use reflection to try and get
7637 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007638 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007639 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7640 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007641
Etan Cohen85000162017-02-05 10:42:27 -08007642 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007643 throw new IllegalArgumentException("Bad timeout specified");
7644 }
Etan Cohen9786d922015-11-18 10:56:15 -08007645
James Mattis3ce3d3c2021-02-09 18:18:28 -08007646 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007647 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007648 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007649 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007650 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007651 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007652
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007653 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7654 // copied from the default request above. (This is necessary to ensure, for example, that
7655 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7656 // changes don't alter request matching.
7657 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7658 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007659 throw new IllegalStateException(
7660 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007661 + networkCapabilities + " vs. " + defaultNc);
7662 }
7663
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007664 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007665 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007666 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007667 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007668 }
7669 return networkRequest;
7670 }
7671
James Mattis3ce3d3c2021-02-09 18:18:28 -08007672 /**
7673 * Return the nri to be used when registering a network request. Specifically, this is used with
7674 * requests registered to track the default request. If there is currently a per-app default
7675 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7676 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007677 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7678 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007679 * @param nr the network request for the nri.
7680 * @param msgr the messenger for the nri.
7681 * @param binder the binder for the nri.
7682 * @param callingAttributionTag the calling attribution tag for the nri.
7683 * @return the nri to register.
7684 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007685 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007686 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007687 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007688 @Nullable String callingAttributionTag) {
7689 final List<NetworkRequest> requests;
7690 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7691 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007692 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007693 } else {
7694 requests = Collections.singletonList(nr);
7695 }
Roshan Pius951c0032020-12-22 15:10:42 -08007696 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007697 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007698 }
7699
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007700 private boolean shouldCheckCapabilitiesDeclaration(
7701 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7702 @NonNull final String callingPackageName) {
7703 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7704 // Only run the check if the change is enabled.
7705 if (!mDeps.isChangeEnabled(
7706 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7707 callingPackageName, user)) {
7708 return false;
7709 }
7710
7711 return networkCapabilities.hasCapability(
7712 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7713 || networkCapabilities.hasCapability(
7714 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7715 }
7716
7717 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007718 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007719 // This check is added to fix the linter error for "current min is 30", which is not going
7720 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007721 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007722 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7723 return;
7724 }
7725 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007726 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007727 try {
7728 synchronized (mSelfCertifiedCapabilityCache) {
7729 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7730 callerPackageName);
7731 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007732 final PackageManager packageManager =
7733 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
7734 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007735 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7736 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7737 callerPackageName
7738 );
7739 final XmlResourceParser parser = packageManager
7740 .getResourcesForApplication(callerPackageName)
7741 .getXml(networkSliceProperty.getResourceId());
7742 applicationNetworkCapabilities =
7743 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7744 mSelfCertifiedCapabilityCache.put(callerPackageName,
7745 applicationNetworkCapabilities);
7746 }
7747
7748 }
7749 } catch (PackageManager.NameNotFoundException ne) {
7750 throw new SecurityException(
7751 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7752 + " property");
7753 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7754 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007755 } finally {
7756 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007757 }
7758
7759 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7760 networkCapabilities);
7761 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007762 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007763 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007764 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7765 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007766 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
7767 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007768 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007769 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007770 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7771 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7772 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7773 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007774 }
junyulai96bd9fe2022-03-08 17:36:42 +08007775 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007776 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007777 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007778 }
7779 }
7780
fenglu3f357402015-03-20 11:29:56 -07007781 @Override
fenglub00f4882015-04-21 17:12:05 -07007782 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007783 enforceAccessPermission();
7784 NetworkAgentInfo nai = null;
7785 if (network == null) {
7786 return false;
7787 }
7788 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007789 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007790 }
7791 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007792 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007793 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007794 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007795 Integer uidReqs = mBandwidthRequests.get(uid);
7796 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007797 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007798 }
7799 mBandwidthRequests.put(uid, ++uidReqs);
7800 }
fenglu3f357402015-03-20 11:29:56 -07007801 return true;
7802 }
7803 return false;
7804 }
7805
Felipe Leme0a5ae422016-06-20 16:36:29 -07007806 private boolean isSystem(int uid) {
7807 return uid < Process.FIRST_APPLICATION_UID;
7808 }
fenglu3f357402015-03-20 11:29:56 -07007809
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007810 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007811 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007812 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007813 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007814 return;
7815 }
Hugo Benichi39621362017-02-11 17:04:43 +09007816 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7817 // Policy already enforced.
7818 return;
7819 }
paulhuaf50d7d2020-12-24 19:47:34 +08007820 final long ident = Binder.clearCallingIdentity();
7821 try {
7822 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7823 // If UID is restricted, don't allow them to bring up metered APNs.
7824 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7825 }
7826 } finally {
7827 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007828 }
7829 }
7830
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007831 @Override
7832 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007833 PendingIntent operation, @NonNull String callingPackageName,
7834 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007835 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007836 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007837 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007838 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007839 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007840 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007841 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007842 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007843 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007844 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7845 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007846
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007847 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007848 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007849 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7850 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007851 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007852 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7853 nri));
7854 return networkRequest;
7855 }
7856
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007857 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7858 mHandler.sendMessageDelayed(
7859 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007860 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007861 }
7862
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007863 @Override
7864 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007865 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007866 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007867 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007868 }
7869
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007870 // In order to implement the compatibility measure for pre-M apps that call
7871 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7872 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7873 // This ensures it has permission to do so.
7874 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7875 if (nc == null) {
7876 return false;
7877 }
7878 int[] transportTypes = nc.getTransportTypes();
7879 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7880 return false;
7881 }
7882 try {
7883 mContext.enforceCallingOrSelfPermission(
7884 android.Manifest.permission.ACCESS_WIFI_STATE,
7885 "ConnectivityService");
7886 } catch (SecurityException e) {
7887 return false;
7888 }
7889 return true;
7890 }
7891
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007892 @Override
7893 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007894 Messenger messenger, IBinder binder,
7895 @NetworkCallback.Flag int callbackFlags,
7896 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007897 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007898 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7899 enforceAccessPermission();
7900 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007901
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007902 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007903 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007904 Binder.getCallingPid(), callingUid, callingPackageName);
7905 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007906 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7907 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7908 // onLost and onAvailable callbacks when networks move in and out of the background.
7909 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7910 // can't request networks.
7911 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007912 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007913
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007914 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007915 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007916 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007917 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007918 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007919 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007920
7921 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7922 return networkRequest;
7923 }
7924
7925 @Override
7926 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007927 PendingIntent operation, @NonNull String callingPackageName,
7928 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007929 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007930 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007931 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7932 enforceAccessPermission();
7933 }
Chalard Jeandd421992021-12-16 23:16:02 +09007934 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007935 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007936 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007937 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007938 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007939
7940 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007941 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007942 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7943 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007944 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007945
WeiZhang1cc3f172021-06-03 19:02:04 -05007946 mHandler.sendMessage(mHandler.obtainMessage(
7947 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007948 }
7949
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007950 /** Returns the next Network provider ID. */
7951 public final int nextNetworkProviderId() {
7952 return mNextNetworkProviderId.getAndIncrement();
7953 }
7954
Erik Kline0c04b742016-07-07 16:50:58 +09007955 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007956 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007957 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007958 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007959 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007960 }
7961
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007962 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7963 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007964 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7965 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7966 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007967 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007968 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007969 return;
7970 }
7971
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007972 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7973 mNetworkProviderInfos.put(npi.messenger, npi);
7974 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007975 }
7976
7977 @Override
7978 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007979 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007980 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007981 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007982 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007983 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7984 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007985 }
7986
7987 @Override
7988 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007989 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007990 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007991 }
7992
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007993 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007994 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007995 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7996 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007997 Objects.requireNonNull(score);
7998 Objects.requireNonNull(caps);
7999 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008000 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008001 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09008002 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
8003 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008004 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
8005 }
8006
Chalard Jeanbb902a52021-08-18 01:35:19 +09008007 private void updateOfferScore(final NetworkOffer offer) {
8008 final boolean yieldToBadWiFi =
8009 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
8010 final NetworkOffer newOffer = new NetworkOffer(
8011 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
8012 offer.caps, offer.callback, offer.providerId);
8013 if (offer.equals(newOffer)) return;
8014 handleRegisterNetworkOffer(newOffer);
8015 }
8016
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008017 @Override
8018 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08008019 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008020 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
8021 }
8022
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008023 private void handleUnregisterNetworkProvider(Messenger messenger) {
8024 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
8025 if (npi == null) {
8026 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008027 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008028 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008029 // Unregister all the offers from this provider
8030 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
8031 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09008032 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008033 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
8034 toRemove.add(noi);
8035 }
8036 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09008037 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008038 handleUnregisterNetworkOffer(noi);
8039 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008040 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07008041 }
8042
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008043 @Override
James Mattisf7027322020-12-13 16:28:14 -08008044 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008045 if (request.hasTransport(TRANSPORT_TEST)) {
8046 enforceNetworkFactoryOrTestNetworksPermission();
8047 } else {
8048 enforceNetworkFactoryPermission();
8049 }
James Mattisf7027322020-12-13 16:28:14 -08008050 final NetworkRequestInfo nri = mNetworkRequests.get(request);
8051 if (nri != null) {
8052 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
8053 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
8054 mHandler.post(() -> handleReleaseNetworkRequest(
8055 nri.mRequests.get(0), mDeps.getCallingUid(), true));
8056 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008057 }
8058
Paul Jensen1f567382015-02-13 14:18:39 -05008059 // NOTE: Accessed on multiple threads, must be synchronized on itself.
8060 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008061 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05008062 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008063 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05008064 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008065 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008066
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008067 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05008068 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008069 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008070
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008071 // UID ranges for users that are currently blocked by VPNs.
8072 // This array is accessed and iterated on multiple threads without holding locks, so its
8073 // contents must never be mutated. When the ranges change, the array is replaced with a new one
8074 // (on the handler thread).
8075 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
8076
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008077 // Must only be accessed on the handler thread
8078 @NonNull
8079 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8080
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008081 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008082 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008083
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008084 // Current OEM network preferences. This object must only be written to on the handler thread.
8085 // Since it is immutable and always non-null, other threads may read it if they only care
8086 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008087 @NonNull
8088 private OemNetworkPreferences mOemNetworkPreferences =
8089 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008090 // Current per-profile network preferences. This object follows the same threading rules as
8091 // the OEM network preferences above.
8092 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008093 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8094 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008095
lucaslin3ba7cc22022-12-19 02:35:33 +00008096 // Current VPN network preferences. This object follows the same threading rules as the OEM
8097 // network preferences above.
8098 @NonNull
8099 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8100 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8101
paulhu51f77dc2021-06-07 02:34:20 +00008102 // A set of UIDs that should use mobile data preferentially if available. This object follows
8103 // the same threading rules as the OEM network preferences above.
8104 @NonNull
8105 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8106
James Mattiscb1e0362021-04-06 17:07:42 -07008107 // OemNetworkPreferences activity String log entries.
8108 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8109 @NonNull
8110 private final LocalLog mOemNetworkPreferencesLogs =
8111 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8112
James Mattis02220e22021-03-13 19:27:21 -08008113 /**
8114 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8115 * @param packageName the package name to check existence of a mapping for.
8116 * @return true if a mapping exists, false otherwise
8117 */
8118 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8119 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8120 }
8121
James Mattise3ef1912020-12-20 11:09:58 -08008122 // The always-on request for an Internet-capable network that apps without a specific default
8123 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008124 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008125 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008126 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008127 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008128 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008129 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008130 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008131
James Mattisd31bdfa2020-12-23 16:37:26 -08008132 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8133 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8134 }
8135
8136 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008137 * Return the default network request currently tracking the given uid.
8138 * @param uid the uid to check.
8139 * @return the NetworkRequestInfo tracking the given uid.
8140 */
8141 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008142 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008143 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008144 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008145 // Checking the first request is sufficient as only multilayer requests will have more
8146 // than one request and for multilayer, all requests will track the same uids.
8147 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008148 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008149 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008150 highestPriorityNri = nri;
8151 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008152 }
8153 }
paulhuaa0743d2021-05-26 21:56:03 +08008154 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008155 }
8156
8157 /**
8158 * Get a copy of the network requests of the default request that is currently tracking the
8159 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008160 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8161 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008162 * @param requestorUid the uid to check the default for.
8163 * @param requestorPackageName the requestor's package name.
8164 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8165 */
8166 @NonNull
8167 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008168 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008169 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008170 getDefaultRequestTrackingUid(asUid).mRequests,
8171 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008172 }
8173
8174 /**
8175 * Copy the given nri's NetworkRequest collection.
8176 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008177 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8178 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008179 * @param requestorUid the uid to set on the copied collection.
8180 * @param requestorPackageName the package name to set on the copied collection.
8181 * @return the copied NetworkRequest collection.
8182 */
8183 @NonNull
8184 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008185 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8186 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008187 final List<NetworkRequest> requests = new ArrayList<>();
8188 for (final NetworkRequest nr : requestsToCopy) {
8189 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008190 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008191 nr.legacyType, nextNetworkRequestId(), nr.type));
8192 }
8193 return requests;
8194 }
8195
8196 @NonNull
8197 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008198 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8199 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008200 // These capabilities are for a TRACK_DEFAULT callback, so:
8201 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8202 // mDefaultRequest and a per-UID default request.
8203 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008204 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008205 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008206 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8207 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008208 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008209 restrictRequestUidsForCallerAndSetRequestorInfo(
8210 netCap, requestorUid, requestorPackageName);
8211 return netCap;
8212 }
8213
8214 /**
8215 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8216 * @param nr the network request to check for equality against.
8217 * @return the nri if one exists, null otherwise.
8218 */
8219 @Nullable
8220 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8221 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8222 if (nri.getNetworkRequestForCallback().equals(nr)) {
8223 return nri;
8224 }
8225 }
8226 return null;
8227 }
8228
8229 /**
8230 * Check if an nri is currently being managed by per-app default networking.
8231 * @param nri the nri to check.
8232 * @return true if this nri is currently being managed by per-app default networking.
8233 */
8234 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8235 // nri.mRequests.get(0) is only different from the original request filed in
8236 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8237 // functionality therefore if these two don't match, it means this particular nri is
8238 // currently being managed by a per-app default.
8239 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8240 }
8241
8242 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008243 * Determine if an nri is a managed default request that disallows default networking.
8244 * @param nri the request to evaluate
8245 * @return true if device-default networking is disallowed
8246 */
8247 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8248 // Check if this nri is a managed default that supports the default network at its
8249 // lowest priority request.
8250 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8251 final NetworkCapabilities lowestPriorityNetCap =
8252 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8253 return isPerAppDefaultRequest(nri)
8254 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8255 lowestPriorityNetCap));
8256 }
8257
Erik Kline05f2b402015-04-30 12:58:40 +09008258 // Request used to optionally keep mobile data active even when higher
8259 // priority networks like Wi-Fi are active.
8260 private final NetworkRequest mDefaultMobileDataRequest;
8261
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008262 // Request used to optionally keep wifi data active even when higher
8263 // priority networks like ethernet are active.
8264 private final NetworkRequest mDefaultWifiRequest;
8265
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008266 // Request used to optionally keep vehicle internal network always active
8267 private final NetworkRequest mDefaultVehicleRequest;
8268
James Mattisd31bdfa2020-12-23 16:37:26 -08008269 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8270 // network with no service. This NAI should never be matched against, nor should any public API
8271 // ever return the associated network. For this reason, this NAI is not in the list of available
8272 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8273 // default requests that don't support using the device default network which will ultimately
8274 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8275 @VisibleForTesting
8276 final NetworkAgentInfo mNoServiceNetwork;
8277
Chalard Jean5b409c72021-02-04 13:12:59 +09008278 // The NetworkAgentInfo currently satisfying the default request, if any.
8279 private NetworkAgentInfo getDefaultNetwork() {
8280 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008281 }
8282
James Mattis2516da32021-01-31 17:06:19 -08008283 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008284 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008285 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8286 // Currently, all network requests will have the same uids therefore checking the first
8287 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008288 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008289 if (null == uids) {
8290 continue;
8291 }
8292 for (final UidRange range : uids) {
8293 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008294 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008295 highestPriorityNri = nri;
8296 }
James Mattis2516da32021-01-31 17:06:19 -08008297 }
8298 }
8299 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008300 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008301 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008302 }
8303
Varun Ananddf569952019-02-06 10:13:38 -08008304 @Nullable
8305 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8306 return nai != null ? nai.network : null;
8307 }
8308
8309 private void ensureRunningOnConnectivityServiceThread() {
8310 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8311 throw new IllegalStateException(
8312 "Not running on ConnectivityService thread: "
8313 + Thread.currentThread().getName());
8314 }
8315 }
8316
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008317 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008318 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8319 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008320 }
8321
Chalard Jean29d06db2018-05-02 21:14:54 +09008322 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008323 * Returns whether local agents are supported on this device.
8324 *
8325 * Local agents are supported from U on TVs, and from V on all devices.
8326 */
8327 @VisibleForTesting
8328 public boolean areLocalAgentsSupported() {
8329 final PackageManager pm = mContext.getPackageManager();
8330 // Local agents are supported starting on U on TVs and on V on everything else.
8331 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8332 }
8333
8334 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008335 * Register a new agent with ConnectivityService to handle a network.
8336 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008337 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008338 * @param networkInfo the initial info associated with this network. It can be updated later :
8339 * see {@link #updateNetworkInfo}.
8340 * @param linkProperties the initial link properties of this network. They can be updated
8341 * later : see {@link #updateLinkProperties}.
8342 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008343 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008344 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008345 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008346 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008347 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008348 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008349 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008350 public Network registerNetworkAgent(INetworkAgent na,
8351 NetworkInfo networkInfo,
8352 LinkProperties linkProperties,
8353 NetworkCapabilities networkCapabilities,
8354 @NonNull NetworkScore initialScore,
8355 @Nullable LocalNetworkConfig localNetworkConfig,
8356 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008357 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008358 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8359 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8360 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008361 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008362 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008363 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008364 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008365 } else {
8366 enforceNetworkFactoryPermission();
8367 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008368 final boolean hasLocalCap =
8369 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8370 if (hasLocalCap && !areLocalAgentsSupported()) {
8371 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8372 throw new IllegalArgumentException("Local agents are not supported in this version");
8373 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008374 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8375 if (hasLocalCap != hasLocalNetworkConfig) {
8376 throw new IllegalArgumentException(null != localNetworkConfig
8377 ? "Only local network agents can have a LocalNetworkConfig"
8378 : "Local network agents must have a LocalNetworkConfig"
8379 );
8380 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008381
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008382 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008383 final long token = Binder.clearCallingIdentity();
8384 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008385 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008386 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8387 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008388 } finally {
8389 Binder.restoreCallingIdentity(token);
8390 }
8391 }
8392
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008393 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008394 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008395 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8396 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008397 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008398
Chalard Jeandbc46952022-02-02 00:14:18 +09008399 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8400 // and mutate them at any time.
8401 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8402 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8403 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008404 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008405
Chalard Jean366c5252022-01-25 18:27:53 +09008406 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008407 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008408 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8409 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008410 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008411 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008412 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8413 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8414 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008415
Chalard Jeandbc46952022-02-02 00:14:18 +09008416 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008417 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008418 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008419 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008420 mDeps.getNetworkStack().makeNetworkMonitor(
8421 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008422 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8423 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008424 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008425 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008426 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008427 }
8428
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008429 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008430 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008431 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008432 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008433 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008434 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8435 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8436 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008437
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008438 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008439
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008440 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008441 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008442 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008443 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008444
8445 try {
8446 networkMonitor.start();
8447 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008448 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008449 }
Chalard Jean366c5252022-01-25 18:27:53 +09008450
Chalard Jean1e4c2182023-10-06 18:45:53 +09008451 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008452 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008453 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008454 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008455 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008456 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008457 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008458 }
8459
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008460 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8461 @NonNull public final NetworkOffer offer;
8462
8463 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8464 this.offer = offer;
8465 }
8466
8467 @Override
8468 public void binderDied() {
8469 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8470 }
8471 }
8472
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008473 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8474 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8475 if (npi.providerId == providerId) return true;
8476 }
8477 return false;
8478 }
8479
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008480 /**
8481 * Register or update a network offer.
8482 * @param newOffer The new offer. If the callback member is the same as an existing
8483 * offer, it is an update of that offer.
8484 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008485 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008486 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8487 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008488 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008489 // This may actually happen if a provider updates its score or registers and then
8490 // immediately unregisters. The offer would still be in the handler queue, but the
8491 // provider would have been removed.
8492 if (DBG) log("Received offer from an unregistered provider");
8493 return;
8494 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008495 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8496 if (null != existingOffer) {
8497 handleUnregisterNetworkOffer(existingOffer);
8498 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008499 if (DBG) {
8500 // handleUnregisterNetworkOffer has already logged the old offer
8501 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8502 }
8503 } else {
8504 if (DBG) {
8505 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8506 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008507 }
8508 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8509 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008510 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008511 } catch (RemoteException e) {
8512 noi.binderDied();
8513 return;
8514 }
8515 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008516 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008517 }
8518
8519 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8520 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008521 if (DBG) {
8522 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8523 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008524
8525 // If the provider removes the offer and dies immediately afterwards this
8526 // function may be called twice in a row, but the array will no longer contain
8527 // the offer.
8528 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008529 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008530 }
8531
8532 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8533 @NonNull final INetworkOfferCallback callback) {
8534 ensureRunningOnConnectivityServiceThread();
8535 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008536 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008537 }
8538 return null;
8539 }
8540
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008541 /**
8542 * Called when receiving LinkProperties directly from a NetworkAgent.
8543 * Stores into |nai| any data coming from the agent that might also be written to the network's
8544 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8545 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008546 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008547 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008548 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8549 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008550 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008551 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008552 }
8553
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008554 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008555 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008556 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008557
Lorenzo Colittid523d142020-04-01 20:16:30 +09008558 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8559 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8560 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008561 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008562
Suprabh Shukla1e312032023-01-24 03:36:37 -08008563 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008564
8565 // update filtering rules, need to happen after the interface update so netd knows about the
8566 // new interface (the interface name -> index map becomes initialized)
8567 updateVpnFiltering(newLp, oldLp, networkAgent);
8568
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008569 updateMtu(newLp, oldLp);
8570 // TODO - figure out what to do for clat
8571// for (LinkProperties lp : newLp.getStackedLinks()) {
8572// updateMtu(lp, null);
8573// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008574 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008575 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008576 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8577 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008578
Erik Klineb9888902016-04-05 13:30:49 +09008579 updateRoutes(newLp, oldLp, netId);
8580 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008581 // Make sure LinkProperties represents the latest private DNS status.
8582 // This does not need to be done before updateDnses because the
8583 // LinkProperties are not the source of the private DNS configuration.
8584 // updateDnses will fetch the private DNS configuration from DnsManager.
8585 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008586
Chalard Jean5b409c72021-02-04 13:12:59 +09008587 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008588 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008589 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008590 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008591 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008592
8593 updateWakeOnLan(newLp);
8594
Hai Shalome58bdc62021-01-11 18:45:34 -08008595 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8596 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8597 // does, it needs to be merged here.
8598 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8599 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008600
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008601 // TODO - move this check to cover the whole function
8602 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008603 synchronized (networkAgent) {
8604 networkAgent.linkProperties = newLp;
8605 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008606 // Start or stop DNS64 detection and 464xlat according to network state.
8607 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008608 // Notify NSS when relevant events happened. Currently, NSS only cares about
8609 // interface changed to update clat interfaces accounting.
8610 final boolean interfacesChanged = oldLp == null
8611 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8612 if (interfacesChanged) {
8613 notifyIfacesChangedForNetworkStats();
8614 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008615 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8616 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008617 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008618 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008619
8620 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008621 }
8622
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008623 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8624 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8625 }
8626
Hai Shalome58bdc62021-01-11 18:45:34 -08008627 /**
8628 * @param naData captive portal data from NetworkAgent
8629 * @param apiData captive portal data from capport API
8630 */
8631 @Nullable
8632 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8633 CaptivePortalData apiData) {
8634 if (naData == null || apiData == null) {
8635 return naData == null ? apiData : naData;
8636 }
8637 final CaptivePortalData.Builder captivePortalBuilder =
8638 new CaptivePortalData.Builder(naData);
8639
8640 if (apiData.isCaptive()) {
8641 captivePortalBuilder.setCaptive(true);
8642 }
8643 if (apiData.isSessionExtendable()) {
8644 captivePortalBuilder.setSessionExtendable(true);
8645 }
8646 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8647 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8648 // otherwise data would be inconsistent. Prefer the capport API info if present,
8649 // as it can generally be refreshed more often.
8650 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8651 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8652 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8653 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8654 // No source has time / bytes remaining information: surface the newest refresh time
8655 // for other fields
8656 captivePortalBuilder.setRefreshTime(
8657 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8658 }
8659
Hai Shalom7c6ab402021-02-04 19:34:06 -08008660 // Prioritize the user portal URL from the network agent if the source is authenticated.
8661 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8662 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8663 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8664 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008665 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008666 // Prioritize the venue information URL from the network agent if the source is
8667 // authenticated.
8668 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8669 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8670 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8671 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008672 }
8673 return captivePortalBuilder.build();
8674 }
8675
Suprabh Shukla53e16392023-04-26 18:47:36 -07008676 @VisibleForTesting
8677 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008678 // This needs to be kept in sync and backwards compatible with the decoding logic in
8679 // NetdEventListenerService, which is non-mainline code.
8680 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8681 }
8682
Suprabh Shukla75642282023-04-25 23:15:43 -07008683 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8684 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8685 return true;
8686 }
8687 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8688 return true;
8689 }
8690 return false;
8691 }
8692
Suprabh Shukla1e312032023-01-24 03:36:37 -08008693 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008694 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008695 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008696 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008697 return;
8698 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008699
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008700 // Mask/mark of zero will not detect anything interesting.
8701 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008702 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008703 return;
8704 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008705
Suprabh Shukla1e312032023-01-24 03:36:37 -08008706 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008707 try {
8708 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008709 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008710 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008711 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008712 }
8713 } catch (Exception e) {
8714 loge("Exception modifying wakeup packet monitoring: " + e);
8715 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008716 }
8717
Junyu Lai970963e2022-10-25 15:46:47 +08008718 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008719 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008720 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008721 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008722 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008723 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008724 for (final String iface : interfaceDiff.added) {
8725 try {
8726 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008727 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008728 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008729 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008730 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008731 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008732 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008733 }
Paul Jensenbff73492014-04-28 10:33:11 -04008734 }
8735 }
Chalard Jean9589e722019-11-19 19:03:53 +09008736 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008737 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008738 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008739 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008740 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008741 } catch (Exception e) {
8742 loge("Exception removing interface: " + e);
8743 }
8744 }
8745 }
8746
Paul Jensene0fd4a82014-08-06 15:51:33 -04008747 /**
8748 * Have netd update routes from oldLp to newLp.
8749 * @return true if routes changed between oldLp and newLp
8750 */
Junyu Lai970963e2022-10-25 15:46:47 +08008751 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8752 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008753 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008754 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8755 new CompareOrUpdateResult<>(
8756 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008757 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008758 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008759
8760 // add routes before removing old in case it helps with continuous connectivity
8761
Chalard Jean9dd11612018-06-04 16:52:49 +09008762 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008763 for (RouteInfo route : routeDiff.added) {
8764 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008765 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008766 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008767 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008768 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008769 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008770 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008771 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008772 }
8773 }
8774 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008775 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008776 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008777 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008778 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008779 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008780 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008781 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008782 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008783 }
8784 }
8785
8786 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008787 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008788 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008789 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008790 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008791 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008792 }
8793 }
Tyler Weare4314862019-12-05 14:55:30 -08008794
8795 for (RouteInfo route : routeDiff.updated) {
8796 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8797 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008798 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008799 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008800 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008801 }
8802 }
8803 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8804 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008805 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008806
Junyu Lai970963e2022-10-25 15:46:47 +08008807 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8808 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008809 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8810 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008811 }
Erik Klineb9888902016-04-05 13:30:49 +09008812
Erik Kline31b4a9e2018-01-11 21:07:29 +09008813 if (DBG) {
8814 final Collection<InetAddress> dnses = newLp.getDnsServers();
8815 log("Setting DNS servers for network " + netId + " to " + dnses);
8816 }
Erik Klineb9888902016-04-05 13:30:49 +09008817 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008818 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008819 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008820 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008821 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008822 }
Erik Kline54e35c02017-04-07 15:29:29 +09008823 }
8824
Junyu Lai970963e2022-10-25 15:46:47 +08008825 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8826 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008827 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8828 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008829 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8830 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008831
8832 if (!wasFiltering && !needsFiltering) {
8833 // Nothing to do.
8834 return;
8835 }
8836
8837 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8838 // Nothing changed.
8839 return;
8840 }
8841
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008842 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008843 if (ranges == null || ranges.isEmpty()) {
8844 return;
8845 }
8846
Qingxi Libb8da982020-01-17 17:54:27 -08008847 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008848 // TODO: this create a window of opportunity for apps to receive traffic between the time
8849 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008850 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008851 // old rules are being removed.
8852 if (wasFiltering) {
8853 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8854 }
8855 if (needsFiltering) {
8856 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8857 }
8858 }
8859
Valentin Iftime9fa35092019-09-24 13:32:13 +02008860 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008861 if (mWolSupportedInterfaces == null) {
8862 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008863 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008864 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008865 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8866 }
8867
Luke Huangb913c812018-08-24 20:33:16 +08008868 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008869 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008870 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008871 }
8872 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008873 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008874 }
Luke Huangb913c812018-08-24 20:33:16 +08008875 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008876 }
8877
Chalard Jean62edfd82019-12-02 18:39:29 +09008878 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8879 @NonNull final NetworkCapabilities newNc) {
8880 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8881 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008882 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008883 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008884 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008885 } catch (RemoteException | ServiceSpecificException e) {
8886 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008887 }
8888 }
8889 }
8890
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008891 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008892 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008893 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008894 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008895 underlyingNetworks = underlyingNetworksOrDefault(
8896 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008897 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008898 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8899 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008900 // metered if any underlying is metered, or originally declared metered by the agent.
8901 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008902 boolean roaming = false; // roaming if any underlying is roaming
8903 boolean congested = false; // congested if any underlying is congested
8904 boolean suspended = true; // suspended if all underlying are suspended
8905
8906 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008907 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008908 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008909 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008910 for (Network underlyingNetwork : underlyingNetworks) {
8911 final NetworkAgentInfo underlying =
8912 getNetworkAgentInfoForNetwork(underlyingNetwork);
8913 if (underlying == null) continue;
8914
8915 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8916 hadUnderlyingNetworks = true;
8917 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008918 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008919 }
8920
8921 // Merge capabilities of this underlying network. For bandwidth, assume the
8922 // worst case.
8923 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8924 underlyingCaps.getLinkDownstreamBandwidthKbps());
8925 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8926 underlyingCaps.getLinkUpstreamBandwidthKbps());
8927 // If this underlying network is metered, the VPN is metered (it may cost money
8928 // to send packets on this network).
8929 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8930 // If this underlying network is roaming, the VPN is roaming (the billing structure
8931 // is different than the usual, local one).
8932 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8933 // If this underlying network is congested, the VPN is congested (the current
8934 // condition of the network affects the performance of this network).
8935 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8936 // If this network is not suspended, the VPN is not suspended (the VPN
8937 // is able to transfer some data).
8938 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008939 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008940 }
8941 }
8942 if (!hadUnderlyingNetworks) {
8943 // No idea what the underlying networks are; assume reasonable defaults
8944 metered = true;
8945 roaming = false;
8946 congested = false;
8947 suspended = false;
8948 }
8949
Chalard Jean1d420b32022-10-12 16:39:37 +09008950 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008951 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8952 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8953 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8954 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8955 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8956 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008957 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008958 }
8959
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008960 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008961 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8962 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8963 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008964 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008965 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008966 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008967 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008968 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8969 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008970 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008971 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008972 if (nai.everConnected()
8973 && !nai.isVPN()
8974 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008975 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008976 // does not cause any request (that is not a listen) currently matching that agent to
8977 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008978 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008979 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008980 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008981 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008982 }
8983
Paul Jensen53f08952015-06-16 14:27:36 -04008984 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008985 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008986 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008987 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008988 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008989 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008990 }
Chalard Jean254bd162022-08-25 13:04:51 +09008991 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008992 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008993 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008994 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008995 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008996 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008997 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008998 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008999 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009000 }
Chalard Jean254bd162022-08-25 13:04:51 +09009001 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08009002 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9003 } else {
9004 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9005 }
lucasline117e2e2019-10-22 18:27:33 +08009006 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009007
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009008 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09009009 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
9010 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009011 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09009012 }
9013
Lorenzo Colittibd079452021-07-02 11:47:57 +09009014 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09009015 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09009016 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009017 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009018 }
9019
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009020 return newNc;
9021 }
9022
Lorenzo Colitti44840702021-01-11 22:27:57 +09009023 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
9024 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
9025 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9026 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9027 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9028 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9029 if (prevSuspended != suspended) {
9030 // TODO (b/73132094) : remove this call once the few users of onSuspended and
9031 // onResumed have been removed.
9032 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
9033 : ConnectivityManager.CALLBACK_RESUMED);
9034 }
9035 if (prevSuspended != suspended || prevRoaming != roaming) {
9036 // updateNetworkInfo will mix in the suspended info from the capabilities and
9037 // take appropriate action for the network having possibly changed state.
9038 updateNetworkInfo(nai, nai.networkInfo);
9039 }
9040 }
9041
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009042 /**
9043 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
9044 *
9045 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
9046 * capabilities we manage and store in {@code nai}, such as validated status and captive
9047 * portal status)
9048 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
9049 * potentially triggers rematches.
9050 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
9051 * change.)
9052 *
9053 * @param oldScore score of the network before any of the changes that prompted us
9054 * to call this function.
9055 * @param nai the network having its capabilities updated.
9056 * @param nc the new network capabilities.
9057 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009058 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09009059 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009060 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009061 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09009062 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
9063 if (null != differences) {
9064 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
9065 }
Chalard Jean62edfd82019-12-02 18:39:29 +09009066 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09009067 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009068
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009069 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09009070 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09009071 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009072
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009073 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009074 // If the requestable capabilities haven't changed, and the score hasn't changed, then
9075 // the change we're processing can't affect any requests, it can only affect the listens
9076 // on this network. We might have been called by rematchNetworkAndRequests when a
9077 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09009078 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009079 } else {
9080 // If the requestable capabilities have changed or the score changed, we can't have been
9081 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009082 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009083 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009084 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009085 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009086
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009087 final boolean oldMetered = prevNc.isMetered();
9088 final boolean newMetered = newNc.isMetered();
9089 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009090
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009091 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009092 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9093 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009094 }
junyulaif2c67e42018-08-07 19:50:45 +08009095
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009096 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9097 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009098
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009099 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009100 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009101 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009102 }
9103
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009104 // This network might have been underlying another network. Propagate its capabilities.
9105 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009106
Ken Chen5a35cf92023-10-07 07:54:22 +08009107 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009108 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009109 }
lucaslin53e8a262021-06-08 01:43:59 +08009110
9111 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009112 }
9113
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009114 /** Convenience method to update the capabilities for a given network. */
9115 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009116 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009117 }
9118
Yang Sun29037f62023-12-04 10:31:58 +08009119 private void maybeApplyMulticastRoutingConfig(@NonNull final NetworkAgentInfo nai,
9120 final LocalNetworkConfig oldConfig,
9121 final LocalNetworkConfig newConfig) {
9122 final MulticastRoutingConfig oldUpstreamConfig =
9123 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9124 oldConfig.getUpstreamMulticastRoutingConfig();
9125 final MulticastRoutingConfig oldDownstreamConfig =
9126 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9127 oldConfig.getDownstreamMulticastRoutingConfig();
9128 final MulticastRoutingConfig newUpstreamConfig =
9129 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9130 newConfig.getUpstreamMulticastRoutingConfig();
9131 final MulticastRoutingConfig newDownstreamConfig =
9132 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9133 newConfig.getDownstreamMulticastRoutingConfig();
9134
9135 if (oldUpstreamConfig.equals(newUpstreamConfig) &&
9136 oldDownstreamConfig.equals(newDownstreamConfig)) {
9137 return;
9138 }
9139
9140 final String downstreamNetworkName = nai.linkProperties.getInterfaceName();
9141 final LocalNetworkInfo lni = localNetworkInfoForNai(nai);
9142 final Network upstreamNetwork = lni.getUpstreamNetwork();
9143
9144 if (upstreamNetwork != null) {
9145 final String upstreamNetworkName =
9146 getLinkProperties(upstreamNetwork).getInterfaceName();
9147 applyMulticastRoutingConfig(downstreamNetworkName, upstreamNetworkName, newConfig);
9148 }
9149 }
9150
9151 private void applyMulticastRoutingConfig(@NonNull String localNetworkInterfaceName,
9152 @NonNull String upstreamNetworkInterfaceName,
9153 @NonNull final LocalNetworkConfig config) {
9154 if (mMulticastRoutingCoordinatorService == null) return;
9155
9156 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9157 upstreamNetworkInterfaceName, config.getUpstreamMulticastRoutingConfig());
9158 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9159 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9160 config.getDownstreamMulticastRoutingConfig());
9161 }
9162
9163 private void disableMulticastRouting(@NonNull String localNetworkInterfaceName,
9164 @NonNull String upstreamNetworkInterfaceName) {
9165 if (mMulticastRoutingCoordinatorService == null) return;
9166
9167 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9168 upstreamNetworkInterfaceName, MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9169 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9170 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9171 MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9172 }
9173
Chalard Jean1e4c2182023-10-06 18:45:53 +09009174 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009175 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009176 @Nullable final LocalNetworkConfig oldConfig,
9177 @NonNull final LocalNetworkConfig newConfig) {
9178 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009179 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9180 return;
9181 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009182
Chalard Jean4fe23392023-10-17 23:02:27 +09009183 if (VDBG) {
9184 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9185 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009186 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
Chalard Jean1e4c2182023-10-06 18:45:53 +09009187 configBuilder.setUpstreamMulticastRoutingConfig(
9188 newConfig.getUpstreamMulticastRoutingConfig());
9189 configBuilder.setDownstreamMulticastRoutingConfig(
9190 newConfig.getDownstreamMulticastRoutingConfig());
9191
9192 final NetworkRequest oldRequest =
9193 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9194 final NetworkCapabilities oldCaps =
9195 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9196 final NetworkRequestInfo oldNri =
9197 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9198 final NetworkAgentInfo oldSatisfier =
9199 null == oldNri ? null : oldNri.getSatisfier();
9200 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9201 final NetworkCapabilities newCaps =
9202 (null == newRequest) ? null : newRequest.networkCapabilities;
9203 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9204 if (null != oldRequest && requestUpdated) {
9205 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9206 if (null == newRequest && null != oldSatisfier) {
9207 // If there is an old satisfier, but no new request, then remove the old upstream.
9208 removeLocalNetworkUpstream(nai, oldSatisfier);
9209 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009210 // When there is a new request, the rematch sees the new request and sends the
9211 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9212 // But here there is no new request, so the rematch won't see anything. Send
9213 // callbacks to apps now to tell them about the loss of upstream.
9214 notifyNetworkCallbacks(nai,
9215 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009216 return;
9217 }
9218 }
9219 if (null != newRequest && requestUpdated) {
9220 // File the new request if :
9221 // - it has changed (requestUpdated), or
9222 // - it's the first time this local info (null == oldConfig)
9223 // is updated and the request has not been filed yet.
9224 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9225 // upstream (the best) but never request it to be brought up.
9226 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9227 nextNetworkRequestId(), LISTEN_FOR_BEST);
9228 configBuilder.setUpstreamSelector(nr);
9229 final NetworkRequestInfo nri = new NetworkRequestInfo(
9230 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9231 0 /* callbackFlags */, null /* attributionTag */);
9232 if (null != oldSatisfier) {
9233 // Set the old satisfier in the new NRI so that the rematch will see any changes
9234 nri.setSatisfier(oldSatisfier, nr);
9235 }
9236 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009237 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9238 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9239 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009240 handleRegisterNetworkRequest(nri);
9241 } else {
9242 configBuilder.setUpstreamSelector(oldRequest);
9243 nai.localNetworkConfig = configBuilder.build();
9244 }
Yang Sun29037f62023-12-04 10:31:58 +08009245 maybeApplyMulticastRoutingConfig(nai, oldConfig, newConfig);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009246 }
9247
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009248 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009249 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009250 *
9251 * Ingress interface filtering enforces that all apps under the given network can only receive
9252 * packets from the network's interface (and loopback). This is important for VPNs because
9253 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9254 * non-VPN interfaces.
9255 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009256 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009257 * 1. the network is an app VPN (not legacy VPN)
9258 * 2. the VPN does not allow bypass
9259 * 3. the VPN is fully-routed
9260 * 4. the VPN interface is non-null
9261 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009262 * @see INetd#firewallAddUidInterfaceRules
9263 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009264 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009265 @Nullable
9266 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009267 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009268 if (nc == null || lp == null) return null;
9269 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009270 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009271 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009272 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009273 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009274 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009275 && !lp.hasExcludeRoute()) {
9276 return lp.getInterfaceName();
9277 }
9278 return null;
9279 }
9280
9281 /**
9282 * Returns whether we need to set interface filtering rule or not
9283 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009284 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009285 String isolationIface) {
9286 // Allow rules are always needed if VPN isolation is enabled.
9287 if (isolationIface != null) return true;
9288
9289 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9290 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9291 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009292 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009293 }
9294
Chiachang Wang28afaff2020-12-10 22:24:47 +08009295 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9296 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9297 int index = 0;
9298 for (UidRange range : ranges) {
9299 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9300 index++;
9301 }
9302 return stableRanges;
9303 }
9304
Chalard Jeane6c95272022-01-25 21:04:21 +09009305 private static UidRangeParcel[] intsToUidRangeStableParcels(
9306 final @NonNull ArraySet<Integer> uids) {
9307 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9308 int index = 0;
9309 for (int uid : uids) {
9310 stableRanges[index] = new UidRangeParcel(uid, uid);
9311 index++;
9312 }
9313 return stableRanges;
9314 }
9315
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009316 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9317 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9318 for (int i = 0; i < ranges.length; i++) {
9319 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9320 }
9321 return stableRanges;
9322 }
9323
Motomu Utsumi93a22182023-03-16 17:04:21 +09009324 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009325 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009326 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9327 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009328 if (mDeps.isAtLeastU()) {
9329 final Set<Integer> exemptUidSet = new ArraySet<>();
9330 for (final int uid: exemptUids) {
9331 exemptUidSet.add(uid);
9332 }
9333 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9334 } else {
9335 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9336 }
Ken Chen5e65a852020-12-24 12:59:10 +08009337 } catch (Exception e) {
9338 loge("Exception in socket destroy: ", e);
9339 }
9340 }
9341 }
9342
paulhuaa0743d2021-05-26 21:56:03 +08009343 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009344 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009345 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9346 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9347 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009348 exemptUids[0] = VPN_UID;
9349 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009350 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9351
Motomu Utsumi6345e462023-03-13 13:24:50 +09009352 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009353 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009354 try {
9355 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009356 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009357 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009358 } else {
paulhu0e79d952021-06-09 16:11:35 +08009359 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009360 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009361 }
9362 } catch (Exception e) {
9363 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9364 " on netId " + nai.network.netId + ". " + e);
9365 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009366 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009367 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009368 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009369
lucaslin53e8a262021-06-08 01:43:59 +08009370 private boolean isProxySetOnAnyDefaultNetwork() {
9371 ensureRunningOnConnectivityServiceThread();
9372 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9373 final NetworkAgentInfo nai = nri.getSatisfier();
9374 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9375 return true;
9376 }
9377 }
9378 return false;
9379 }
9380
9381 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9382 NetworkCapabilities newNc) {
9383 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9384 // the proxy might be changed since the default network satisfied by the apps might also
9385 // changed.
9386 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9387 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009388 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9389 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009390 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009391 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9392 mProxyTracker.sendProxyBroadcast();
9393 }
9394 }
9395
Chalard Jeane6c95272022-01-25 21:04:21 +09009396 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9397 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009398 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9399 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009400 if (null == prevRanges) prevRanges = new ArraySet<>();
9401 if (null == newRanges) newRanges = new ArraySet<>();
9402 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9403
9404 prevRanges.removeAll(newRanges);
9405 newRanges.removeAll(prevRangesCopy);
9406
9407 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009408 // When updating the VPN uid routing rules, add the new range first then remove the old
9409 // range. If old range were removed first, there would be a window between the old
9410 // range being removed and the new range being added, during which UIDs contained
9411 // in both ranges are not subject to any VPN routing rules. Adding new range before
9412 // removing old range works because, unlike the filtering rules below, it's possible to
9413 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009414 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9415 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9416 // [1-5] & [1-2],[4-5] == [3]
9417 // Then we can do:
9418 // maybeCloseSockets([3])
9419 // mNetd.networkAddUidRanges([1-2],[4-5])
9420 // mNetd.networkRemoveUidRanges([1-5])
9421 // maybeCloseSockets([3])
9422 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9423 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009424 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009425 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009426 }
9427 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009428 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009429 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009430 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9431 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009432 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9433 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009434 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009435 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009436 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9437 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9438 // were added first and then newRanges got removed later, there would be only one uid
9439 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9440 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9441 // Note that this is in contrast with the (more robust) update of VPN routing rules
9442 // above, where the addition of new ranges happens before the removal of old ranges.
9443 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9444 // to be removed will never overlap with the new range to be added.
9445 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009446 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9447 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009448 }
9449 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009450 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009451 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009452 } catch (Exception e) {
9453 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009454 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009455 }
9456 }
9457
Chalard Jeande665262022-02-25 16:12:12 +09009458 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009459 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9460 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009461 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9462 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009463 if (prevEmpty && newEmpty) return;
9464
9465 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009466 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009467 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009468 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009469
9470 if (prevUids.equals(newUids)) return;
9471
9472 // This implementation is very simple and vastly faster for sets of Integers than
9473 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9474 // a key computed from the value and has storage for that.
9475 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9476 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9477 toRemove.removeAll(newUids);
9478 toAdd.removeAll(prevUids);
9479
9480 try {
9481 if (!toAdd.isEmpty()) {
9482 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9483 nai.network.netId,
9484 intsToUidRangeStableParcels(toAdd),
9485 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9486 }
9487 if (!toRemove.isEmpty()) {
9488 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9489 nai.network.netId,
9490 intsToUidRangeStableParcels(toRemove),
9491 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9492 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009493 } catch (ServiceSpecificException e) {
9494 // Has the interface disappeared since the network was built ?
9495 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009496 } catch (RemoteException e) {
9497 // Netd died. This usually causes a runtime restart anyway.
9498 }
9499 }
9500
Junyu Lai2ed7d412022-10-07 16:52:21 +08009501 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9502 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009503 ensureRunningOnConnectivityServiceThread();
9504
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009505 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009506 // Ignore updates for disconnected networks
9507 return;
9508 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009509 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009510 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009511 + "; created=" + nai.getCreatedTime()
9512 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009513 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009514 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9515 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009516 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009517 }
9518
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009519 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9520 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009521 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009522 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009523 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009524 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9525 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9526 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009527 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9528 // need to be sent as a separate extra.
9529 final NetworkRequest req = nri.isMultilayerRequest()
9530 ? nri.getActiveRequest()
9531 // Non-multilayer listen requests do not have an active request
9532 : nri.mRequests.get(0);
9533 if (req == null) {
9534 Log.wtf(TAG, "No request in NRI " + nri);
9535 }
9536 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009537 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009538 sendIntent(nri.mPendingIntent, intent);
9539 }
9540 // else not handled
9541 }
9542
Michael Groover73f69482023-01-27 11:01:25 -06009543 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9544 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009545 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9546 mPendingIntentWakeLock.acquire();
9547 try {
9548 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009549 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009550 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009551 // Explicitly disallow the receiver from starting activities, to prevent apps from
9552 // utilizing the PendingIntent as a backdoor to do this.
9553 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9554 }
9555 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9556 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009557 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009558 } catch (PendingIntent.CanceledException e) {
9559 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9560 mPendingIntentWakeLock.release();
9561 releasePendingNetworkRequest(pendingIntent);
9562 }
9563 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9564 }
9565
9566 @Override
9567 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9568 String resultData, Bundle resultExtras) {
9569 if (DBG) log("Finished sending " + pendingIntent);
9570 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009571 // Release with a delay so the receiving client has an opportunity to put in its
9572 // own request.
9573 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009574 }
9575
Chalard Jean22350c92023-10-07 19:21:45 +09009576 @Nullable
9577 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9578 if (!nai.isLocalNetwork()) return null;
9579 final Network upstream;
9580 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9581 if (null == selector) {
9582 upstream = null;
9583 } else {
9584 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9585 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9586 upstream = (null == satisfier) ? null : satisfier.network;
9587 }
9588 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9589 }
9590
Chalard Jean46bfbf02022-02-02 00:56:25 +09009591 // networkAgent is only allowed to be null if notificationType is
9592 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9593 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009594 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009595 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009596 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009597 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009598 // Default request has no msgr. Also prevents callbacks from being invoked for
9599 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9600 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9601 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009602 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009603 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009604 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009605 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009606 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009607 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009608 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009609 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9610 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009611 }
Roshan Pius951c0032020-12-22 15:10:42 -08009612 final boolean includeLocationSensitiveInfo =
9613 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009614 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009615 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009616 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009617 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009618 networkCapabilitiesRestrictedForCallerPermissions(
9619 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9620 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009621 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009622 nri.mCallingAttributionTag);
9623 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009624 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9625 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009626 // The local network info is often null, so can't use the static putParcelable
9627 // method here.
9628 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9629 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009630 // For this notification, arg1 contains the blocked status.
9631 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009632 break;
9633 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009634 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009635 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009636 break;
9637 }
9638 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009639 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009640 final NetworkCapabilities netCap =
9641 networkCapabilitiesRestrictedForCallerPermissions(
9642 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9643 putParcelable(
9644 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009645 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009646 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009647 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009648 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009649 break;
9650 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009651 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009652 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9653 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009654 break;
9655 }
junyulaif2c67e42018-08-07 19:50:45 +08009656 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009657 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009658 msg.arg1 = arg1;
9659 break;
9660 }
Chalard Jean22350c92023-10-07 19:21:45 +09009661 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9662 if (!networkAgent.isLocalNetwork()) {
9663 Log.wtf(TAG, "Callback for local info for a non-local network");
9664 return;
9665 }
9666 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9667 break;
9668 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009669 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009670 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009671 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009672 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009673 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009674 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009675 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009676 }
James Mattis45d81842021-01-10 14:24:24 -08009677 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009678 } catch (RemoteException e) {
9679 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009680 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009681 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009682 }
9683
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009684 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9685 bundle.putParcelable(t.getClass().getSimpleName(), t);
9686 }
9687
Chalard Jean0702f982021-09-16 21:50:07 +09009688 /**
9689 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9690 *
9691 * When a request should be assigned to a new network, it is normally lingered to give
9692 * time for apps to gracefully migrate their connections. When both networks are on the same
9693 * radio, but that radio can't do time-sharing efficiently, this may end up being
9694 * counter-productive because any traffic on the old network may drastically reduce the
9695 * performance of the new network.
9696 * The stack supports a configuration to let modem vendors state that their radio can't
9697 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9698 * from one cell network to another can't be done gracefully.
9699 *
9700 * @param oldNai the old network serving the request
9701 * @param newNai the new network serving the request
9702 * @return whether the switch can be graceful
9703 */
9704 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9705 @NonNull final NetworkAgentInfo newSatisfier) {
9706 if (mCellularRadioTimesharingCapable) return true;
9707 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9708 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9709 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9710 }
9711
Paul Jensenaf94b982014-09-30 15:37:41 -04009712 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009713 if (nai.numRequestNetworkRequests() != 0) {
9714 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9715 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009716 // Ignore listening and track default requests.
9717 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009718 loge("Dead network still had at least " + nr);
9719 break;
9720 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009721 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009722 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009723 }
9724
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009725 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9726 if (oldNetwork == null) {
9727 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9728 return;
9729 }
Chalard Jean49707572019-12-10 21:07:02 +09009730 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009731
9732 // If we get here it means that the last linger timeout for this network expired. So there
9733 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009734 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009735
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009736 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009737 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009738 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009739 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009740 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009741 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009742 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009743 }
9744
James Mattise3ef1912020-12-20 11:09:58 -08009745 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9746 boolean isDefaultChanged = false;
9747 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9748 final NetworkReassignment.RequestReassignment reassignment =
9749 changes.getReassignment(defaultRequestInfo);
9750 if (null == reassignment) {
9751 continue;
9752 }
9753 // reassignment only contains those instances where the satisfying network changed.
9754 isDefaultChanged = true;
9755 // Notify system services of the new default.
9756 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9757 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009758
James Mattise3ef1912020-12-20 11:09:58 -08009759 if (isDefaultChanged) {
9760 // Hold a wakelock for a short time to help apps in migrating to a new default.
9761 scheduleReleaseNetworkTransitionWakelock();
9762 }
9763 }
9764
Aaron Huang9fe47be2021-06-08 13:11:45 +08009765 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9766 if (null == oldDefaultNetwork) return;
9767 // The network stopped being the default. If it was using a PAC proxy, then the
9768 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9769 // to the local proxy server, which would forward them over the newly default network.
9770 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9771 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9772 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9773 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9774 }
9775
James Mattise3ef1912020-12-20 11:09:58 -08009776 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9777 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9778 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9779 if (DBG) {
9780 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9781 }
Chalard Jean8e382112019-12-03 20:45:30 +09009782
James Mattisd31bdfa2020-12-23 16:37:26 -08009783 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9784 if (newDefaultNetwork != null) {
9785 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009786 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009787
James Mattisd31bdfa2020-12-23 16:37:26 -08009788 // Set an app level managed default and return since further processing only applies to the
9789 // default network.
9790 if (mDefaultRequest != nri) {
9791 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9792 return;
9793 }
9794
9795 makeDefaultNetwork(newDefaultNetwork);
9796
James Mattise3ef1912020-12-20 11:09:58 -08009797 if (oldDefaultNetwork != null) {
9798 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9799 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09009800 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009801 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009802 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009803 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009804 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009805 updateTcpBufferSizes(null != newDefaultNetwork
9806 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009807 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009808 }
9809
James Mattisd31bdfa2020-12-23 16:37:26 -08009810 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9811 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9812 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9813 try {
9814 if (VDBG) {
9815 log("Setting default network for " + nri
9816 + " using UIDs " + nri.getUids()
9817 + " with old network " + (oldDefaultNetwork != null
9818 ? oldDefaultNetwork.network().getNetId() : "null")
9819 + " and new network " + (newDefaultNetwork != null
9820 ? newDefaultNetwork.network().getNetId() : "null"));
9821 }
9822 if (nri.getUids().isEmpty()) {
9823 throw new IllegalStateException("makeDefaultForApps called without specifying"
9824 + " any applications to set as the default." + nri);
9825 }
9826 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009827 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009828 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009829 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009830 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009831 }
9832 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009833 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009834 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009835 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009836 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009837 }
9838 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009839 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009840 }
9841 }
9842
Junyu Lai35665cc2022-12-19 17:37:48 +08009843 /**
9844 * Collect restricted uid ranges for the given network and UserHandle, these uids
9845 * are not restricted for matched enterprise networks but being restricted for non-matched
9846 * enterprise networks and non-enterprise networks.
9847 */
9848 @NonNull
9849 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9850 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9851 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9852 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9853 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9854
9855 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9856 // The NC is built from a `ProfileNetworkPreference` which has only one
9857 // enterprise ID, so it's guaranteed to have exactly one.
9858 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9859 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9860 continue;
9861 }
9862 }
9863
9864 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9865 pref.capabilities.getUidRanges())) {
9866 throw new IllegalArgumentException(
9867 "Overlapping uid range in preference: " + pref);
9868 }
9869 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9870 }
9871 return restrictedUidRanges;
9872 }
9873
9874 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009875 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009876 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009877
Junyu Lai35665cc2022-12-19 17:37:48 +08009878 ensureRunningOnConnectivityServiceThread();
9879 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9880 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9881 .getUserHandles(true /* excludeDying */);
9882 if (users.isEmpty()) {
9883 throw new IllegalStateException("No user is available");
9884 }
9885
9886 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9887 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9888 for (final UserHandle user : users) {
9889 final ArraySet<UidRange> restrictedUidRanges =
9890 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9891 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9892 UidRange.createForUser(user), restrictedUidRanges));
9893 }
9894
9895 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9896 configs.add(new NativeUidRangeConfig(
9897 nai.network.netId, rangesParcel, 0 /* subPriority */));
9898 }
9899
9900 // The netd API replaces the previous configs with the current configs.
9901 // Thus, for network disconnection or preference removal, no need to
9902 // unset previous config. Instead, collecting all currently needed
9903 // configs and issue to netd.
9904 try {
9905 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9906 } catch (ServiceSpecificException e) {
9907 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009908 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009909 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009910 // Netd died. This will cause a runtime restart anyway.
9911 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009912 }
9913 }
9914
James Mattisd31bdfa2020-12-23 16:37:26 -08009915 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9916 try {
9917 if (null != newDefaultNetwork) {
9918 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9919 } else {
9920 mNetd.networkClearDefault();
9921 }
9922 } catch (RemoteException | ServiceSpecificException e) {
9923 loge("Exception setting default network :" + e);
9924 }
9925 }
9926
Chalard Jean05cbe972019-12-09 11:50:38 +09009927 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009928 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009929 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009930 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009931 processNewlySatisfiedListenRequests(nai);
9932 }
9933
9934 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009935 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9936 if (nri.isMultilayerRequest()) {
9937 continue;
9938 }
9939 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009940 if (!nr.isListen()) continue;
9941 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009942 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009943 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9944 }
9945 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009946 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009947
Chalard Jeancd397a22019-11-22 22:33:33 +09009948 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009949 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9950 if (nri.isMultilayerRequest()) {
9951 continue;
9952 }
9953 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009954 if (!nr.isListen()) continue;
9955 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9956 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009957 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009958 }
9959 }
9960 }
9961
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009962 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009963 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009964 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009965 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009966 @Nullable public final NetworkRequest mOldNetworkRequest;
9967 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009968 @Nullable public final NetworkAgentInfo mOldNetwork;
9969 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009970 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009971 @Nullable final NetworkRequest oldNetworkRequest,
9972 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009973 @Nullable final NetworkAgentInfo oldNetwork,
9974 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009975 mNetworkRequestInfo = networkRequestInfo;
9976 mOldNetworkRequest = oldNetworkRequest;
9977 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009978 mOldNetwork = oldNetwork;
9979 mNewNetwork = newNetwork;
9980 }
Chalard Jean49707572019-12-10 21:07:02 +09009981
9982 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009983 final NetworkRequest requestToShow = null != mNewNetworkRequest
9984 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9985 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009986 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9987 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009988 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009989 }
9990
Chalard Jean46a62372019-12-10 21:25:24 +09009991 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009992
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009993 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009994 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009995 }
9996
9997 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009998 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009999 // The code is never supposed to add two reassignments of the same request. Make
10000 // sure this stays true, but without imposing this expensive check on all
10001 // reassignments on all user devices.
10002 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -080010003 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +090010004 throw new IllegalStateException("Trying to reassign ["
10005 + reassignment + "] but already have ["
10006 + existing + "]");
10007 }
10008 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +090010009 }
Chalard Jean46a62372019-12-10 21:25:24 +090010010 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010011 }
10012
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010013 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +090010014 // the passed request.
10015 @Nullable
10016 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010017 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010018 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010019 }
10020 return null;
10021 }
Chalard Jean49707572019-12-10 21:07:02 +090010022
10023 public String toString() {
10024 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
10025 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +090010026 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010027 for (final RequestReassignment rr : getRequestReassignments()) {
10028 sj.add(rr.toString());
10029 }
10030 return sj.toString();
10031 }
10032
10033 public String debugString() {
10034 final StringBuilder sb = new StringBuilder();
10035 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +090010036 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010037 for (final RequestReassignment rr : getRequestReassignments()) {
10038 sb.append("\n ").append(rr);
10039 }
10040 return sb.append("\n").toString();
10041 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010042 }
10043
Chalard Jean24344d72019-12-04 13:32:31 +090010044 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +090010045 @Nullable final NetworkRequest previousRequest,
10046 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +090010047 @Nullable final NetworkAgentInfo previousSatisfier,
10048 @Nullable final NetworkAgentInfo newSatisfier,
10049 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -080010050 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +090010051 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +090010052 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010053 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010054 log(" accepting network in place of " + previousSatisfier.toShortString()
10055 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010056 }
James Mattisa076c532020-12-02 14:12:41 -080010057 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010058 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +090010059 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +090010060 // If this network switch can't be supported gracefully, the request is not
10061 // lingered. This allows letting go of the network sooner to reclaim some
10062 // performance on the new network, since the radio can't do both at the same
10063 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010064 //
10065 // Also don't linger the request if the old network has been destroyed.
10066 // A destroyed network does not provide actual network connectivity, so
10067 // lingering it is not useful. In particular this ensures that a destroyed
10068 // network is outscored by its replacement,
10069 // then it is torn down immediately instead of being lingered, and any apps that
10070 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +090010071 previousSatisfier.lingerRequest(previousRequest.requestId, now);
10072 }
Chalard Jean24344d72019-12-04 13:32:31 +090010073 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010074 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010075 }
junyulai0ac374f2020-12-14 18:41:52 +080010076
10077 // To prevent constantly CPU wake up for nascent timer, if a network comes up
10078 // and immediately satisfies a request then remove the timer. This will happen for
10079 // all networks except in the case of an underlying network for a VCN.
10080 if (newSatisfier.isNascent()) {
10081 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +080010082 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010083 }
10084
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010085 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -080010086 newSatisfier.unlingerRequest(newRequest.requestId);
10087 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +080010088 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -080010089 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010090 }
Chalard Jeana8ac2302021-03-01 22:16:08 +090010091 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010092 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010093 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -080010094 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010095 }
James Mattisa076c532020-12-02 14:12:41 -080010096 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010097 }
James Mattisa076c532020-12-02 14:12:41 -080010098 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010099 }
10100
James Mattisa076c532020-12-02 14:12:41 -080010101 /**
10102 * This function is triggered when something can affect what network should satisfy what
10103 * request, and it computes the network reassignment from the passed collection of requests to
10104 * network match to the one that the system should now have. That data is encoded in an
10105 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
10106 * satisfier.
10107 *
10108 * After the reassignment is computed, it is applied to the state objects.
10109 *
10110 * @param networkRequests the nri objects to evaluate for possible network reassignment
10111 * @return NetworkReassignment listing of proposed network assignment changes
10112 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010113 @NonNull
James Mattisa076c532020-12-02 14:12:41 -080010114 private NetworkReassignment computeNetworkReassignment(
10115 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090010116 final NetworkReassignment changes = new NetworkReassignment();
10117
Chalard Jeanc81d4c32021-04-07 17:06:19 +090010118 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090010119 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010120 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +090010121 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +090010122 }
Chalard Jean857a1712019-12-10 21:08:07 +090010123
James Mattisa076c532020-12-02 14:12:41 -080010124 for (final NetworkRequestInfo nri : networkRequests) {
10125 // Non-multilayer listen requests can be ignored.
10126 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
10127 continue;
10128 }
10129 NetworkAgentInfo bestNetwork = null;
10130 NetworkRequest bestRequest = null;
10131 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090010132 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080010133 // Stop evaluating as the highest possible priority request is satisfied.
10134 if (null != bestNetwork) {
10135 bestRequest = req;
10136 break;
10137 }
10138 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010139 if (null == bestNetwork && isDefaultBlocked(nri)) {
10140 // Remove default networking if disallowed for managed default requests.
10141 bestNetwork = mNoServiceNetwork;
10142 }
10143 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010144 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010145 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010146 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010147 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010148 }
10149 return changes;
10150 }
10151
James Mattisa076c532020-12-02 14:12:41 -080010152 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10153 return new HashSet<>(mNetworkRequests.values());
10154 }
10155
Paul Jensenc88b39b2015-06-16 14:27:36 -040010156 /**
James Mattisa076c532020-12-02 14:12:41 -080010157 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010158 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010159 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010160 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010161 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10162 }
10163
10164 /**
10165 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10166 * being disconnected.
10167 */
10168 private void rematchNetworksAndRequests(
10169 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10170 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010171 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010172 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010173 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010174 final long computed = SystemClock.elapsedRealtime();
10175 applyNetworkReassignment(changes, start);
10176 final long applied = SystemClock.elapsedRealtime();
10177 issueNetworkNeeds();
10178 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010179 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010180 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10181 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010182 log(changes.debugString());
10183 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010184 // Shorter form, only one line of log
10185 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10186 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010187 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010188 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010189
Chalard Jean1e4c2182023-10-06 18:45:53 +090010190 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10191 @Nullable final NetworkAgentInfo nai2) {
10192 if (null == nai1) return null == nai2;
10193 if (null == nai2) return false;
10194 return nai1.linkProperties.getInterfaceName()
10195 .equals(nai2.linkProperties.getInterfaceName());
10196 }
10197
Chalard Jeand7f762d2019-12-10 19:01:29 +090010198 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010199 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010200 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010201
10202 // Since most of the time there are only 0 or 1 background networks, it would probably
10203 // be more efficient to just use an ArrayList here. TODO : measure performance
10204 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10205 for (final NetworkAgentInfo nai : nais) {
10206 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10207 }
10208
Chalard Jeand7f762d2019-12-10 19:01:29 +090010209 // First, update the lists of satisfied requests in the network agents. This is necessary
10210 // because some code later depends on this state to be correct, most prominently computing
10211 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010212 for (final NetworkReassignment.RequestReassignment event :
10213 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010214 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10215 event.mOldNetworkRequest, event.mNewNetworkRequest,
10216 event.mOldNetwork, event.mNewNetwork,
10217 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010218 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010219
James Mattise3ef1912020-12-20 11:09:58 -080010220 // Process default network changes if applicable.
10221 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010222
Chalard Jean68eab722023-11-16 17:00:04 +090010223 // Update forwarding rules for the upstreams of local networks. Do this before sending
10224 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10225 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10226 // onAvailable so clients know what network the change is about. Store such changes in
10227 // an array that's only allocated if necessary (because it's almost never necessary).
10228 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10229 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10230 if (!nai.isLocalNetwork()) continue;
10231 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10232 if (null == nr) continue; // No upstream for this local network
10233 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10234 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10235 if (null == change) continue; // No change in upstreams for this network
10236 final String fromIface = nai.linkProperties.getInterfaceName();
10237 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10238 || change.mOldNetwork.isDestroyed()) {
10239 // There can be a change with the same interface name if the new network is the
10240 // replacement for the old network that was unregisteredAfterReplacement.
10241 try {
10242 if (null != change.mOldNetwork) {
10243 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10244 change.mOldNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010245 disableMulticastRouting(fromIface,
10246 change.mOldNetwork.linkProperties.getInterfaceName());
Chalard Jean68eab722023-11-16 17:00:04 +090010247 }
10248 // If the new upstream is already destroyed, there is no point in setting up
10249 // a forward (in fact, it might forward to the interface for some new network !)
10250 // Later when the upstream disconnects CS will try to remove the forward, which
10251 // is ignored with a benign log by RoutingCoordinatorService.
10252 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10253 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10254 change.mNewNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010255 applyMulticastRoutingConfig(fromIface,
10256 change.mNewNetwork.linkProperties.getInterfaceName(),
10257 nai.localNetworkConfig);
Chalard Jean68eab722023-11-16 17:00:04 +090010258 }
10259 } catch (final RemoteException e) {
10260 loge("Can't update forwarding rules", e);
10261 }
10262 }
10263 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10264 localInfoChangedAgents.add(nai);
10265 }
10266
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010267 // Notify requested networks are available after the default net is switched, but
10268 // before LegacyTypeTracker sends legacy broadcasts
10269 for (final NetworkReassignment.RequestReassignment event :
10270 changes.getRequestReassignments()) {
10271 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010272 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010273 } else {
James Mattisa076c532020-12-02 14:12:41 -080010274 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010275 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010276 }
10277 }
10278
junyulai0ac374f2020-12-14 18:41:52 +080010279 // Update the inactivity state before processing listen callbacks, because the background
10280 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010281 // just yet though, because they have to be sent after the listens are processed to keep
10282 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010283 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010284 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010285 // Rematching may have altered the inactivity state of some networks, so update all
10286 // inactivity timers. updateInactivityState reads the state from the network agent
10287 // and does nothing if the state has not changed : the source of truth is controlled
10288 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10289 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010290 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010291 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010292 }
10293 }
10294
Chalard Jeanb10ab412019-12-11 14:12:30 +090010295 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010296 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010297 // Process listen requests and update capabilities if the background state has
10298 // changed for this network. For consistency with previous behavior, send onLost
10299 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010300 processNewlyLostListenRequests(nai);
10301 if (oldBackground != nai.isBackgroundNetwork()) {
10302 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010303 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010304 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010305 }
10306
junyulai0ac374f2020-12-14 18:41:52 +080010307 for (final NetworkAgentInfo nai : inactiveNetworks) {
10308 // For nascent networks, if connecting with no foreground request, skip broadcasting
10309 // LOSING for backward compatibility. This is typical when mobile data connected while
10310 // wifi connected with mobile data always-on enabled.
10311 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010312 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010313 }
10314
Chalard Jean68eab722023-11-16 17:00:04 +090010315 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10316 if (null != localInfoChangedAgents) {
10317 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10318 notifyNetworkCallbacks(nai,
10319 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010320 }
10321 }
10322
James Mattise3ef1912020-12-20 11:09:58 -080010323 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010324
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010325 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010326 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010327 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010328 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010329 // This network has active linger timers and no requests, but is not
10330 // lingering. Linger it.
10331 //
10332 // One way (the only way?) this can happen if this network is unvalidated
10333 // and became unneeded due to another network improving its score to the
10334 // point where this network will no longer be able to satisfy any requests
10335 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010336 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010337 notifyNetworkLosing(nai, now);
10338 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010339 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010340 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010341 teardownUnneededNetwork(nai);
10342 }
10343 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010344 }
10345 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010346
Chalard Jean62edfd82019-12-02 18:39:29 +090010347 /**
10348 * Apply a change in background state resulting from rematching networks with requests.
10349 *
10350 * During rematch, a network may change background states by starting to satisfy or stopping
10351 * to satisfy a foreground request. Listens don't count for this. When a network changes
10352 * background states, its capabilities need to be updated and callbacks fired for the
10353 * capability change.
10354 *
10355 * @param nai The network that changed background states
10356 */
10357 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10358 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10359 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10360 updateNetworkPermissions(nai, newNc);
10361 nai.getAndSetNetworkCapabilities(newNc);
10362 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10363 }
10364
Chalard Jeanf0344532019-11-19 19:23:38 +090010365 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010366 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010367 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010368 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10369 changes.getReassignment(mDefaultRequest);
10370 final NetworkAgentInfo oldDefaultNetwork =
10371 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10372 final NetworkAgentInfo newDefaultNetwork =
10373 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010374
Chalard Jean5b409c72021-02-04 13:12:59 +090010375 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010376 // Maintain the illusion : since the legacy API only understands one network at a time,
10377 // if the default network changed, apps should see a disconnected broadcast for the
10378 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010379 if (oldDefaultNetwork != null) {
10380 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10381 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010382 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010383 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010384 // The new default network can be newly null if and only if the old default
10385 // network doesn't satisfy the default request any more because it lost a
10386 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010387 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010388 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010389 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010390 }
10391 }
10392
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010393 // Now that all the callbacks have been sent, send the legacy network broadcasts
10394 // as needed. This is necessary so that legacy requests correctly bind dns
10395 // requests to this network. The legacy users are listening for this broadcast
10396 // and will generally do a dns request so they can ensureRouteToHost and if
10397 // they do that before the callbacks happen they'll use the default network.
10398 //
10399 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10400 // callbacks, but if apps can receive the broadcast before the callback, they still might
10401 // have an inconsistent view of networking.
10402 //
10403 // This *does* introduce a race where if the user uses the new api
10404 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10405 // they may get old info. Reverse this after the old startUsing api is removed.
10406 // This is on top of the multiple intent sequencing referenced in the todo above.
10407 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010408 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010409 addNetworkToLegacyTypeTracker(nai);
10410 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010411 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010412 }
10413
Chalard Jean0354d8c2021-01-12 10:58:56 +090010414 private void issueNetworkNeeds() {
10415 ensureRunningOnConnectivityServiceThread();
10416 for (final NetworkOfferInfo noi : mNetworkOffers) {
10417 issueNetworkNeeds(noi);
10418 }
10419 }
10420
10421 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10422 ensureRunningOnConnectivityServiceThread();
10423 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10424 informOffer(nri, noi.offer, mNetworkRanker);
10425 }
10426 }
10427
10428 /**
10429 * Inform a NetworkOffer about any new situation of a request.
10430 *
10431 * This function handles updates to offers. A number of events may happen that require
10432 * updating the registrant for this offer about the situation :
10433 * • The offer itself was updated. This may lead the offer to no longer being able
10434 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10435 * or conversely being strengthened enough to beat the satisfier (and therefore
10436 * start being needed)
10437 * • The network satisfying a request changed (including cases where the request
10438 * starts or stops being satisfied). The new network may be a stronger or weaker
10439 * match than the old one, possibly affecting whether the offer is needed.
10440 * • The network satisfying a request updated their score. This may lead the offer
10441 * to no longer be able to beat it if the current satisfier got better, or
10442 * conversely start being a good choice if the current satisfier got weaker.
10443 *
10444 * @param nri The request
10445 * @param offer The offer. This may be an updated offer.
10446 */
10447 private static void informOffer(@NonNull NetworkRequestInfo nri,
10448 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10449 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10450 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010451
10452 // Multi-layer requests have a currently active request, the one being satisfied.
10453 // Since the system will try to bring up a better network than is currently satisfying
10454 // the request, NetworkProviders need to be told the offers matching the requests *above*
10455 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10456 // not needed, and the offer is needed for the active request iff the offer can beat
10457 // the satisfier.
10458 // For non-multilayer requests, the logic above gracefully degenerates to only the
10459 // last case.
10460 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10461 // providers that the offer is needed for this request, until the active request is found.
10462 // In a second phase, deal with the currently active request. In a third phase, inform
10463 // the providers that offer is unneeded for the remaining requests.
10464
10465 // First phase : inform providers of all requests above the active request.
10466 int i;
10467 for (i = 0; nri.mRequests.size() > i; ++i) {
10468 final NetworkRequest request = nri.mRequests.get(i);
10469 if (activeRequest == request) break; // Found the active request : go to phase 2
10470 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10471 // Since this request is higher-priority than the one currently satisfied, if the
10472 // offer can satisfy it, the provider should try and bring up the network for sure ;
10473 // no need to even ask the ranker – an offer that can satisfy is always better than
10474 // no network. Hence tell the provider so unless it already knew.
10475 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10476 offer.onNetworkNeeded(request);
10477 }
10478 }
10479
10480 // Second phase : deal with the active request (if any)
10481 if (null != activeRequest && activeRequest.isRequest()) {
10482 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010483 // If an offer can satisfy the request, it is considered needed if it is currently
10484 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010485 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010486 && satisfier.factorySerialNumber == offer.providerId
10487 && activeRequest.canBeSatisfiedBy(offer.caps);
10488 final boolean newNeeded = currentlyServing
10489 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010490 if (newNeeded != oldNeeded) {
10491 if (newNeeded) {
10492 offer.onNetworkNeeded(activeRequest);
10493 } else {
10494 // The offer used to be able to beat the satisfier. Now it can't.
10495 offer.onNetworkUnneeded(activeRequest);
10496 }
10497 }
10498 }
10499
10500 // Third phase : inform the providers that the offer isn't needed for any request
10501 // below the active one.
10502 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10503 final NetworkRequest request = nri.mRequests.get(i);
10504 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10505 // Since this request is lower-priority than the one currently satisfied, if the
10506 // offer can satisfy it, the provider should not try and bring up the network.
10507 // Hence tell the provider so unless it already knew.
10508 if (offer.neededFor(request)) {
10509 offer.onNetworkUnneeded(request);
10510 }
10511 }
10512 }
10513
Chalard Jean61c79252019-11-07 23:07:32 +090010514 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10515 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10516 NetworkRequest nr = nai.requestAt(i);
10517 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10518 // legacy type tracker filters out repeat adds
10519 mLegacyTypeTracker.add(nr.legacyType, nai);
10520 }
10521 }
10522
10523 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010524 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010525 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10526 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10527 if (nai.isVPN()) {
10528 mLegacyTypeTracker.add(TYPE_VPN, nai);
10529 }
10530 }
10531
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010532 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010533 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010534 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010535 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010536 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010537 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010538
Chalard Jean254bd162022-08-25 13:04:51 +090010539 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010540 // Don't repeat publish.
10541 if (newInetCondition == mDefaultInetConditionPublished) return;
10542
10543 mDefaultInetConditionPublished = newInetCondition;
10544 sendInetConditionBroadcast(nai.networkInfo);
10545 }
10546
Chalard Jeand61375d2020-01-14 22:46:36 +090010547 @NonNull
10548 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10549 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010550 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010551 final boolean suspended =
10552 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10553 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10554 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10555 // state. This is because the network could have been suspended before connecting,
10556 // or it could be disconnecting while being suspended, and in both these cases
10557 // the state should not be overridden. Note that the only detailed state that
10558 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10559 // worry about multiple different substates of CONNECTED.
10560 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10561 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010562 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10563 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10564 // network agent is created, then goes to suspended, then goes out of suspended without
10565 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010566 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010567 ? NetworkInfo.DetailedState.CONNECTED
10568 : NetworkInfo.DetailedState.CONNECTING,
10569 info.getReason(),
10570 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010571 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010572 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010573 return newInfo;
10574 }
10575
10576 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10577 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10578
Erik Kline99f301b2017-02-15 19:59:17 +090010579 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010580 NetworkInfo oldInfo = null;
10581 synchronized (networkAgent) {
10582 oldInfo = networkAgent.networkInfo;
10583 networkAgent.networkInfo = newInfo;
10584 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010585
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010586 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010587 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10588 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010589 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010590
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010591 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010592 // A network that has just connected has zero requests and is thus a foreground network.
10593 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10594
Luke Huangfdd11f82019-04-09 18:41:49 +080010595 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010596
10597 networkAgent.setCreated();
10598
10599 // If the network is created immediately on register, then apply the LinkProperties now.
10600 // Otherwise, this is done further down when the network goes into connected state.
10601 // Applying the LinkProperties means that the network is ready to carry traffic -
10602 // interfaces and routing rules have been added, DNS servers programmed, etc.
10603 // For VPNs, this must be done before the capabilities are updated, because as soon as
10604 // that happens, UIDs are routed to the network.
10605 if (shouldCreateNetworksImmediately()) {
10606 applyInitialLinkProperties(networkAgent);
10607 }
10608
10609 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10610 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010611 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010612 // Initialize the network's capabilities to their starting values according to the
10613 // underlying networks. This ensures that the capabilities are correct before
10614 // anything happens to the network.
10615 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010616 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010617 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010618 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010619 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010620 }
10621
Chalard Jean254bd162022-08-25 13:04:51 +090010622 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10623 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010624
lucaslin45e639b2019-04-03 17:09:28 +080010625 // NetworkCapabilities need to be set before sending the private DNS config to
10626 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010627 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10628
Erik Kline9a62f012018-03-21 07:18:33 -070010629 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010630 if (!shouldCreateNetworksImmediately()) {
10631 applyInitialLinkProperties(networkAgent);
10632 } else {
10633 // The network was created when the agent registered, and the LinkProperties are
10634 // already up-to-date. However, updateLinkProperties also makes some changes only
10635 // when the network connects. Apply those changes here. On T and below these are
10636 // handled by the applyInitialLinkProperties call just above.
10637 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10638 // If something depends on both LinkProperties and connected state, it should be in
10639 // this method as well.
10640 networkAgent.clatd.update();
10641 updateProxy(networkAgent.linkProperties, null);
10642 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010643
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010644 // If a rate limit has been configured and is applicable to this network (network
10645 // provides internet connectivity), apply it. The tc police filter cannot be attached
10646 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010647 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010648 // Note: in case of a system server crash, the NetworkController constructor in netd
10649 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10650 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10651 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10652 mIngressRateLimit);
10653 }
10654
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010655 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10656 // command must be sent after updating LinkProperties to maximize chances of
10657 // NetworkMonitor seeing the correct LinkProperties when starting.
10658 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010659 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010660 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010661 }
Chalard Jeand4900722022-02-06 12:25:38 +090010662 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10663 params.networkAgentConfig = networkAgent.networkAgentConfig;
10664 params.networkCapabilities = networkAgent.networkCapabilities;
10665 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10666 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010667 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10668 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10669 // call that would cause a Log.wtf to be emitted from the system_server process, and
10670 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10671 // process to check the interface version, just use an SDK check. NetworkStack will
10672 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010673 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010674 networkAgent.networkMonitor().notifyNetworkConnected(params);
10675 } else {
10676 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10677 params.networkCapabilities);
10678 }
Chalard Jean0f141332023-06-05 19:26:17 +090010679 final long evaluationDelay;
10680 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10681 // If the network is anything other than pure wifi, use the default timeout.
10682 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10683 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10684 // If the network is explicitly selected, use the default timeout because it's
10685 // shorter and the user is likely staring at the screen expecting it to validate
10686 // right away.
10687 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10688 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10689 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10690 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10691 } else {
10692 // It's wifi, automatically connected, and bad wifi is preferred : use the
10693 // longer timeout to avoid the device switching to captive portals with bad
10694 // signal or very slow response.
10695 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10696 }
10697 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010698
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010699 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10700 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10701 // capabilities, so it only needs to be done once on initial connect, not every time the
10702 // network's capabilities change. Note that we do this before rematching the network,
10703 // so we could decide to tear it down immediately afterwards. That's fine though - on
10704 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10705 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010706 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010707
junyulai0ac374f2020-12-14 18:41:52 +080010708 // Before first rematching networks, put an inactivity timer without any request, this
10709 // allows {@code updateInactivityState} to update the state accordingly and prevent
10710 // tearing down for any {@code unneeded} evaluation in this period.
10711 // Note that the timer will not be rescheduled since the expiry time is
10712 // fixed after connection regardless of the network satisfying other requests or not.
10713 // But it will be removed as soon as the network satisfies a request for the first time.
10714 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10715 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010716 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010717
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010718 if (mTrackMultiNetworkActivities) {
10719 // Start tracking activity of this network.
10720 // This must be called before rematchAllNetworksAndRequests since the network
10721 // should be tracked when the network becomes the default network.
10722 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
10723 // can be triggered later if this network becomes the default network.
10724 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
10725 }
10726
Paul Jensen05e85ee2014-09-11 11:00:39 -040010727 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010728 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010729
10730 // This has to happen after matching the requests, because callbacks are just requests.
10731 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010732 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010733 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010734 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010735 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010736 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010737 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010738 if (networkAgent.isVPN()) {
10739 // As the active or bound network changes for apps, broadcast the default proxy, as
10740 // apps may need to update their proxy data. This is called after disconnecting from
10741 // VPN to make sure we do not broadcast the old proxy data.
10742 // TODO(b/122649188): send the broadcast only to VPN users.
10743 mProxyTracker.sendProxyBroadcast();
10744 }
Chalard Jean254bd162022-08-25 13:04:51 +090010745 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10746 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010747 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010748 }
10749 }
10750
Chalard Jean28018572020-12-21 18:36:52 +090010751 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010752 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10753 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010754 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010755 }
10756
Erik Kline99f301b2017-02-15 19:59:17 +090010757 // Notify only this one new request of the current state. Transfer all the
10758 // current state by calling NetworkCapabilities and LinkProperties callbacks
10759 // so that callers can be guaranteed to have as close to atomicity in state
10760 // transfer as can be supported by this current API.
10761 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010762 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010763 if (nri.mPendingIntent != null) {
10764 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10765 // Attempt no subsequent state pushes where intents are involved.
10766 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010767 }
Erik Kline99f301b2017-02-15 19:59:17 +090010768
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010769 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010770 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010771 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10772 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10773 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010774 }
10775
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010776 // Notify the requests on this NAI that the network is now lingered.
10777 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010778 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010779 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10780 }
10781
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010782 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10783 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10784 return vpnBlocked
10785 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10786 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10787 }
10788
10789 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10790 if (blockedReasons == BLOCKED_REASON_NONE) {
10791 mUidBlockedReasons.delete(uid);
10792 } else {
10793 mUidBlockedReasons.put(uid, blockedReasons);
10794 }
10795 }
10796
junyulaif2c67e42018-08-07 19:50:45 +080010797 /**
10798 * Notify of the blocked state apps with a registered callback matching a given NAI.
10799 *
10800 * Unlike other callbacks, blocked status is different between each individual uid. So for
10801 * any given nai, all requests need to be considered according to the uid who filed it.
10802 *
10803 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010804 * @param oldMetered True if the previous network capabilities were metered.
10805 * @param newMetered True if the current network capabilities are metered.
10806 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10807 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010808 */
10809 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010810 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10811 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010812
10813 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10814 NetworkRequest nr = nai.requestAt(i);
10815 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010816
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010817 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10818 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10819 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010820 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010821 : oldVpnBlocked;
10822
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010823 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10824 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10825 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010826 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010827 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010828 }
10829 }
10830 }
10831
10832 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010833 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010834 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010835 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010836 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010837 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010838 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010839 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010840 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010841
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010842 final int oldBlockedState = getBlockedState(
10843 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10844 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10845 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010846 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010847 }
junyulaif2c67e42018-08-07 19:50:45 +080010848 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10849 NetworkRequest nr = nai.requestAt(i);
10850 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010851 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010852 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10853 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010854 }
10855 }
10856 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010857 }
10858
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010859 @VisibleForTesting
10860 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010861 // The NetworkInfo we actually send out has no bearing on the real
10862 // state of affairs. For example, if the default connection is mobile,
10863 // and a request for HIPRI has just gone away, we need to pretend that
10864 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10865 // the state to DISCONNECTED, even though the network is of type MOBILE
10866 // and is still connected.
10867 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10868 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010869 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010870 if (state != DetailedState.DISCONNECTED) {
10871 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010872 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010873 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010874 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010875 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10876 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10877 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10878 if (info.isFailover()) {
10879 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10880 nai.networkInfo.setFailover(false);
10881 }
10882 if (info.getReason() != null) {
10883 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10884 }
10885 if (info.getExtraInfo() != null) {
10886 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10887 }
10888 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010889 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010890 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010891 if (newDefaultAgent != null) {
10892 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10893 newDefaultAgent.networkInfo);
10894 } else {
10895 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10896 }
10897 }
10898 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10899 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010900 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010901 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010902 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010903 }
10904 }
10905 }
10906
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010907 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010908 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010909 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010910 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010911 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010912 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10913 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010914 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10915 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010916 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010917 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010918 } else {
10919 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10920 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010921 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010922 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010923
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010924 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10925 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10926 }
10927
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010928 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010929 * Returns the list of all interfaces that could be used by network traffic that does not
10930 * explicitly specify a network. This includes the default network, but also all VPNs that are
10931 * currently connected.
10932 *
10933 * Must be called on the handler thread.
10934 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010935 @NonNull
10936 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010937 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010938 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010939 final Set<Integer> activeNetIds = new ArraySet<>();
10940 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10941 if (nri.isBeingSatisfied()) {
10942 activeNetIds.add(nri.getSatisfier().network().netId);
10943 }
10944 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010945 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010946 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010947 defaultNetworks.add(nai.network);
10948 }
10949 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010950 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010951 }
10952
10953 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010954 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10955 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010956 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010957 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010958 ensureRunningOnConnectivityServiceThread();
10959 String activeIface = null;
10960 LinkProperties activeLinkProperties = getActiveLinkProperties();
10961 if (activeLinkProperties != null) {
10962 activeIface = activeLinkProperties.getInterfaceName();
10963 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010964
junyulai2050bed2021-01-23 09:46:34 +080010965 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010966 try {
junyulaide41fc22021-01-22 22:46:01 +080010967 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010968 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010969 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10970 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010971 } catch (Exception ignored) {
10972 }
10973 }
10974
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010975 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010976 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010977 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010978 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010979 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010980
10981 if (!TextUtils.isEmpty(settingUrl)) {
10982 return settingUrl;
10983 }
10984
10985 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010986 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010987 if (!TextUtils.isEmpty(settingUrl)) {
10988 return settingUrl;
10989 }
10990
10991 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010992 }
10993
10994 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010995 public void startNattKeepalive(Network network, int intervalSeconds,
10996 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010997 enforceKeepalivePermission();
10998 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010999 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000011000 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
11001 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000011002 // false and set the underpinned network to null because there is no way and no
11003 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
11004 // deprecated method.
11005 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011006 }
11007
11008 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011009 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080011010 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000011011 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070011012 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080011013 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011014 mKeepaliveTracker.startNattKeepalive(
11015 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000011016 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
11017 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070011018 } finally {
11019 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11020 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011021 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11022 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011023 }
11024 }
junyulaid05a1922019-01-15 11:32:44 +080011025 }
11026
11027 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011028 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080011029 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070011030 try {
11031 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080011032 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011033 mKeepaliveTracker.startTcpKeepalive(
11034 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
11035 } finally {
11036 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11037 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011038 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11039 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011040 }
11041 }
junyulai0835a1e2019-01-08 20:04:33 +080011042 }
11043
11044 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011045 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011046 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011047 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
11048 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011049 }
11050
11051 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090011052 public int[] getSupportedKeepalives() {
11053 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
11054 // Backwards compatibility with CTS 13
11055 android.Manifest.permission.QUERY_ALL_PACKAGES);
11056
11057 return BinderUtils.withCleanCallingIdentity(() ->
11058 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
11059 }
11060
11061 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070011062 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080011063 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070011064
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011065 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080011066 final long token = Binder.clearCallingIdentity();
11067 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011068 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
11069 UserHandle.getUserHandleForUid(uid))) {
11070 return;
11071 }
11072
Heemin Seogdb8489d2019-06-12 09:21:44 -070011073 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
11074 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011075
11076 // Turn airplane mode off
11077 setAirplaneMode(false);
11078
11079 // restore private DNS settings to default mode (opportunistic)
11080 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
11081 UserHandle.getUserHandleForUid(uid))) {
11082 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
11083 PRIVATE_DNS_MODE_OPPORTUNISTIC);
11084 }
11085
11086 Settings.Global.putString(mContext.getContentResolver(),
11087 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080011088 } finally {
11089 Binder.restoreCallingIdentity(token);
11090 }
Stuart Scottd5463642015-04-02 18:00:02 -070011091 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040011092
Ricky Wai7097cc92018-01-23 04:09:45 +000011093 @Override
11094 public byte[] getNetworkWatchlistConfigHash() {
11095 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
11096 if (nwm == null) {
11097 loge("Unable to get NetworkWatchlistManager");
11098 return null;
11099 }
11100 // Redirect it to network watchlist service to access watchlist file and calculate hash.
11101 return nwm.getWatchlistConfigHash();
11102 }
11103
Hugo Benichibe0c7652016-05-31 16:28:06 +090011104 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090011105 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080011106 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090011107 }
Hugo Benichif4210292017-04-21 15:07:12 +090011108
11109 private static boolean toBool(int encodedBoolean) {
11110 return encodedBoolean != 0; // Only 0 means false.
11111 }
11112
11113 private static int encodeBool(boolean b) {
11114 return b ? 1 : 0;
11115 }
mswest4632928412018-03-12 10:34:34 -070011116
11117 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011118 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
11119 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
11120 @NonNull String[] args) {
11121 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
11122 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070011123 }
11124
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011125 private Boolean parseBooleanArgument(final String arg) {
11126 if ("true".equals(arg)) {
11127 return true;
11128 } else if ("false".equals(arg)) {
11129 return false;
11130 } else {
11131 return null;
11132 }
11133 }
11134
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011135 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070011136 @Override
11137 public int onCommand(String cmd) {
11138 if (cmd == null) {
11139 return handleDefaultCommands(cmd);
11140 }
11141 final PrintWriter pw = getOutPrintWriter();
11142 try {
11143 switch (cmd) {
11144 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011145 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11146 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011147 final String action = getNextArg();
11148 if ("enable".equals(action)) {
11149 setAirplaneMode(true);
11150 return 0;
11151 } else if ("disable".equals(action)) {
11152 setAirplaneMode(false);
11153 return 0;
11154 } else if (action == null) {
11155 final ContentResolver cr = mContext.getContentResolver();
11156 final int enabled = Settings.Global.getInt(cr,
11157 Settings.Global.AIRPLANE_MODE_ON);
11158 pw.println(enabled == 0 ? "disabled" : "enabled");
11159 return 0;
11160 } else {
11161 onHelp();
11162 return -1;
11163 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011164 case "set-chain3-enabled": {
11165 final Boolean enabled = parseBooleanArgument(getNextArg());
11166 if (null == enabled) {
11167 onHelp();
11168 return -1;
11169 }
11170 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11171 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11172 enabled);
11173 return 0;
11174 }
11175 case "get-chain3-enabled": {
11176 final boolean chainEnabled = getFirewallChainEnabled(
11177 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11178 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11179 return 0;
11180 }
11181 case "set-package-networking-enabled": {
11182 final Boolean enabled = parseBooleanArgument(getNextArg());
11183 final String packageName = getNextArg();
11184 if (null == enabled || null == packageName) {
11185 onHelp();
11186 return -1;
11187 }
11188 // Throws NameNotFound if the package doesn't exist.
11189 final int appId = setPackageFirewallRule(
11190 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11191 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11192 final String msg = (enabled ? "Enabled" : "Disabled")
11193 + " networking for " + packageName + ", appId " + appId;
11194 Log.i(TAG, msg);
11195 pw.println(msg);
11196 return 0;
11197 }
11198 case "get-package-networking-enabled": {
11199 final String packageName = getNextArg();
11200 final int rule = getPackageFirewallRule(
11201 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11202 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11203 pw.println(packageName + ":" + "allow");
11204 } else if (FIREWALL_RULE_DENY == rule) {
11205 pw.println(packageName + ":" + "deny");
11206 } else {
11207 throw new IllegalStateException("Unknown rule " + rule + " for package "
11208 + packageName);
11209 }
11210 return 0;
11211 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011212 case "reevaluate":
11213 // Usage : adb shell cmd connectivity reevaluate <netId>
11214 // If netId is omitted, then reevaluate the default network
11215 final String netId = getNextArg();
11216 final NetworkAgentInfo nai;
11217 if (null == netId) {
11218 // Note that the command is running on the wrong thread to call this,
11219 // so this could in principle return stale data. But it can't crash.
11220 nai = getDefaultNetwork();
11221 } else {
11222 // If netId can't be parsed, this throws NumberFormatException, which
11223 // is passed back to adb who prints it.
11224 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11225 }
11226 if (null == nai) {
11227 pw.println("Unknown network (net ID not found or no default network)");
11228 return 0;
11229 }
11230 Log.d(TAG, "Reevaluating network " + nai.network);
11231 reportNetworkConnectivity(nai.network, !nai.isValidated());
11232 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011233 case "bpf-get-cgroup-program-id": {
11234 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11235 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11236 // for more detail.
11237 // If type can't be parsed, this throws NumberFormatException, which
11238 // is passed back to adb who prints it.
11239 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011240 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011241 pw.println(ret);
11242 return 0;
11243 }
mswest4632928412018-03-12 10:34:34 -070011244 default:
11245 return handleDefaultCommands(cmd);
11246 }
11247 } catch (Exception e) {
11248 pw.println(e);
11249 }
11250 return -1;
11251 }
11252
11253 @Override
11254 public void onHelp() {
11255 PrintWriter pw = getOutPrintWriter();
11256 pw.println("Connectivity service commands:");
11257 pw.println(" help");
11258 pw.println(" Print this help text.");
11259 pw.println(" airplane-mode [enable|disable]");
11260 pw.println(" Turn airplane mode on or off.");
11261 pw.println(" airplane-mode");
11262 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011263 pw.println(" set-chain3-enabled [true|false]");
11264 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11265 pw.println(" get-chain3-enabled");
11266 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11267 pw.println(" set-package-networking-enabled [true|false] [package name]");
11268 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11269 + " no effect if the chain is disabled.");
11270 pw.println(" get-package-networking-enabled [package name]");
11271 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011272 }
11273 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011274
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011275 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011276 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11277 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11278 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011279 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011280 }
11281
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011282 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11283 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011284 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11285 final TransportInfo newInfo = nc.getTransportInfo();
11286 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11287 return;
11288 }
11289 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011290 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011291 }
11292 }
11293
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011294 /**
11295 * @param connectionInfo the connection to resolve.
11296 * @return {@code uid} if the connection is found and the app has permission to observe it
11297 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11298 * connection is not found.
11299 */
11300 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011301 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11302 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11303 }
11304
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011305 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011306 connectionInfo.local, connectionInfo.remote);
11307
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011308 if (uid == INVALID_UID) return uid; // Not found.
11309
11310 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11311 // VPN, if any, that applies to the UID that owns the connection.
11312 if (checkNetworkStackPermission()) return uid;
11313
11314 final NetworkAgentInfo vpn = getVpnForUid(uid);
11315 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011316 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011317 return INVALID_UID;
11318 }
11319
11320 return uid;
11321 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011322
Benedict Wong493e04b2018-11-09 14:45:34 -080011323 /**
11324 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11325 *
11326 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11327 */
11328 @Override
11329 public IBinder startOrGetTestNetworkService() {
11330 synchronized (mTNSLock) {
11331 TestNetworkService.enforceTestNetworkPermissions(mContext);
11332
11333 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011334 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011335 }
11336
11337 return mTNS;
11338 }
11339 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011340
Cody Kesting73708bf2019-12-18 10:57:50 -080011341 /**
11342 * Handler used for managing all Connectivity Diagnostics related functions.
11343 *
11344 * @see android.net.ConnectivityDiagnosticsManager
11345 *
11346 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11347 */
11348 @VisibleForTesting
11349 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011350 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11351
Cody Kesting73708bf2019-12-18 10:57:50 -080011352 /**
11353 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11354 * android.net.ConnectivityDiagnosticsManager}.
11355 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11356 * NetworkRequestInfo to be registered
11357 */
11358 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11359
11360 /**
11361 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11362 * android.net.ConnectivityDiagnosticsManager}.
11363 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11364 * arg1 = the uid of the caller
11365 */
11366 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11367
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011368 /**
11369 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011370 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011371 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11372 * NetworkMonitor.
11373 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011374 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011375 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011376
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011377 /**
11378 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11379 * been detected on the network.
11380 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11381 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11382 * arg2 = NetID.
11383 * data = PersistableBundle of extras passed from NetworkMonitor.
11384 */
11385 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11386
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011387 /**
11388 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11389 * the platform. This event will invoke {@link
11390 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11391 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011392 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011393 */
11394 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11395
Cody Kesting73708bf2019-12-18 10:57:50 -080011396 private ConnectivityDiagnosticsHandler(Looper looper) {
11397 super(looper);
11398 }
11399
11400 @Override
11401 public void handleMessage(Message msg) {
11402 switch (msg.what) {
11403 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11404 handleRegisterConnectivityDiagnosticsCallback(
11405 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11406 break;
11407 }
11408 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11409 handleUnregisterConnectivityDiagnosticsCallback(
11410 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11411 break;
11412 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011413 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011414 final ConnectivityReportEvent reportEvent =
11415 (ConnectivityReportEvent) msg.obj;
11416
Aaron Huang959d3642021-01-21 15:47:41 +080011417 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011418 break;
11419 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011420 case EVENT_DATA_STALL_SUSPECTED: {
11421 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011422 final Pair<Long, PersistableBundle> arg =
11423 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011424 if (nai == null) break;
11425
Aaron Huang959d3642021-01-21 15:47:41 +080011426 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011427 break;
11428 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011429 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011430 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011431 break;
11432 }
11433 default: {
11434 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11435 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011436 }
11437 }
11438 }
11439
11440 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11441 @VisibleForTesting
11442 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11443 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11444 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011445 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011446
11447 @VisibleForTesting
11448 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011449 @NonNull IConnectivityDiagnosticsCallback cb,
11450 @NonNull NetworkRequestInfo nri,
11451 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011452 mCb = cb;
11453 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011454 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011455 }
11456
11457 @Override
11458 public void binderDied() {
11459 log("ConnectivityDiagnosticsCallback IBinder died.");
11460 unregisterConnectivityDiagnosticsCallback(mCb);
11461 }
11462 }
11463
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011464 /**
11465 * Class used for sending information from {@link
11466 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11467 */
11468 private static class NetworkTestedResults {
11469 private final int mNetId;
11470 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011471 @Nullable private final String mRedirectUrl;
11472
11473 private NetworkTestedResults(
11474 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11475 mNetId = netId;
11476 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011477 mRedirectUrl = redirectUrl;
11478 }
11479 }
11480
11481 /**
11482 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11483 * ConnectivityDiagnosticsHandler}.
11484 */
11485 private static class ConnectivityReportEvent {
11486 private final long mTimestampMillis;
11487 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011488 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011489
Aaron Huang959d3642021-01-21 15:47:41 +080011490 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11491 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011492 mTimestampMillis = timestampMillis;
11493 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011494 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011495 }
11496 }
11497
Cody Kestingf1120be2020-08-03 18:01:40 -070011498 /**
11499 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11500 * ConnectivityDiagnosticsHandler}.
11501 */
11502 private static class ReportedNetworkConnectivityInfo {
11503 public final boolean hasConnectivity;
11504 public final boolean isNetworkRevalidating;
11505 public final int reporterUid;
11506 @NonNull public final NetworkAgentInfo nai;
11507
11508 private ReportedNetworkConnectivityInfo(
11509 boolean hasConnectivity,
11510 boolean isNetworkRevalidating,
11511 int reporterUid,
11512 @NonNull NetworkAgentInfo nai) {
11513 this.hasConnectivity = hasConnectivity;
11514 this.isNetworkRevalidating = isNetworkRevalidating;
11515 this.reporterUid = reporterUid;
11516 this.nai = nai;
11517 }
11518 }
11519
Cody Kesting73708bf2019-12-18 10:57:50 -080011520 private void handleRegisterConnectivityDiagnosticsCallback(
11521 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11522 ensureRunningOnConnectivityServiceThread();
11523
11524 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011525 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011526 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11527
James Mattis64b8b0f2020-11-24 17:40:49 -080011528 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11529 // confusing for these networks to change when an NRI is satisfied in another layer.
11530 if (nri.isMultilayerRequest()) {
11531 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11532 + "network requests.");
11533 }
11534
Cody Kesting73708bf2019-12-18 10:57:50 -080011535 // This means that the client registered the same callback multiple times. Do
11536 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011537 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011538 if (VDBG) log("Diagnostics callback is already registered");
11539
11540 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11541 // incremented when the NetworkRequestInfo is created as part of
11542 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011543 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011544 return;
11545 }
11546
Cody Kesting31f1ff62020-03-05 10:46:02 -080011547 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011548
11549 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011550 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011551 } catch (RemoteException e) {
11552 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011553 return;
11554 }
11555
11556 // Once registered, provide ConnectivityReports for matching Networks
11557 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11558 synchronized (mNetworkForNetId) {
11559 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11560 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011561 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11562 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011563 matchingNetworks.add(nai);
11564 }
11565 }
11566 }
11567 for (final NetworkAgentInfo nai : matchingNetworks) {
11568 final ConnectivityReport report = nai.getConnectivityReport();
11569 if (report == null) {
11570 continue;
11571 }
11572 if (!checkConnectivityDiagnosticsPermissions(
11573 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11574 continue;
11575 }
11576
11577 try {
11578 cb.onConnectivityReportAvailable(report);
11579 } catch (RemoteException e) {
11580 // Exception while sending the ConnectivityReport. Move on to the next network.
11581 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011582 }
11583 }
11584
11585 private void handleUnregisterConnectivityDiagnosticsCallback(
11586 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11587 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011588 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011589
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011590 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11591 mConnectivityDiagnosticsCallbacks.remove(iCb);
11592 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011593 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11594 return;
11595 }
11596
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011597 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011598
Cody Kesting70fa2b22020-12-02 12:16:56 -080011599 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11600 // (if the Binder died)
11601 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11602 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011603 return;
11604 }
11605
Cody Kesting46cb1672020-03-04 13:35:20 -080011606 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11607 // incremented when the NetworkRequestInfo is created as part of
11608 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011609 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011610
Cody Kesting31f1ff62020-03-05 10:46:02 -080011611 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011612 }
11613
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011614 private void handleNetworkTestedWithExtras(
11615 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11616 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011617 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011618 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011619 final ConnectivityReport report =
11620 new ConnectivityReport(
11621 reportEvent.mNai.network,
11622 reportEvent.mTimestampMillis,
11623 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011624 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011625 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011626 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011627
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011628 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011629 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011630 for (final IConnectivityDiagnosticsCallback cb : results) {
11631 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011632 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011633 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011634 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011635 }
11636 }
11637 }
11638
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011639 private void handleDataStallSuspected(
11640 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11641 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011642 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011643 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011644 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011645 new DataStallReport(
11646 nai.network,
11647 timestampMillis,
11648 detectionMethod,
11649 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011650 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011651 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011652 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011653 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011654 for (final IConnectivityDiagnosticsCallback cb : results) {
11655 try {
11656 cb.onDataStallSuspected(report);
11657 } catch (RemoteException ex) {
11658 loge("Error invoking onDataStallSuspected", ex);
11659 }
11660 }
11661 }
11662
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011663 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011664 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11665 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11666 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11667
11668 // If the Network is being re-validated as a result of this call to
11669 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11670 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011671 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011672 getMatchingPermissionedCallbacks(
11673 nai,
11674 reportedNetworkConnectivityInfo.isNetworkRevalidating
11675 ? Process.INVALID_UID
11676 : reportedNetworkConnectivityInfo.reporterUid);
11677
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011678 for (final IConnectivityDiagnosticsCallback cb : results) {
11679 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011680 cb.onNetworkConnectivityReported(
11681 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011682 } catch (RemoteException ex) {
11683 loge("Error invoking onNetworkConnectivityReported", ex);
11684 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011685
11686 // If the Network isn't re-validating, also provide the cached report. If there is no
11687 // cached report, the Network is still being validated and a report will be sent once
11688 // validation is complete. Note that networks which never undergo validation will still
11689 // have a cached ConnectivityReport with RESULT_SKIPPED.
11690 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11691 try {
11692 cb.onConnectivityReportAvailable(cachedReport);
11693 } catch (RemoteException ex) {
11694 loge("Error invoking onConnectivityReportAvailable", ex);
11695 }
11696 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011697 }
11698 }
11699
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011700 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011701 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11702 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011703 sanitized.setUids(null);
11704 sanitized.setAdministratorUids(new int[0]);
11705 sanitized.setOwnerUid(Process.INVALID_UID);
11706 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011707 }
11708
Cody Kestingf1120be2020-08-03 18:01:40 -070011709 /**
11710 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11711 *
11712 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11713 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011714 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011715 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011716 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011717 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011718 mConnectivityDiagnosticsCallbacks.entrySet()) {
11719 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11720 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011721
James Mattis64b8b0f2020-11-24 17:40:49 -080011722 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011723 if (!nai.satisfies(nri.mRequests.get(0))) {
11724 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011725 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011726
11727 // UID for this callback must either be:
11728 // - INVALID_UID (which sends callbacks to all UIDs), or
11729 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11730 // notified as a result)
11731 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11732 continue;
11733 }
11734
11735 if (!checkConnectivityDiagnosticsPermissions(
11736 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11737 continue;
11738 }
11739
11740 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011741 }
11742 return results;
11743 }
11744
Cody Kesting7474f672021-05-11 14:22:40 -070011745 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11746 @NonNull NetworkAgentInfo nai) {
11747 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11748 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11749 }
11750
Cody Kesting160ef392021-05-05 13:17:22 -070011751 private boolean hasLocationPermission(String packageName, int uid) {
11752 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11753 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11754 // call in a try-catch.
11755 try {
11756 if (!mLocationPermissionChecker.checkLocationPermission(
11757 packageName, null /* featureId */, uid, null /* message */)) {
11758 return false;
11759 }
11760 } catch (SecurityException e) {
11761 return false;
11762 }
11763
11764 return true;
11765 }
11766
11767 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11768 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011769 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011770 && virtual.networkCapabilities.getOwnerUid() == uid
11771 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11772 return true;
11773 }
11774 }
11775
11776 return false;
11777 }
11778
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011779 @VisibleForTesting
11780 boolean checkConnectivityDiagnosticsPermissions(
11781 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11782 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11783 return true;
11784 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011785 if (mAllowSysUiConnectivityReports
Chris Göllnercc962022023-12-26 09:55:32 +000011786 && checkSystemBarServicePermission(callbackPid, callbackUid)) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011787 return true;
11788 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011789
Cody Kesting160ef392021-05-05 13:17:22 -070011790 // Administrator UIDs also contains the Owner UID
11791 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11792 if (!CollectionUtils.contains(administratorUids, callbackUid)
11793 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011794 return false;
11795 }
11796
Cody Kesting7474f672021-05-11 14:22:40 -070011797 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11798 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011799 }
11800
Cody Kestingd199a9d2019-12-17 12:55:28 -080011801 @Override
11802 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011803 @NonNull IConnectivityDiagnosticsCallback callback,
11804 @NonNull NetworkRequest request,
11805 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011806 Objects.requireNonNull(callback, "callback must not be null");
11807 Objects.requireNonNull(request, "request must not be null");
11808 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11809
Cody Kesting73708bf2019-12-18 10:57:50 -080011810 if (request.legacyType != TYPE_NONE) {
11811 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11812 + " Please use NetworkCapabilities instead.");
11813 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011814 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011815 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011816
11817 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11818 // and administrator uids to be safe.
11819 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011820 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011821
11822 final NetworkRequest requestWithId =
11823 new NetworkRequest(
11824 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11825
11826 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11827 //
11828 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11829 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11830 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011831 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011832 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011833 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011834
11835 mConnectivityDiagnosticsHandler.sendMessage(
11836 mConnectivityDiagnosticsHandler.obtainMessage(
11837 ConnectivityDiagnosticsHandler
11838 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11839 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011840 }
11841
11842 @Override
11843 public void unregisterConnectivityDiagnosticsCallback(
11844 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011845 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011846 mConnectivityDiagnosticsHandler.sendMessage(
11847 mConnectivityDiagnosticsHandler.obtainMessage(
11848 ConnectivityDiagnosticsHandler
11849 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011850 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011851 0,
11852 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011853 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011854
Yan Yanfe96dde2022-12-05 23:00:01 +000011855 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11856 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11857 if (underlyingNetworks == null) return false;
11858
11859 for (Network network : underlyingNetworks) {
11860 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11861 return true;
11862 }
11863 }
11864 return false;
11865 }
11866
Cody Kestingf53a0752020-04-15 12:33:28 -070011867 @Override
11868 public void simulateDataStall(int detectionMethod, long timestampMillis,
11869 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011870 Objects.requireNonNull(network, "network must not be null");
11871 Objects.requireNonNull(extras, "extras must not be null");
11872
paulhu3ffffe72021-09-16 10:15:22 +080011873 enforceAnyPermissionOf(mContext,
11874 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011875 android.Manifest.permission.NETWORK_STACK);
11876 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011877 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11878 throw new SecurityException(
11879 "Data Stall simulation is only possible for test networks or networks built on"
11880 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011881 }
11882
11883 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011884 if (nai == null
11885 || (nai.creatorUid != mDeps.getCallingUid()
11886 && nai.creatorUid != Process.SYSTEM_UID)) {
11887 throw new SecurityException(
11888 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011889 }
11890
Cody Kesting652e3ec2020-05-21 12:08:21 -070011891 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11892 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11893 // Data Stall information as a DataStallReportParcelable and passing to
11894 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11895 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011896 final DataStallReportParcelable p = new DataStallReportParcelable();
11897 p.timestampMillis = timestampMillis;
11898 p.detectionMethod = detectionMethod;
11899
11900 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11901 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11902 }
11903 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11904 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11905 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11906 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11907 }
11908
Serik Beketayevec8ad212020-12-07 22:43:07 -080011909 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011910 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011911
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011912 /**
11913 * Class to hold the information for network activity change event from idle timers
11914 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11915 */
11916 private static final class NetworkActivityParams {
11917 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011918 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
11919 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011920 public final int label;
11921 public final long timestampNs;
11922 // Uid represents the uid that was responsible for waking the radio.
11923 // -1 for no uid and uid is -1 if isActive is false.
11924 public final int uid;
11925
11926 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11927 this.isActive = isActive;
11928 this.label = label;
11929 this.timestampNs = timestampNs;
11930 this.uid = uid;
11931 }
11932 }
11933
lucaslin66f44212021-02-23 01:12:55 +080011934 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11935 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011936 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011937 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011938 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11939 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011940 }
lucaslin37a16d92021-01-21 19:48:09 +080011941
11942 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011943 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011944 mHandler.post(() -> {
11945 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011946 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011947 }
11948 });
lucaslin37a16d92021-01-21 19:48:09 +080011949 }
11950
11951 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011952 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011953 mHandler.post(() -> {
11954 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011955 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011956 }
11957 });
lucaslin66f44212021-02-23 01:12:55 +080011958 }
11959 }
11960
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011961 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080011962 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11963
11964 /**
11965 * Class used for updating network activity tracking with netd and notify network activity
11966 * changes.
11967 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011968 @VisibleForTesting
11969 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011970 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011971 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011972 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011973 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011974 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11975 new RemoteCallbackList<>();
11976 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011977 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011978 // If there is no default network, default network is considered active to keep the existing
11979 // behavior. Initial value is used until first connect to the default network.
11980 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011981 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011982 // Key is netId. Value is configured idle timer information.
11983 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011984 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011985 // Store netIds of Wi-Fi networks whose idletimers report that they are active
11986 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
11987 // Store netIds of cellular networks whose idletimers report that they are active
11988 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011989
Chalard Jean46bfbf02022-02-02 00:56:25 +090011990 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011991 public final int timeout;
11992 public final int transportType;
11993
11994 IdleTimerParams(int timeout, int transport) {
11995 this.timeout = timeout;
11996 this.transportType = transport;
11997 }
11998 }
11999
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012000 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012001 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012002 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080012003 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012004 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012005 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012006 }
12007
12008 private void ensureRunningOnConnectivityServiceThread() {
12009 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
12010 throw new IllegalStateException("Not running on ConnectivityService thread: "
12011 + Thread.currentThread().getName());
12012 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012013 }
12014
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012015 /**
12016 * Update network activity and call BatteryStats to update radio power state if the
12017 * mobile or Wi-Fi activity is changed.
12018 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
12019 * mobile network is active since BatteryStatsService only maintains a single power state
12020 * for the mobile network.
12021 * The Wi-Fi network is also the same.
12022 *
12023 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
12024 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
12025 * transports.
12026 */
12027 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
12028 final boolean isActive, final int uid) {
12029 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
12030 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
12031 + transportType);
12032 return;
12033 }
12034 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
12035 ? mActiveWifiNetworks : mActiveCellularNetworks;
12036
12037 final boolean wasEmpty = activeNetworks.isEmpty();
12038 if (isActive) {
12039 activeNetworks.add(netId);
12040 } else {
12041 activeNetworks.remove(netId);
12042 }
12043
12044 if (wasEmpty != activeNetworks.isEmpty()) {
12045 updateRadioPowerState(isActive, transportType, uid);
12046 }
12047 }
12048
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012049 private void handleDefaultNetworkActivity(final int transportType,
12050 final boolean isActive, final long timestampNs) {
12051 mIsDefaultNetworkActive = isActive;
12052 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
12053 isActive, timestampNs);
12054 if (isActive) {
12055 reportNetworkActive();
12056 }
12057 }
12058
12059 private void handleReportNetworkActivityWithNetIdLabel(
12060 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012061 final int netId = activityParams.label;
12062 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012063 if (idleTimerParams == null) {
12064 // This network activity change is not tracked anymore
12065 // This can happen if netd callback post activity change event message but idle
12066 // timer is removed before processing this message.
12067 return;
12068 }
12069 // TODO: if a network changes transports, storing the transport type in the
12070 // IdleTimerParams is not correct. Consider getting it from the network's
12071 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012072 final int transportType = idleTimerParams.transportType;
12073 maybeUpdateRadioPowerState(netId, transportType,
12074 activityParams.isActive, activityParams.uid);
12075
12076 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
12077 // This activity change is not for the default network.
12078 return;
12079 }
12080
12081 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012082 activityParams.timestampNs);
12083 }
12084
12085 private void handleReportNetworkActivityWithTransportTypeLabel(
12086 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012087 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012088 // This activity change is not for the current default network.
12089 // This can happen if netd callback post activity change event message but
12090 // the default network is lost before processing this message.
12091 return;
12092 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012093 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
12094 activityParams.timestampNs);
12095 }
12096
12097 /**
12098 * Handle network activity change
12099 */
12100 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
12101 ensureRunningOnConnectivityServiceThread();
12102 if (mTrackMultiNetworkActivities) {
12103 handleReportNetworkActivityWithNetIdLabel(activityParams);
12104 } else {
12105 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080012106 }
12107 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012108
lucaslin1193a5d2021-01-21 02:04:15 +080012109 private void reportNetworkActive() {
12110 final int length = mNetworkActivityListeners.beginBroadcast();
12111 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
12112 try {
12113 for (int i = 0; i < length; i++) {
12114 try {
12115 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
12116 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012117 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080012118 }
12119 }
12120 } finally {
12121 mNetworkActivityListeners.finishBroadcast();
12122 }
12123 }
12124
lucaslin1a8b4c62021-01-21 02:02:55 +080012125 // This is deprecated and only to support legacy use cases.
12126 private int transportTypeToLegacyType(int type) {
12127 switch (type) {
12128 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012129 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080012130 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012131 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080012132 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012133 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080012134 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012135 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080012136 default:
12137 loge("Unexpected transport in transportTypeToLegacyType: " + type);
12138 }
12139 return ConnectivityManager.TYPE_NONE;
12140 }
12141
12142 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12143 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12144 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12145 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12146 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12147 final long ident = Binder.clearCallingIdentity();
12148 try {
12149 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12150 RECEIVE_DATA_ACTIVITY_CHANGE,
12151 null /* resultReceiver */,
12152 null /* scheduler */,
12153 0 /* initialCode */,
12154 null /* initialData */,
12155 null /* initialExtra */);
12156 } finally {
12157 Binder.restoreCallingIdentity(ident);
12158 }
12159 }
12160
12161 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012162 * Get idle timer label
12163 */
12164 @VisibleForTesting
12165 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12166 final int netId, final int transportType) {
12167 return trackMultiNetworkActivities ? netId : transportType;
12168 }
12169
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012170 private boolean maybeCreateIdleTimer(
12171 String iface, int netId, int timeout, int transportType) {
12172 if (timeout <= 0 || iface == null) return false;
12173 try {
12174 final String label = Integer.toString(getIdleTimerLabel(
12175 mTrackMultiNetworkActivities, netId, transportType));
12176 mNetd.idletimerAddInterface(iface, timeout, label);
12177 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12178 return true;
12179 } catch (Exception e) {
12180 loge("Exception in createIdleTimer", e);
12181 return false;
12182 }
12183 }
12184
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012185 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012186 * Setup data activity tracking for the given network.
12187 *
12188 * Every {@code setupDataActivityTracking} should be paired with a
12189 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012190 *
12191 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012192 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012193 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012194 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012195 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012196 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012197
12198 final int timeout;
12199 final int type;
12200
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012201 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12202 // Do not track VPN network.
12203 return false;
12204 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012205 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12206 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012207 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012208 10);
12209 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12210 } else if (networkAgent.networkCapabilities.hasTransport(
12211 NetworkCapabilities.TRANSPORT_WIFI)) {
12212 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012213 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012214 15);
12215 type = NetworkCapabilities.TRANSPORT_WIFI;
12216 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012217 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012218 }
12219
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012220 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12221 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12222 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12223 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12224 // state only about a network that has an idletimer.
12225 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012226 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012227 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012228 }
12229
12230 /**
12231 * Remove data activity tracking when network disconnects.
12232 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012233 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12234 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012235 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012236 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012237 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12238
lucaslinb961efc2021-01-21 02:03:17 +080012239 if (iface == null) return;
12240
12241 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012242 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12243 // Do not track VPN network.
12244 return;
12245 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012246 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12247 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12248 type = NetworkCapabilities.TRANSPORT_WIFI;
12249 } else {
12250 return; // do not track any other networks
12251 }
12252
12253 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012254 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012255 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012256 if (params == null) {
12257 // IdleTimer is not added if the configured timeout is 0 or negative value
12258 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012259 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012260 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012261 final String label = Integer.toString(getIdleTimerLabel(
12262 mTrackMultiNetworkActivities, netId, params.transportType));
12263 // The call fails silently if no idle timer setup for this interface
12264 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012265 } catch (Exception e) {
12266 // You shall not crash!
12267 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012268 }
12269 }
12270
Motomu Utsumi6225d572023-05-29 15:08:57 +090012271 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12272 boolean hasIdleTimer) {
12273 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012274 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012275 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012276 // If only the default network is tracked, callbacks are called only when the
12277 // network has the idle timer.
12278 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012279 reportNetworkActive();
12280 }
12281 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012282 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012283 // If there is no default network, default network is considered active to keep the
12284 // existing behavior.
12285 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090012286 }
12287 }
12288
lucaslin1a8b4c62021-01-21 02:02:55 +080012289 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012290 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012291 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012292 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012293 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012294 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012295 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12296 // first connected and remove when the network is disconnected.
12297 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12298 // becomes the default network and remove when the network becomes no longer the default
12299 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012300 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012301 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012302 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012303 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012304 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012305 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012306 removeDataActivityTracking(oldNetwork);
12307 }
12308 }
lucaslinb961efc2021-01-21 02:03:17 +080012309
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012310 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012311 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12312 switch (transportType) {
12313 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012314 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012315 break;
12316 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012317 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012318 break;
12319 default:
12320 logw("Untracked transport type:" + transportType);
12321 }
12322 }
lucaslin1193a5d2021-01-21 02:04:15 +080012323
12324 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012325 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012326 }
12327
12328 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12329 mNetworkActivityListeners.register(l);
12330 }
12331
12332 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12333 mNetworkActivityListeners.unregister(l);
12334 }
lucaslin012f7a12021-01-21 02:04:35 +080012335
12336 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012337 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012338 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012339 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012340 pw.println("Idle timers:");
12341 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012342 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12343 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12344 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012345 pw.print(" timeout="); pw.print(params.timeout);
12346 pw.print(" type="); pw.println(params.transportType);
12347 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012348 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12349 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012350 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012351 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12352 // be accessed from handler thread, except dump(). As dump() is never called in
12353 // normal usage, it would be needlessly expensive to lock the collection only for
12354 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012355 // So catching the exception and logging.
12356 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012357 }
12358 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012359 }
James Mattis47db0582021-01-01 14:13:35 -080012360
Daniel Brightf9e945b2020-06-15 16:10:01 -070012361 /**
12362 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12363 *
12364 * @param socketInfo the socket information
12365 * @param callback the callback to register
12366 */
12367 @Override
12368 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12369 @NonNull final IQosCallback callback) {
12370 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12371 if (nai == null || nai.networkCapabilities == null) {
12372 try {
12373 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12374 } catch (final RemoteException ex) {
12375 loge("registerQosCallbackInternal: RemoteException", ex);
12376 }
12377 return;
12378 }
12379 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12380 }
12381
12382 /**
12383 * Register a {@link IQosCallback} with base {@link QosFilter}.
12384 *
12385 * @param filter the filter to register
12386 * @param callback the callback to register
12387 * @param nai the agent information related to the filter's network
12388 */
12389 @VisibleForTesting
12390 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12391 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012392 Objects.requireNonNull(filter, "filter must be non-null");
12393 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012394
12395 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012396 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12397 // on this network is unregistered when the app loses permission or b) no QoS
12398 // callbacks are sent for restricted networks unless the app currently has permission
12399 // to access restricted networks.
12400 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012401 }
12402 mQosCallbackTracker.registerCallback(callback, filter, nai);
12403 }
12404
12405 /**
12406 * Unregisters the given callback.
12407 *
12408 * @param callback the callback to unregister
12409 */
12410 @Override
12411 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012412 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012413 mQosCallbackTracker.unregisterCallback(callback);
12414 }
James Mattis47db0582021-01-01 14:13:35 -080012415
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012416 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12417 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12418 // Enterprise device can be fully managed like device owner and such use case
12419 // also should be supported. Calling app check for work profile and fully managed device
12420 // is already done in DevicePolicyManager.
12421 // This check is an extra caution to be sure device is fully managed or not.
12422 final UserManager um = mContext.getSystemService(UserManager.class);
12423 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12424 if (um.isManagedProfile(profile.getIdentifier())) {
12425 return true;
12426 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012427 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012428 return false;
12429 }
12430
James Mattis45d81842021-01-10 14:24:24 -080012431 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012432 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012433 *
12434 * See the documentation for the individual preferences for a description of the supported
12435 * behaviors.
12436 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012437 * @param profile If the device owner is set, any profile is allowed.
12438 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012439 * @param preferences the list of profile network preferences for the
12440 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012441 * @param listener an optional listener to listen for completion of the operation.
12442 */
12443 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012444 public void setProfileNetworkPreferences(
12445 @NonNull final UserHandle profile,
12446 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012447 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012448 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012449 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012450
12451 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012452 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12453 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12454 .build();
12455 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012456 }
12457
paulhu3ffffe72021-09-16 10:15:22 +080012458 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012459 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012460 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012461 }
12462 if (profile.getIdentifier() < 0) {
12463 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12464 + "UserHandle.CURRENT not supported)");
12465 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012466 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12467 throw new IllegalArgumentException("Profile must be a managed profile "
12468 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012469 }
paulhuaa0743d2021-05-26 21:56:03 +080012470
Chalard Jean0606fc82022-12-14 20:34:43 +090012471 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012472 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012473 for (final ProfileNetworkPreference preference : preferences) {
12474 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012475 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012476 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012477 switch (preference.getPreference()) {
12478 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12479 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012480 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012481 if (preference.getPreferenceEnterpriseId() != 0) {
12482 throw new IllegalArgumentException(
12483 "Invalid enterprise identifier in setProfileNetworkPreferences");
12484 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012485 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012486 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12487 blockingNonEnterprise = true;
12488 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012489 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12490 allowFallback = false;
12491 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012492 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012493 // This code is needed even though there is a check later on,
12494 // because isRangeAlreadyInPreferenceList assumes that every preference
12495 // has a UID list.
12496 if (hasDefaultPreference) {
12497 throw new IllegalArgumentException(
12498 "Default profile preference should not be set along with other "
12499 + "preference");
12500 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012501 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12502 throw new IllegalArgumentException(
12503 "Invalid enterprise identifier in setProfileNetworkPreferences");
12504 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012505 final Set<UidRange> uidRangeSet =
12506 getUidListToBeAppliedForNetworkPreference(profile, preference);
12507 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12508 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12509 } else {
12510 throw new IllegalArgumentException(
12511 "Overlapping uid range in setProfileNetworkPreferences");
12512 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012513 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012514 nc.addEnterpriseId(
12515 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012516 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12517 break;
12518 default:
12519 throw new IllegalArgumentException(
12520 "Invalid preference in setProfileNetworkPreferences");
12521 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012522 preferenceList.add(new ProfileNetworkPreferenceInfo(
12523 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012524 if (hasDefaultPreference && preferenceList.size() > 1) {
12525 throw new IllegalArgumentException(
12526 "Default profile preference should not be set along with other preference");
12527 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012528 }
12529 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012530 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012531 }
12532
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012533 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12534 @NonNull final UserHandle profile,
12535 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12536 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012537 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12538 profileNetworkPreference.getIncludedUids());
12539
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012540 if (uidRangeSet.size() > 0) {
12541 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12542 throw new IllegalArgumentException(
12543 "Allow uid range is outside the uid range of profile.");
12544 }
12545 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012546 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012547 profileNetworkPreference.getExcludedUids());
12548 if (disallowUidRangeSet.size() > 0) {
12549 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12550 throw new IllegalArgumentException(
12551 "disallow uid range is outside the uid range of profile.");
12552 }
12553 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12554 disallowUidRangeSet);
12555 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012556 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012557 uidRangeSet.add(profileUids);
12558 }
12559 }
12560 return uidRangeSet;
12561 }
12562
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012563 private boolean isEnterpriseIdentifierValid(
12564 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012565 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012566 return true;
12567 }
12568 return false;
12569 }
12570
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012571 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012572 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012573 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012574 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012575 // The NRI for a user should contain the request for capabilities.
12576 // If fallback to default network is needed then NRI should include
12577 // the request for the default network. Create an image of it to
12578 // have the correct UIDs in it (also a request can only be part of one NRI, because
12579 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012580 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12581 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012582 if (pref.allowFallback) {
12583 nrs.add(createDefaultInternetRequestForTransport(
12584 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12585 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012586 if (VDBG) {
12587 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12588 pref.capabilities.getUids()));
12589 }
12590
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012591 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012592 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012593 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012594 result.add(nri);
12595 }
12596 return result;
12597 }
12598
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012599 /**
12600 * Compare if the given UID range sets have the same UIDs.
12601 *
12602 */
12603 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012604 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012605 @NonNull Set<UidRange> uidRangeSet) {
12606 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12607 return false;
12608 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012609 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012610 if (UidRangeUtils.doesRangeSetOverlap(
12611 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12612 return true;
12613 }
12614 }
12615 return false;
12616 }
12617
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012618 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012619 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012620 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012621 /*
12622 * handleSetProfileNetworkPreference is always called for single user.
12623 * preferenceList only contains preferences for different uids within the same user
12624 * (enforced by getUidListToBeAppliedForNetworkPreference).
12625 * Clear all the existing preferences for the user before applying new preferences.
12626 *
12627 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012628 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12629 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012630 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12631 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012632
paulhu74128522021-09-28 02:29:03 +000012633 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12634 addPerAppDefaultNetworkRequests(
12635 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012636 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012637
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012638 // Finally, rematch.
12639 rematchAllNetworksAndRequests();
12640
12641 if (null != listener) {
12642 try {
12643 listener.onComplete();
12644 } catch (RemoteException e) {
12645 loge("Listener for setProfileNetworkPreference has died");
12646 }
12647 }
12648 }
12649
paulhu51f77dc2021-06-07 02:34:20 +000012650 @VisibleForTesting
12651 @NonNull
12652 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12653 @NonNull final Set<Integer> uids) {
12654 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12655 if (uids.size() == 0) {
12656 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12657 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12658 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12659 return nris;
12660 }
12661
12662 final List<NetworkRequest> requests = new ArrayList<>();
12663 // The NRI should be comprised of two layers:
12664 // - The request for the mobile network preferred.
12665 // - The request for the default network, for fallback.
12666 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012667 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012668 requests.add(createDefaultInternetRequestForTransport(
12669 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12670 final Set<UidRange> ranges = new ArraySet<>();
12671 for (final int uid : uids) {
12672 ranges.add(new UidRange(uid, uid));
12673 }
12674 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012675 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012676 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012677 return nris;
12678 }
12679
12680 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012681 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012682 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12683 addPerAppDefaultNetworkRequests(
12684 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012685 // Finally, rematch.
12686 rematchAllNetworksAndRequests();
12687 }
12688
Patrick Rohr2857ac42022-01-21 14:58:16 +010012689 private void handleIngressRateLimitChanged() {
12690 final long oldIngressRateLimit = mIngressRateLimit;
12691 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12692 mContext);
12693 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12694 if (canNetworkBeRateLimited(networkAgent)) {
12695 // If rate limit has previously been enabled, remove the old limit first.
12696 if (oldIngressRateLimit >= 0) {
12697 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12698 }
12699 if (mIngressRateLimit >= 0) {
12700 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12701 mIngressRateLimit);
12702 }
12703 }
12704 }
12705 }
12706
12707 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012708 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012709 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012710
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012711 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12712 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12713 // internet connectivity can be rate limited.
12714 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12715 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012716 return false;
12717 }
12718
12719 final String iface = networkAgent.linkProperties.getInterfaceName();
12720 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012721 // This may happen in tests, but if there is no interface then there is nothing that
12722 // can be rate limited.
12723 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012724 return false;
12725 }
12726 return true;
12727 }
12728
James Mattis45d81842021-01-10 14:24:24 -080012729 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012730 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12731 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012732 }
12733
12734 /**
12735 * Used by automotive devices to set the network preferences used to direct traffic at an
12736 * application level as per the given OemNetworkPreferences. An example use-case would be an
12737 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12738 * vehicle via a particular network.
12739 *
12740 * Calling this will overwrite the existing preference.
12741 *
James Mattisda32cfe2021-01-26 16:23:52 -080012742 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012743 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012744 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012745 */
James Mattis47db0582021-01-01 14:13:35 -080012746 @Override
James Mattis45d81842021-01-10 14:24:24 -080012747 public void setOemNetworkPreference(
12748 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012749 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012750
James Mattisfa270db2021-05-31 17:11:10 -070012751 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12752 // Only bypass the permission/device checks if this is a valid test request.
12753 if (isValidTestOemNetworkPreference(preference)) {
12754 enforceManageTestNetworksPermission();
12755 } else {
12756 enforceAutomotiveDevice();
12757 enforceOemNetworkPreferencesPermission();
12758 validateOemNetworkPreferences(preference);
12759 }
James Mattis45d81842021-01-10 14:24:24 -080012760
James Mattis45d81842021-01-10 14:24:24 -080012761 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12762 new Pair<>(preference, listener)));
12763 }
12764
James Mattisfa270db2021-05-31 17:11:10 -070012765 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012766 * Sets the specified UIDs to get/receive the VPN as the only default network.
12767 *
12768 * Calling this will overwrite the existing network preference for this session, and the
12769 * specified UIDs won't get any default network when no VPN is connected.
12770 *
12771 * @param session The VPN session which manages the passed UIDs.
12772 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12773 * setting for this session if the array is empty. Null is not allowed, the
12774 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12775 * @hide
12776 */
12777 @Override
12778 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12779 Objects.requireNonNull(ranges);
12780 enforceNetworkStackOrSettingsPermission();
12781 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12782 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12783 throw new IllegalArgumentException(
12784 "setVpnNetworkPreference: Passed UID ranges overlap");
12785 }
12786
12787 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12788 new VpnNetworkPreferenceInfo(session,
12789 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12790 }
12791
12792 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12793 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12794
12795 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12796 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12797
12798 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12799 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12800 // Finally, rematch.
12801 rematchAllNetworksAndRequests();
12802 }
12803
12804 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12805 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12806 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12807 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12808 final List<NetworkRequest> requests = new ArrayList<>();
12809 // Request VPN only, so other networks won't be the fallback options when VPN is not
12810 // connected temporarily.
12811 requests.add(createVpnRequest());
12812 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12813 setNetworkRequestUids(requests, uidRanges);
12814 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12815 }
12816 return nris;
12817 }
12818
12819 /**
James Mattisfa270db2021-05-31 17:11:10 -070012820 * Check the validity of an OEM network preference to be used for testing purposes.
12821 * @param preference the preference to validate
12822 * @return true if this is a valid OEM network preference test request.
12823 */
12824 private boolean isValidTestOemNetworkPreference(
12825 @NonNull final OemNetworkPreferences preference) {
12826 // Allow for clearing of an existing OemNetworkPreference used for testing.
12827 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12828 // changes after this check is complete. This is an unlikely scenario as calling of this API
12829 // is controlled by the OEM therefore the added complexity is not worth adding given those
12830 // circumstances. That said, it is an edge case to be aware of hence this comment.
12831 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12832 && isTestOemNetworkPreference(mOemNetworkPreferences);
12833 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12834 }
12835
12836 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12837 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12838 return prefMap.size() == 1
12839 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12840 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12841 }
12842
James Mattis45d81842021-01-10 14:24:24 -080012843 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12844 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12845 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012846 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12847 throw new IllegalArgumentException(
12848 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12849 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012850 }
12851 }
12852 }
12853
12854 private void handleSetOemNetworkPreference(
12855 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012856 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012857 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12858 if (DBG) {
12859 log("set OEM network preferences :" + preference.toString());
12860 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012861
James Mattiscb1e0362021-04-06 17:07:42 -070012862 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012863 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12864 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12865 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012866 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012867
12868 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012869 try {
12870 listener.onComplete();
12871 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012872 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012873 }
James Mattis45d81842021-01-10 14:24:24 -080012874 }
12875 }
12876
paulhu74128522021-09-28 02:29:03 +000012877 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012878 // Skip the requests which are set by other network preference. Because the uid range rules
12879 // should stay in netd.
12880 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012881 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012882 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012883 }
12884
James Mattis3ce3d3c2021-02-09 18:18:28 -080012885 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12886 ensureRunningOnConnectivityServiceThread();
12887 mDefaultNetworkRequests.addAll(nris);
12888 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12889 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012890 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012891 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12892 nrisToRegister.addAll(
12893 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12894 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012895 }
12896
12897 /**
12898 * All current requests that are tracking the default network need to be assessed as to whether
12899 * or not the current set of per-application default requests will be changing their default
12900 * network. If so, those requests will need to be updated so that they will send callbacks for
12901 * default network changes at the appropriate time. Additionally, those requests tracking the
12902 * default that were previously updated by this flow will need to be reassessed.
12903 * @return the nris which will need to be updated.
12904 */
12905 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12906 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12907 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12908 // same nri in the map's values for each of its NetworkRequest objects.
12909 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012910 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012911 // Include this nri if it is currently being tracked.
12912 if (isPerAppTrackedNri(nri)) {
12913 defaultCallbackRequests.add(nri);
12914 continue;
12915 }
12916 // We only track callbacks for requests tracking the default.
12917 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12918 continue;
12919 }
12920 // Include this nri if it will be tracked by the new per-app default requests.
12921 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012922 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012923 if (isNriGoingToBeTracked) {
12924 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012925 }
12926 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012927 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012928 }
12929
James Mattis3ce3d3c2021-02-09 18:18:28 -080012930 /**
12931 * Create nris for those network requests that are currently tracking the default network that
12932 * are being controlled by a per-application default.
12933 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12934 * foundation when creating the nri. Important items include the calling uid's original
12935 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12936 * requests are assumed to have already been validated as needing to be updated.
12937 * @return the Set of nris to use when registering network requests.
12938 */
12939 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12940 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12941 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12942 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12943 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012944 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012945
Chalard Jean9473c982021-07-29 20:03:04 +090012946 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012947 if (trackingNri == mDefaultRequest) {
12948 callbackRequestsToRegister.add(new NetworkRequestInfo(
12949 callbackRequest,
12950 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12951 continue;
12952 }
12953
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012954 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012955 callbackRequestsToRegister.add(new NetworkRequestInfo(
12956 callbackRequest,
12957 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012958 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012959 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012960 }
12961 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012962 }
12963
Chalard Jean17215832021-03-01 14:06:28 +090012964 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12965 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012966 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012967 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012968 }
12969 }
12970
James Mattis45d81842021-01-10 14:24:24 -080012971 /**
12972 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12973 */
12974 @VisibleForTesting
12975 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012976 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012977 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012978 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012979 final SparseArray<Set<Integer>> uids =
12980 createUidsFromOemNetworkPreferences(preference);
12981 for (int i = 0; i < uids.size(); i++) {
12982 final int key = uids.keyAt(i);
12983 final Set<Integer> value = uids.valueAt(i);
12984 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12985 // No need to add an nri without any requests.
12986 if (0 == nri.mRequests.size()) {
12987 continue;
12988 }
12989 nris.add(nri);
12990 }
12991
12992 return nris;
12993 }
12994
12995 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12996 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012997 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012998 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012999 final List<UserHandle> users =
13000 mContext.getSystemService(UserManager.class).getUserHandles(true);
13001 if (null == users || users.size() == 0) {
13002 if (VDBG || DDBG) {
13003 log("No users currently available for setting the OEM network preference.");
13004 }
James Mattisb6b6a432021-06-01 22:30:36 -070013005 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080013006 }
James Mattis45d81842021-01-10 14:24:24 -080013007 for (final Map.Entry<String, Integer> entry :
13008 preference.getNetworkPreferences().entrySet()) {
13009 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070013010 // Add the rules for all users as this policy is device wide.
13011 for (final UserHandle user : users) {
13012 try {
13013 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
13014 if (!prefToUids.contains(pref)) {
13015 prefToUids.put(pref, new ArraySet<>());
13016 }
13017 prefToUids.get(pref).add(uid);
13018 } catch (PackageManager.NameNotFoundException e) {
13019 // Although this may seem like an error scenario, it is ok that uninstalled
13020 // packages are sent on a network preference as the system will watch for
13021 // package installations associated with this network preference and update
13022 // accordingly. This is done to minimize race conditions on app install.
13023 continue;
James Mattis45d81842021-01-10 14:24:24 -080013024 }
James Mattis45d81842021-01-10 14:24:24 -080013025 }
13026 }
James Mattisb6b6a432021-06-01 22:30:36 -070013027 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080013028 }
13029
13030 private NetworkRequestInfo createNriFromOemNetworkPreferences(
13031 @OemNetworkPreferences.OemNetworkPreference final int preference,
13032 @NonNull final Set<Integer> uids) {
13033 final List<NetworkRequest> requests = new ArrayList<>();
13034 // Requests will ultimately be evaluated by order of insertion therefore it matters.
13035 switch (preference) {
13036 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
13037 requests.add(createUnmeteredNetworkRequest());
13038 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070013039 requests.add(createDefaultInternetRequestForTransport(
13040 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080013041 break;
13042 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
13043 requests.add(createUnmeteredNetworkRequest());
13044 requests.add(createOemPaidNetworkRequest());
13045 break;
13046 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
13047 requests.add(createOemPaidNetworkRequest());
13048 break;
13049 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
13050 requests.add(createOemPrivateNetworkRequest());
13051 break;
James Mattisfa270db2021-05-31 17:11:10 -070013052 case OEM_NETWORK_PREFERENCE_TEST:
13053 requests.add(createUnmeteredNetworkRequest());
13054 requests.add(createTestNetworkRequest());
13055 requests.add(createDefaultRequest());
13056 break;
13057 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
13058 requests.add(createTestNetworkRequest());
13059 break;
James Mattis45d81842021-01-10 14:24:24 -080013060 default:
13061 // This should never happen.
13062 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
13063 + " called with invalid preference of " + preference);
13064 }
13065
James Mattisfa270db2021-05-31 17:11:10 -070013066 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090013067 for (final int uid : uids) {
13068 ranges.add(new UidRange(uid, uid));
13069 }
13070 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080013071 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080013072 }
13073
13074 private NetworkRequest createUnmeteredNetworkRequest() {
13075 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13076 .addCapability(NET_CAPABILITY_NOT_METERED)
13077 .addCapability(NET_CAPABILITY_VALIDATED);
13078 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
13079 }
13080
13081 private NetworkRequest createOemPaidNetworkRequest() {
13082 // NET_CAPABILITY_OEM_PAID is a restricted capability.
13083 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13084 .addCapability(NET_CAPABILITY_OEM_PAID)
13085 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13086 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13087 }
13088
13089 private NetworkRequest createOemPrivateNetworkRequest() {
13090 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
13091 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13092 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
13093 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13094 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13095 }
13096
13097 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070013098 final NetworkCapabilities netcap = new NetworkCapabilities();
13099 netcap.addCapability(NET_CAPABILITY_INTERNET);
13100 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
13101 return netcap;
13102 }
13103
13104 private NetworkRequest createTestNetworkRequest() {
13105 final NetworkCapabilities netcap = new NetworkCapabilities();
13106 netcap.clearAll();
13107 netcap.addTransportType(TRANSPORT_TEST);
13108 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080013109 }
James Mattis47db0582021-01-01 14:13:35 -080013110 }
markchien738ad912021-12-09 18:15:45 +080013111
Junyu Lai38c75032023-12-04 07:52:19 +000013112 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080013113 @Override
Junyu Laidf210362023-10-24 02:47:50 +000013114 public void setDataSaverEnabled(final boolean enable) {
13115 enforceNetworkStackOrSettingsPermission();
13116 try {
13117 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
13118 if (!ret) {
13119 throw new IllegalStateException("Error when changing iptables: " + enable);
13120 }
13121 } catch (RemoteException e) {
13122 // Lack of permission or binder errors.
13123 throw new IllegalStateException(e);
13124 }
Ken Chen24330172023-10-20 13:02:14 +080013125
13126 try {
13127 mBpfNetMaps.setDataSaverEnabled(enable);
13128 } catch (ServiceSpecificException | UnsupportedOperationException e) {
13129 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
13130 }
Junyu Laidf210362023-10-24 02:47:50 +000013131 }
13132
13133 @Override
markchien738ad912021-12-09 18:15:45 +080013134 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
13135 enforceNetworkStackOrSettingsPermission();
13136
13137 try {
13138 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013139 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013140 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013141 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013142 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013143 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013144 throw new IllegalStateException(e);
13145 }
13146 }
13147
13148 @Override
13149 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13150 enforceNetworkStackOrSettingsPermission();
13151
13152 try {
13153 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013154 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013155 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013156 mBpfNetMaps.removeNaughtyApp(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 }
markchiene1561fa2021-12-09 22:00:56 +080013162
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013163 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13164 throws PackageManager.NameNotFoundException {
13165 final PackageManager pm = mContext.getPackageManager();
13166 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13167 if (appId < Process.FIRST_APPLICATION_UID) {
13168 throw new RuntimeException("Can't set package firewall rule for system app "
13169 + packageName + " with appId " + appId);
13170 }
13171 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13172 final int uid = uh.getUid(appId);
13173 setUidFirewallRule(chain, uid, rule);
13174 }
13175 return appId;
13176 }
13177
markchiene1561fa2021-12-09 22:00:56 +080013178 @Override
markchien3c04e662022-03-22 16:29:56 +080013179 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013180 enforceNetworkStackOrSettingsPermission();
13181
markchien3c04e662022-03-22 16:29:56 +080013182 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13183 int firewallRule = getFirewallRuleType(chain, rule);
13184
13185 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13186 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13187 }
13188
markchiene1561fa2021-12-09 22:00:56 +080013189 try {
markchien3c04e662022-03-22 16:29:56 +080013190 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013191 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013192 throw new IllegalStateException(e);
13193 }
13194 }
markchien98a6f952022-01-13 23:43:53 +080013195
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013196 private int getPackageFirewallRule(final int chain, final String packageName)
13197 throws PackageManager.NameNotFoundException {
13198 final PackageManager pm = mContext.getPackageManager();
13199 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13200 return getUidFirewallRule(chain, appId);
13201 }
13202
Motomu Utsumi900b8062023-01-19 16:16:49 +090013203 @Override
13204 public int getUidFirewallRule(final int chain, final int uid) {
13205 enforceNetworkStackOrSettingsPermission();
13206 return mBpfNetMaps.getUidRule(chain, uid);
13207 }
13208
markchien3c04e662022-03-22 16:29:56 +080013209 private int getFirewallRuleType(int chain, int rule) {
13210 final int defaultRule;
13211 switch (chain) {
13212 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013213 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13214 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013215 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013216 defaultRule = FIREWALL_RULE_ALLOW;
13217 break;
13218 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13219 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13220 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13221 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013222 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013223 defaultRule = FIREWALL_RULE_DENY;
13224 break;
13225 default:
13226 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13227 }
13228 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13229
13230 return rule;
13231 }
13232
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013233 private void closeSocketsForFirewallChainLocked(final int chain)
13234 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013235 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013236 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13237 // So, close all non-system socket owned by uids that are not explicitly allowed
13238 Set<Range<Integer>> ranges = new ArraySet<>();
13239 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13240 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13241 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13242 } else {
13243 // Denylist means the firewall allows all by default, uids must be explicitly denied
13244 // So, close socket owned by uids that are explicitly denied
13245 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13246 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13247 }
13248 }
13249
markchien98a6f952022-01-13 23:43:53 +080013250 @Override
13251 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13252 enforceNetworkStackOrSettingsPermission();
13253
13254 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013255 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013256 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013257 throw new IllegalStateException(e);
13258 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013259
Chalard Jeandf29a852023-05-29 17:02:43 +090013260 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013261 try {
13262 closeSocketsForFirewallChainLocked(chain);
13263 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13264 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13265 }
13266 }
markchien98a6f952022-01-13 23:43:53 +080013267 }
13268
markchien00a0bed2022-01-13 23:46:13 +080013269 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013270 public boolean getFirewallChainEnabled(final int chain) {
13271 enforceNetworkStackOrSettingsPermission();
13272
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013273 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013274 }
13275
13276 @Override
markchien00a0bed2022-01-13 23:46:13 +080013277 public void replaceFirewallChain(final int chain, final int[] uids) {
13278 enforceNetworkStackOrSettingsPermission();
13279
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013280 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013281 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013282
13283 @Override
13284 public IBinder getCompanionDeviceManagerProxyService() {
13285 enforceNetworkStackPermission(mContext);
13286 return mCdmps;
13287 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013288
13289 @Override
13290 public IBinder getRoutingCoordinatorService() {
13291 enforceNetworkStackPermission(mContext);
13292 return mRoutingCoordinatorService;
13293 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013294}