blob: ba9ea868bbbb4b48a4472232f3e933ffee13c509 [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;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090035import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
36import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000037import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang9fe47be2021-06-08 13:11:45 +080038import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070039import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080040import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
41import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
42import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090043import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090044import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090045import static android.net.ConnectivityManager.TYPE_MOBILE;
46import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
48import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
49import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
50import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
51import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
52import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
53import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
54import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070055import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090056import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070057import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090058import static android.net.ConnectivityManager.TYPE_WIFI;
59import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070060import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070061import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080062import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080063import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080066import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040067import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
74import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080077import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080079import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
80import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080081import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090082import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090083import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080084import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
85import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080086import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
87import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
88import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090089import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090090import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060091import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070092import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080093import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090094import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070095import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
96import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070097import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080098import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +010099import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700100import static android.system.OsConstants.IPPROTO_TCP;
101import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900102
Junyu Lai155760b2023-10-05 14:51:00 +0800103import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
104import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
105import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
106import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
107import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Xiao Ma60142372022-07-16 17:30:20 +0900108import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800109import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800110import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
111import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
112import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900113import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900114
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800115import static java.util.Map.Entry;
116
Chalard Jean5b639762020-03-09 21:25:37 +0900117import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000118import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800119import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600120import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800121import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000122import android.app.ActivityManager;
123import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800124import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800125import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700126import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700127import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900128import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800129import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700130import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800131import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132import android.content.ContentResolver;
133import android.content.Context;
134import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700135import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800136import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900137import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700138import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800139import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900140import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900141import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700142import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800143import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800144import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900146import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800147import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900148import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800149import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900150import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800151import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700152import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900153import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800154import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800155import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800156import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800157import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800158import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900159import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900160import android.net.INetworkMonitor;
161import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900162import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900163import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700164import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800165import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900166import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900167import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900168import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800169import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900170import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900171import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100172import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800173import android.net.NativeNetworkConfig;
174import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800175import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700176import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700177import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900178import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700179import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800180import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700181import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900182import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900183import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000184import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900185import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700186import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900187import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700188import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900189import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700190import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800191import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900192import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700193import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000194import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800195import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900196import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800197import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400198import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700199import android.net.QosCallbackException;
200import android.net.QosFilter;
201import android.net.QosSocketFilter;
202import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700203import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800204import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800205import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900206import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400207import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800208import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800209import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400210import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800211import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900212import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900213import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900214import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900215import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800216import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900217import android.net.networkstack.ModuleNetworkStackClient;
218import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900219import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800220import android.net.resolv.aidl.DnsHealthEventParcel;
221import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
222import android.net.resolv.aidl.Nat64PrefixEventParcel;
223import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900224import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900225import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800226import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800227import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800228import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700229import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000230import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700232import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700233import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800234import android.os.Looper;
235import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700236import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700237import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900238import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800239import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700240import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700241import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800242import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700243import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900244import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900245import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700246import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700247import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400248import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800249import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900250import android.stats.connectivity.MeteredState;
251import android.stats.connectivity.RequestType;
252import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900253import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700254import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700255import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700256import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800257import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900258import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000259import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600260import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900261import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900262import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700263import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700264import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900265import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800266
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800267import androidx.annotation.RequiresApi;
268
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900269import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400270import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400271import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700272import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900273import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900274import com.android.metrics.ConnectionDurationForTransports;
275import com.android.metrics.ConnectionDurationPerTransports;
276import com.android.metrics.ConnectivitySampleMetricsHelper;
277import com.android.metrics.ConnectivityStateSample;
278import com.android.metrics.NetworkCountForTransports;
279import com.android.metrics.NetworkCountPerTransports;
280import com.android.metrics.NetworkDescription;
281import com.android.metrics.NetworkList;
282import com.android.metrics.NetworkRequestCount;
283import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800284import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900285import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800286import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000287import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900288import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800289import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900290import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900291import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100292import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900293import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
294import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900295import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800296import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800297import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100298import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000299import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800300import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
301import com.android.networkstack.apishim.ConstantsShim;
302import com.android.networkstack.apishim.common.BroadcastOptionsShim;
303import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900304import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900305import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000306import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900307import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800308import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800309import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900310import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900311import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900312import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500313import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700314import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900315import com.android.server.connectivity.FullScore;
Junyu Laif8dba342023-10-12 17:01:03 +0800316import com.android.server.connectivity.HandlerUtils;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900317import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900318import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000319import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100320import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700321import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900322import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700323import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600324import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900325import com.android.server.connectivity.NetworkNotificationManager;
326import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900327import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900328import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900329import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700330import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900331import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900332import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700333import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900334import com.android.server.connectivity.RoutingCoordinatorService;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800335import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000336import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800337import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600338
Josh Gao461a1222020-06-16 15:58:11 -0700339import libcore.io.IoUtils;
340
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900341import org.xmlpull.v1.XmlPullParserException;
342
The Android Open Source Project28527d22009-03-03 19:31:44 -0800343import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100344import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900345import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800346import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900347import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700348import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700349import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900350import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900351import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700352import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700353import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700354import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700355import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800356import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900357import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800358import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700359import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700360import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700361import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700362import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900363import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700364import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900365import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600366import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900367import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600368import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900369import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900370import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800371
372/**
373 * @hide
374 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800375public class ConnectivityService extends IConnectivityManager.Stub
376 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900377 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800378
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900379 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900380 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900381 private static final String NETWORK_ARG = "networks";
382 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800383 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900384
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900385 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900386 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
387 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800388
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900389 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700390
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100391 /**
392 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
393 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800394 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100395 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
396 * (preferably via runtime resource overlays).
397 */
398 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
399 "http://connectivitycheck.gstatic.com/generate_204";
400
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700401 // TODO: create better separation between radio types and network types
402
Robert Greenwalt2034b912009-08-12 16:08:25 -0700403 // how long to wait before switching back to a radio's default network
404 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
405 // system property that can override the above value
406 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
407 "android.telephony.apn-restore";
408
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900409 // How long to wait before putting up a "This network doesn't have an Internet connection,
410 // connect anyway?" dialog after the user selects a network that doesn't validate.
411 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
412
Chalard Jean5fb43c72022-09-08 19:03:14 +0900413 // How long to wait before considering that a network is bad in the absence of any form
414 // of connectivity (valid, partial, captive portal). If none has been detected after this
415 // delay, the stack considers this network bad, which may affect how it's handled in ranking
416 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900417 // Timeout in case the "actively prefer bad wifi" feature is on
418 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
419 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900420 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900421
junyulai0ac374f2020-12-14 18:41:52 +0800422 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900423 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
424 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800425 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700426
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800427 // Delimiter used when creating the broadcast delivery group for sending
428 // CONNECTIVITY_ACTION broadcast.
429 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
430
he_won.hwang881307a2022-03-15 21:23:52 +0900431 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900432 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900433
Daniel Brightf9e945b2020-06-15 16:10:01 -0700434 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900435 @VisibleForTesting
436 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700437
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900438 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700439 @VisibleForTesting
440 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900441
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900442 @VisibleForTesting
443 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800444 @VisibleForTesting
445 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900446 // True if the cell radio of the device is capable of time-sharing.
447 @VisibleForTesting
448 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900449
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800450 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800451 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800452 private final int mReleasePendingIntentDelayMs;
453
Chalard Jean46bfbf02022-02-02 00:56:25 +0900454 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900455
Motomu Utsumif360aa62023-01-30 17:52:20 +0900456 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700457
Chalard Jean9473c982021-07-29 20:03:04 +0900458 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800459 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700460 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800461 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700462
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900463 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700464
junyulaif2c67e42018-08-07 19:50:45 +0800465 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000466 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
467 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800468 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900469 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800470
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900471 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900472 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000473 private final int mWakeUpMark;
474 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000475 // The Context is created for UserHandle.ALL.
476 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900477 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900478 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700479 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700480 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800481
Chenbo Feng15416292018-11-08 17:36:21 -0800482 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800483 protected IDnsResolver mDnsResolver;
484 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800485 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700486 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900487 private final NetworkStatsManager mStatsManager;
488 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800489 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700490
Benedict Wong493e04b2018-11-09 14:45:34 -0800491 /**
492 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
493 * instances.
494 */
495 @GuardedBy("mTNSLock")
496 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800497 private final CompanionDeviceManagerProxyService mCdmps;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900498 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800499
500 private final Object mTNSLock = new Object();
501
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700502 private String mCurrentTcpBufferSizes;
503
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900504 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000505 new Class[] {
506 ConnectivityService.class,
507 NetworkAgent.class,
508 NetworkAgentInfo.class,
509 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900510
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500511 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400512 // Tear down networks that have no chance (e.g. even if validated) of becoming
513 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500514 // all networks have been rematched against all NetworkRequests.
515 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400516 // Don't reap networks. This should be passed when some networks have not yet been
517 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500518 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900519 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500520
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900521 private enum UnneededFor {
522 LINGER, // Determine whether this network is unneeded and should be lingered.
523 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
524 }
525
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700526 /**
paulhuaa0743d2021-05-26 21:56:03 +0800527 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800528 * should have priority. The order is passed to netd which will use it together
529 * with UID ranges to generate the corresponding IP rule. This serves to
530 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800531 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800532 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000533 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800534 *
paulhu48291862021-07-14 14:53:57 +0800535 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
536 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800537 */
paulhu48291862021-07-14 14:53:57 +0800538 // Used when sending to netd to code for "no order".
539 static final int PREFERENCE_ORDER_NONE = 0;
540 // Order for requests that don't code for a per-app preference. As it is
541 // out of the valid range, the corresponding order should be
542 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800543 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800544 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800545 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800546 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
547 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800548 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800549 static final int PREFERENCE_ORDER_OEM = 10;
550 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800551 // See {@link #setProfileNetworkPreference}.
552 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800553 static final int PREFERENCE_ORDER_PROFILE = 20;
554 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800555 // better scores are connected.
556 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800557 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800558 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900559 // Preference order that signifies the network shouldn't be set as a default network for
560 // the UIDs, only give them access to it. TODO : replace this with a boolean
561 // in NativeUidRangeConfig
562 @VisibleForTesting
563 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
564 // Bound for the lowest valid preference order.
565 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800566
567 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700568 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700569 * from one net to another. Clear happens when we get a new
570 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
571 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700572 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700573 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700574
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700575 /**
576 * used internally to reload global proxy settings
577 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700578 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700579
Robert Greenwalt34848c02011-03-25 13:09:25 -0700580 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400581 * PAC manager has received new port.
582 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800583 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400584
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700585 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900586 * used internally when registering NetworkProviders
587 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700588 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900589 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700590
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700591 /**
592 * used internally when registering NetworkAgents
593 * obj = Messenger
594 */
595 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
596
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700597 /**
598 * used to add a network request
599 * includes a NetworkRequestInfo
600 */
601 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
602
603 /**
604 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900605 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700606 * cancel it.
607 * includes a NetworkRequestInfo
608 */
609 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
610
611 /**
612 * used to add a network listener - no request
613 * includes a NetworkRequestInfo
614 */
615 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
616
617 /**
618 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400619 * arg1 = UID of caller
620 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700621 */
622 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
623
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700624 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900625 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700626 * obj = Messenger
627 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900628 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700629
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700630 /**
631 * used internally to expire a wakelock when transitioning
632 * from one net to another. Expire happens when we fail to find
633 * a new network (typically after 1 minute) -
634 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
635 * a replacement network.
636 */
637 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
638
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700639 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800640 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400641 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800642 */
643 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
644
645 /**
646 * used to remove a pending intent and its associated network request.
647 * arg1 = UID of caller
648 * obj = PendingIntent
649 */
650 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
651
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900652 /**
653 * used to specify whether a network should be used even if unvalidated.
654 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
655 * arg2 = whether to remember this choice in the future (1 or 0)
656 * obj = network
657 */
658 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
659
660 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700661 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900662 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700663 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900664
Paul Jensenc8873fc2015-06-17 14:15:39 -0400665 /**
666 * used to add a network listener with a pending intent
667 * obj = NetworkRequestInfo
668 */
669 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
670
Hugo Benichid6b510a2017-04-06 17:22:18 +0900671 /**
672 * used to specify whether a network should not be penalized when it becomes unvalidated.
673 */
674 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
675
676 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700677 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900678 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700679 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900680
Erik Kline31b4a9e2018-01-11 21:07:29 +0900681 // Handle changes in Private DNS settings.
682 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
683
dalyk1720e542018-03-05 12:42:22 -0500684 // Handle private DNS validation status updates.
685 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
686
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900687 /**
688 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
689 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800690 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
691 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
692 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900693 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900694 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900695
696 /**
697 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
698 * config was resolved.
699 * obj = PrivateDnsConfig
700 * arg2 = netid
701 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900702 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900703
704 /**
705 * Request ConnectivityService display provisioning notification.
706 * arg1 = Whether to make the notification visible.
707 * arg2 = NetID.
708 * obj = Intent to be launched when notification selected by user, null if !arg1.
709 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900710 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900711
712 /**
lucaslin2240ef62019-03-12 13:08:03 +0800713 * Used to specify whether a network should be used even if connectivity is partial.
714 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
715 * false)
716 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
717 * obj = network
718 */
lucaslin444d43a2020-02-20 16:56:59 +0800719 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800720
721 /**
lucasline117e2e2019-10-22 18:27:33 +0800722 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
723 * Both of the arguments are bitmasks, and the value of bits come from
724 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900725 * arg1 = unused
726 * arg2 = netId
727 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800728 */
lucaslin444d43a2020-02-20 16:56:59 +0800729 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800730
731 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900732 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
733 * arg1 = unused
734 * arg2 = netId
735 * obj = captive portal data
736 */
lucaslin444d43a2020-02-20 16:56:59 +0800737 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900738
739 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900740 * Used by setRequireVpnForUids.
741 * arg1 = whether the specified UID ranges are required to use a VPN.
742 * obj = Array of UidRange objects.
743 */
744 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
745
746 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900747 * Used internally when setting the default networks for OemNetworkPreferences.
748 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800749 */
750 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
751
752 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800753 * Used to indicate the system default network becomes active.
754 */
755 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
756
757 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900758 * Used internally when setting a network preference for a user profile.
759 * obj = Pair<ProfileNetworkPreference, Listener>
760 */
761 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
762
763 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000764 * Event to specify that reasons for why an uid is blocked changed.
765 * arg1 = uid
766 * arg2 = blockedReasons
767 */
768 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
769
770 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900771 * Event to register a new network offer
772 * obj = NetworkOffer
773 */
774 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
775
776 /**
777 * Event to unregister an existing network offer
778 * obj = INetworkOfferCallback
779 */
780 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
781
782 /**
paulhu51f77dc2021-06-07 02:34:20 +0000783 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
784 */
785 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
786
787 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800788 * Event to set temporary allow bad wifi within a limited time to override
789 * {@code config_networkAvoidBadWifi}.
790 */
791 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
792
793 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100794 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
795 */
796 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
797
798 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900799 * The initial evaluation period is over for this network.
800 *
801 * If no form of connectivity has been found on this network (valid, partial, captive portal)
802 * then the stack will now consider it to have been determined bad.
803 */
804 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
805
806 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000807 * Used internally when the user does not want the network from captive portal app.
808 * obj = Network
809 */
810 private static final int EVENT_USER_DOES_NOT_WANT = 58;
811
812 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000813 * Event to set VPN as preferred network for specific apps.
814 * obj = VpnNetworkPreferenceInfo
815 */
816 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
817
818 /**
chiachangwange0192a72023-02-06 13:25:01 +0000819 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
820 */
821 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
822
823 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000824 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
825 */
826 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
827
828 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900829 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
830 * should be shown.
831 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900832 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900833
834 /**
835 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
836 * should be hidden.
837 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900838 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900839
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800840 /**
841 * The maximum alive time to allow bad wifi configuration for testing.
842 */
843 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
844
Patrick Rohr2857ac42022-01-21 14:58:16 +0100845 /**
chiachangwange0192a72023-02-06 13:25:01 +0000846 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
847 * testing.
848 */
849 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
850
851 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100852 * The priority of the tc police rate limiter -- smaller value is higher priority.
853 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
854 */
855 private static final short TC_PRIO_POLICE = 1;
856
857 /**
858 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
859 */
860 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700861 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100862
Hugo Benichi47011212017-03-30 10:46:05 +0900863 private static String eventName(int what) {
864 return sMagicDecoderRing.get(what, Integer.toString(what));
865 }
866
paulhua10d8212020-11-10 15:32:56 +0800867 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900868 final DnsResolverServiceManager dsm = context.getSystemService(
869 DnsResolverServiceManager.class);
870 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800871 }
872
Cody Kesting73708bf2019-12-18 10:57:50 -0800873 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900874 @VisibleForTesting
875 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700876 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700877 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700878 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700879 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800880 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
881 @VisibleForTesting
882 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
883
Erik Kline32120082017-12-13 19:40:49 +0900884 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900885 @VisibleForTesting
886 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700887
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400888 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800889 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400890
Chalard Jean46bfbf02022-02-02 00:56:25 +0900891 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800892 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700893
Chalard Jean5d70ba42018-06-07 16:44:04 +0900894 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
895 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800896 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400897
Erik Kline05f2b402015-04-30 12:58:40 +0900898 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700899
Chalard Jean46bfbf02022-02-02 00:56:25 +0900900 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400901
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700902 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900903 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700904
Valentin Iftime9fa35092019-09-24 13:32:13 +0200905 private Set<String> mWolSupportedInterfaces;
906
Roshan Pius08c94fb2020-01-16 12:17:17 -0800907 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800908 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800909 private final AppOpsManager mAppOpsManager;
910
911 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400912
chiachangwang3d60bac2023-01-17 14:38:08 +0000913 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900914 private final QosCallbackTracker mQosCallbackTracker;
915 private final NetworkNotificationManager mNotifier;
916 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900917
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700918 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800919 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700920
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900921 // Sequence number for NetworkProvider IDs.
922 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
923 NetworkProvider.FIRST_PROVIDER_ID);
924
Erik Klineedf878b2015-07-09 18:24:03 +0900925 // NetworkRequest activity String log entries.
926 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
927 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
928
Hugo Benichid159fdd2016-07-11 11:05:12 +0900929 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900930 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900931 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
932
Hugo Benichi47011212017-03-30 10:46:05 +0900933 private static final int MAX_WAKELOCK_LOGS = 20;
934 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900935 private int mTotalWakelockAcquisitions = 0;
936 private int mTotalWakelockReleases = 0;
937 private long mTotalWakelockDurationMs = 0;
938 private long mMaxWakelockDurationMs = 0;
939 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900940
Hugo Benichi208c0102016-07-28 17:53:06 +0900941 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900942
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700943 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900944 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700945
Erik Kline95ecfee2016-10-02 18:02:14 +0900946 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900947 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900948
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900949 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800950 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
951 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800952
Patrick Rohr2857ac42022-01-21 14:58:16 +0100953 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
954 // configured via {@link
955 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
956 // Only the handler thread is allowed to access this field.
957 private long mIngressRateLimit = -1;
958
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900959 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
960 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900961 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900962 @GuardedBy("mSelfCertifiedCapabilityCache")
963 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
964 mSelfCertifiedCapabilityCache = new HashMap<>();
965
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900966 // Flag to enable the feature of closing frozen app sockets.
967 private final boolean mDestroyFrozenSockets;
968
969 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
970 private final boolean mDelayDestroyFrozenSockets;
971
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900972 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
973 private final boolean mAllowSysUiConnectivityReports;
974
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900975 // Uids that ConnectivityService is pending to close sockets of.
976 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
977
Robert Greenwalt802c1102014-06-02 15:32:02 -0700978 /**
979 * Implements support for the legacy "one network per network type" model.
980 *
981 * We used to have a static array of NetworkStateTrackers, one for each
982 * network type, but that doesn't work any more now that we can have,
983 * for example, more that one wifi network. This class stores all the
984 * NetworkAgentInfo objects that support a given type, but the legacy
985 * API will only see the first one.
986 *
987 * It serves two main purposes:
988 *
989 * 1. Provide information about "the network for a given type" (since this
990 * API only supports one).
991 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
992 * the first network for a given type changes, or if the default network
993 * changes.
994 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900995 @VisibleForTesting
996 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900997
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900998 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900999 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001000
Robert Greenwalt802c1102014-06-02 15:32:02 -07001001 /**
1002 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1003 * Each list holds references to all NetworkAgentInfos that are used to
1004 * satisfy requests for that network type.
1005 *
1006 * This array is built out at startup such that an unsupported network
1007 * doesn't get an ArrayList instance, making this a tristate:
1008 * unsupported, supported but not active and active.
1009 *
1010 * The actual lists are populated when we scan the network types that
1011 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001012 *
1013 * Threading model:
1014 * - addSupportedType() is only called in the constructor
1015 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1016 * They are therefore not thread-safe with respect to each other.
1017 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1018 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001019 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001020 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001021 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001022 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001023 @NonNull
1024 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001025
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001026 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1027 // an entry have no timer (equivalent to -1). Lazily loaded.
1028 @NonNull
1029 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1030
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001031 LegacyTypeTracker(@NonNull ConnectivityService service) {
1032 mService = service;
1033 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001034 }
1035
Chiachang Wang3bc52762021-11-25 14:17:57 +08001036 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1037 // addressed.
1038 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001039 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1040 final PackageManager pm = ctx.getPackageManager();
1041 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1042 addSupportedType(TYPE_WIFI);
1043 }
1044 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1045 addSupportedType(TYPE_WIFI_P2P);
1046 }
1047 if (tm.isDataCapable()) {
1048 // Telephony does not have granular support for these types: they are either all
1049 // supported, or none is supported
1050 addSupportedType(TYPE_MOBILE);
1051 addSupportedType(TYPE_MOBILE_MMS);
1052 addSupportedType(TYPE_MOBILE_SUPL);
1053 addSupportedType(TYPE_MOBILE_DUN);
1054 addSupportedType(TYPE_MOBILE_HIPRI);
1055 addSupportedType(TYPE_MOBILE_FOTA);
1056 addSupportedType(TYPE_MOBILE_IMS);
1057 addSupportedType(TYPE_MOBILE_CBS);
1058 addSupportedType(TYPE_MOBILE_IA);
1059 addSupportedType(TYPE_MOBILE_EMERGENCY);
1060 }
1061 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1062 addSupportedType(TYPE_BLUETOOTH);
1063 }
1064 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1065 // TYPE_PROXY is only used on Wear
1066 addSupportedType(TYPE_PROXY);
1067 }
1068 // Ethernet is often not specified in the configs, although many devices can use it via
1069 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001070 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001071 addSupportedType(TYPE_ETHERNET);
1072 }
1073
1074 // Always add TYPE_VPN as a supported type
1075 addSupportedType(TYPE_VPN);
1076 }
1077
1078 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001079 if (mTypeLists[type] != null) {
1080 throw new IllegalStateException(
1081 "legacy list for type " + type + "already initialized");
1082 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001083 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001084 }
1085
Robert Greenwalt802c1102014-06-02 15:32:02 -07001086 public boolean isTypeSupported(int type) {
1087 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1088 }
1089
1090 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001091 synchronized (mTypeLists) {
1092 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1093 return mTypeLists[type].get(0);
1094 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001095 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001096 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001097 }
1098
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001099 public int getRestoreTimerForType(int type) {
1100 synchronized (mTypeLists) {
1101 if (mRestoreTimers == null) {
1102 mRestoreTimers = loadRestoreTimers();
1103 }
1104 return mRestoreTimers.getOrDefault(type, -1);
1105 }
1106 }
1107
1108 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1109 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001110 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001111 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1112 for (final String config : configs) {
1113 final String[] splits = TextUtils.split(config, ",");
1114 if (splits.length != 2) {
1115 logwtf("Invalid restore timer token count: " + config);
1116 continue;
1117 }
1118 try {
1119 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1120 } catch (NumberFormatException e) {
1121 logwtf("Invalid restore timer number format: " + config, e);
1122 }
1123 }
1124 return ret;
1125 }
1126
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001127 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001128 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001129 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001130 log("Sending " + state
1131 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001132 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001133 }
1134 }
1135
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001136 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1137 // network type, to preserve previous behaviour.
1138 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1139 if (vpnNai != mService.getLegacyLockdownNai()) return;
1140
1141 if (vpnNai.declaredUnderlyingNetworks == null
1142 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1143 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1144 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1145 return;
1146 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001147 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001148 vpnNai.declaredUnderlyingNetworks[0]);
1149 if (underlyingNai == null) return;
1150
1151 final int type = underlyingNai.networkInfo.getType();
1152 final DetailedState state = DetailedState.CONNECTED;
1153 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1154 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1155 }
1156
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001157 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001158 public void add(int type, NetworkAgentInfo nai) {
1159 if (!isTypeSupported(type)) {
1160 return; // Invalid network type.
1161 }
1162 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1163
1164 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1165 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001166 return;
1167 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001168 synchronized (mTypeLists) {
1169 list.add(nai);
1170 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001171
Chalard Jean5b409c72021-02-04 13:12:59 +09001172 // Send a broadcast if this is the first network of its type or if it's the default.
1173 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001174
1175 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1176 // to preserve previous behaviour.
1177 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001178 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001179 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1180 mService.sendLegacyNetworkBroadcast(nai, state, type);
1181 }
1182
1183 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1184 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001185 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001186 }
1187
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001188 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001189 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001190 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1191 if (list == null || list.isEmpty()) {
1192 return;
1193 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001194 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001195
Hugo Benichi389633f2016-06-21 09:48:07 +09001196 synchronized (mTypeLists) {
1197 if (!list.remove(nai)) {
1198 return;
1199 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001200 }
1201
Lorenzo Colitti49767722015-05-01 00:30:10 +09001202 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001203 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1204 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001205 }
1206
1207 if (!list.isEmpty() && wasFirstNetwork) {
1208 if (DBG) log("Other network available for type " + type +
1209 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001210 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001211 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001212 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001213 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001214 }
1215 }
1216
1217 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001218 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1219 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001220 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001221 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001222 }
1223 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001224
Chalard Jean46bfbf02022-02-02 00:56:25 +09001225 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001226 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001227 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001228 final DetailedState state = nai.networkInfo.getDetailedState();
1229 for (int type = 0; type < mTypeLists.length; type++) {
1230 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001231 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001232 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001233 if (isFirst || contains && isDefault) {
1234 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001235 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001236 }
1237 }
1238 }
1239
Robert Greenwalt94e22142014-07-30 16:31:24 -07001240 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001241 pw.println("mLegacyTypeTracker:");
1242 pw.increaseIndent();
1243 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001244 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001245 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001246 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001247 pw.println();
1248 pw.println("Current state:");
1249 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001250 synchronized (mTypeLists) {
1251 for (int type = 0; type < mTypeLists.length; type++) {
1252 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1253 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001254 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001255 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001256 }
1257 }
1258 pw.decreaseIndent();
1259 pw.decreaseIndent();
1260 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001261 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001262 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001263 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001264
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001265 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001266 /**
1267 * Helper class which parses out priority arguments and dumps sections according to their
1268 * priority. If priority arguments are omitted, function calls the legacy dump command.
1269 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001270 private class LocalPriorityDump {
1271 private static final String PRIORITY_ARG = "--dump-priority";
1272 private static final String PRIORITY_ARG_HIGH = "HIGH";
1273 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001274 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001275
1276 LocalPriorityDump() {}
1277
1278 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Laif8dba342023-10-12 17:01:03 +08001279 if (!HandlerUtils.runWithScissors(mHandler, () -> {
1280 doDump(fd, pw, new String[]{DIAG_ARG});
1281 doDump(fd, pw, new String[]{SHORT_ARG});
1282 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1283 pw.println("dumpHigh timeout");
1284 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001285 }
1286
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001287 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Laif8dba342023-10-12 17:01:03 +08001288 if (!HandlerUtils.runWithScissors(mHandler, () -> doDump(fd, pw, args),
1289 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1290 pw.println("dumpNormal timeout");
1291 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001292 }
1293
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001294 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1295 if (args == null) {
1296 dumpNormal(fd, pw, args);
1297 return;
1298 }
1299
1300 String priority = null;
1301 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1302 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1303 argIndex++;
1304 priority = args[argIndex];
1305 }
1306 }
1307
1308 if (PRIORITY_ARG_HIGH.equals(priority)) {
1309 dumpHigh(fd, pw);
1310 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1311 dumpNormal(fd, pw, args);
1312 } else {
1313 // ConnectivityService publishes binder service using publishBinderService() with
1314 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001315 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1316 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001317 // TODO: Integrate into signal dump.
1318 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001319 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001320 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001321 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001322
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001323 /**
1324 * Dependencies of ConnectivityService, for injection in tests.
1325 */
1326 @VisibleForTesting
1327 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001328 public int getCallingUid() {
1329 return Binder.getCallingUid();
1330 }
1331
Chalard Jeandf29a852023-05-29 17:02:43 +09001332 public boolean isAtLeastS() {
1333 return SdkLevel.isAtLeastS();
1334 }
1335
1336 public boolean isAtLeastT() {
1337 return SdkLevel.isAtLeastT();
1338 }
1339
1340 public boolean isAtLeastU() {
1341 return SdkLevel.isAtLeastU();
1342 }
1343
Chalard Jeaneb663892023-10-07 15:17:07 +09001344 public boolean isAtLeastV() {
1345 return SdkLevel.isAtLeastV();
1346 }
1347
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001348 /**
1349 * Get system properties to use in ConnectivityService.
1350 */
1351 public MockableSystemProperties getSystemProperties() {
1352 return new MockableSystemProperties();
1353 }
1354
1355 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001356 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1357 */
1358 public ConnectivityResources getResources(@NonNull Context ctx) {
1359 return new ConnectivityResources(ctx);
1360 }
1361
1362 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001363 * Create a HandlerThread to use in ConnectivityService.
1364 */
1365 public HandlerThread makeHandlerThread() {
1366 return new HandlerThread("ConnectivityServiceThread");
1367 }
1368
1369 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001370 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001371 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001372 public NetworkStackClientBase getNetworkStack() {
1373 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001374 }
1375
1376 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001377 * @see ProxyTracker
1378 */
1379 public ProxyTracker makeProxyTracker(@NonNull Context context,
1380 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001381 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001382 }
1383
1384 /**
1385 * @see NetIdManager
1386 */
1387 public NetIdManager makeNetIdManager() {
1388 return new NetIdManager();
1389 }
1390
1391 /**
1392 * @see NetworkUtils#queryUserAccess(int, int)
1393 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001394 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1395 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001396 }
1397
1398 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001399 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1400 * requires CAP_NET_ADMIN, which the unit tests do not have.
1401 */
1402 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1403 InetSocketAddress remote) {
1404 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1405 }
1406
1407 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001408 * @see MultinetworkPolicyTracker
1409 */
1410 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1411 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1412 return new MultinetworkPolicyTracker(c, h, r);
1413 }
1414
Aaron Huang330a4c02020-10-27 03:36:19 +08001415 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001416 * @see AutomaticOnOffKeepaliveTracker
1417 */
1418 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1419 @NonNull Context c, @NonNull Handler h) {
1420 return new AutomaticOnOffKeepaliveTracker(c, h);
1421 }
1422
1423 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001424 * @see BatteryStatsManager
1425 */
1426 public void reportNetworkInterfaceForTransports(Context context, String iface,
1427 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001428 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001429 context.getSystemService(BatteryStatsManager.class);
1430 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1431 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001432
1433 public boolean getCellular464XlatEnabled() {
1434 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1435 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001436
1437 /**
1438 * @see PendingIntent#intentFilterEquals
1439 */
1440 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1441 return a.intentFilterEquals(b);
1442 }
1443
1444 /**
1445 * @see LocationPermissionChecker
1446 */
1447 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1448 return new LocationPermissionChecker(context);
1449 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001450
1451 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001452 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001453 *
1454 * This method returns null in versions before T, where carrier privilege
1455 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001456 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001457 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001458 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1459 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001460 if (isAtLeastT()) {
Chalard Jean84dfa9f2023-01-30 11:23:20 +09001461 return new CarrierPrivilegeAuthenticator(context, this, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001462 } else {
1463 return null;
1464 }
1465 }
1466
1467 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001468 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001469 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001470 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001471 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001472 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001473
1474 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001475 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1476 */
1477 public boolean isFeatureNotChickenedOut(Context context, String name) {
1478 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1479 }
1480
1481 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001482 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001483 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001484 * @return BpfNetMaps implementation.
1485 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001486 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1487 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001488 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001489
1490 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001491 * @see ClatCoordinator
1492 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001493 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001494 public ClatCoordinator getClatCoordinator(INetd netd) {
1495 return new ClatCoordinator(
1496 new ClatCoordinator.Dependencies() {
1497 @NonNull
1498 public INetd getNetd() {
1499 return netd;
1500 }
1501 });
1502 }
1503
1504 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001505 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1506 */
1507 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1508 final InterfaceParams params = InterfaceParams.getByName(iface);
1509 if (params == null) {
1510 // the interface might have disappeared.
1511 logw("Failed to get interface params for interface " + iface);
1512 return;
1513 }
1514 try {
1515 // converting rateInBytesPerSecond from long to int is safe here because the
1516 // setting's range is limited to INT_MAX.
1517 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001518 Log.i(TAG,
1519 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001520 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1521 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1522 } catch (IOException e) {
1523 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1524 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1525 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1526 + ") failure: ", e);
1527 }
1528 }
1529
1530 /**
1531 * Wraps {@link TcUtils#tcFilterDelDev}
1532 */
1533 public void disableIngressRateLimit(String iface) {
1534 final InterfaceParams params = InterfaceParams.getByName(iface);
1535 if (params == null) {
1536 // the interface might have disappeared.
1537 logw("Failed to get interface params for interface " + iface);
1538 return;
1539 }
1540 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001541 Log.i(TAG,
1542 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001543 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1544 } catch (IOException e) {
1545 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1546 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1547 }
1548 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001549
1550 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001551 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1552 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001553 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001554 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001555 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001556 }
1557
1558 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001559 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1560 */
1561 // TODO: when available in all active branches:
1562 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1563 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1564 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1565 return BroadcastOptionsShimImpl.newInstance(options);
1566 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001567
1568 /**
1569 * Wrapper method for
1570 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1571 *
1572 * @param changeId The ID of the compatibility change in question.
1573 * @param packageName The package name of the app in question.
1574 * @param user The user that the operation is done for.
1575 * @return {@code true} if the change is enabled for the specified package.
1576 */
1577 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1578 @NonNull final UserHandle user) {
1579 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1580 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001581
1582 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001583 * As above but with a UID.
1584 * @see CompatChanges#isChangeEnabled(long, int)
1585 */
1586 public boolean isChangeEnabled(final long changeId, final int uid) {
1587 return CompatChanges.isChangeEnabled(changeId, uid);
1588 }
1589
1590 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001591 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1592 *
1593 * @param ranges target uid ranges
1594 * @param exemptUids uids to skip close socket
1595 */
1596 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1597 @NonNull final Set<Integer> exemptUids)
1598 throws SocketException, InterruptedIOException, ErrnoException {
1599 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1600 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001601
1602 /**
1603 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1604 *
1605 * @param ownerUids target uids to close sockets
1606 */
1607 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1608 throws SocketException, InterruptedIOException, ErrnoException {
1609 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1610 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001611
1612 /**
1613 * Schedule the evaluation timeout.
1614 *
1615 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1616 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1617 * of these events happen, this time will run out, after which the network is considered
1618 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1619 * on this network and considers it won't provide connectivity. In particular, that means
1620 * it's when the system prefers it to cell if it's wifi and configuration says it should
1621 * prefer bad wifi to cell.
1622 */
1623 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1624 @NonNull final Network network, final long delayMs) {
1625 handler.sendMessageDelayed(
1626 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1627 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001628 }
1629
junyulaie7c7d2a2021-01-26 15:29:15 +08001630 public ConnectivityService(Context context) {
1631 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001632 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1633 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001634 }
1635
1636 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001637 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1638 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001639 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001640
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001641 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001642 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001643 mSystemProperties = mDeps.getSystemProperties();
1644 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001645 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001646 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001647 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1648 // Pass limit - 1 to maintain backward compatibility.
1649 // TODO: Remove the workaround.
1650 mNetworkRequestCounter =
1651 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1652 mSystemNetworkRequestCounter =
1653 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001654
Hugo Benichi208c0102016-07-28 17:53:06 +09001655 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001656 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1657 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001658 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001659 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001660 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001661 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1662 mDefaultNetworkRequests.add(mDefaultRequest);
1663 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001664
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001665 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001666 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001667
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001668 // The default WiFi request is a background request so that apps using WiFi are
1669 // migrated to a better network (typically ethernet) when one comes up, instead
1670 // of staying on WiFi forever.
1671 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1672 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1673
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001674 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1675 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1676 NetworkRequest.Type.BACKGROUND_REQUEST);
1677
Chalard Jean0702f982021-09-16 21:50:07 +09001678 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1679 // TODO: Consider making the timer customizable.
1680 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1681 mCellularRadioTimesharingCapable =
1682 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1683
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001684 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1685 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1686
1687 if (SdkLevel.isAtLeastU()) {
1688 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1689 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1690 final int defaultUMarkMask = 0x80000000; // u32
1691
1692 if ((mark == 0) || (mask == 0)) {
1693 // simply treat unset/disabled as the default U value
1694 mark = defaultUMarkMask;
1695 mask = defaultUMarkMask;
1696 }
1697 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1698 // invalid device overlay settings
1699 throw new IllegalArgumentException(
1700 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1701 }
1702 }
1703
1704 mWakeUpMark = mark;
1705 mWakeUpMask = mask;
1706
Paul Hu51f816b2022-08-11 14:43:47 +00001707 mNetd = netd;
1708 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001709 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001710 mPermissionMonitor =
1711 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001712 mHandlerThread.start();
1713 mHandler = new InternalHandler(mHandlerThread.getLooper());
1714 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001715 mConnectivityDiagnosticsHandler =
1716 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001717
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001718 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001719 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001720
junyulaie7c7d2a2021-01-26 15:29:15 +08001721 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001722 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001723 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001724 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001725
Wink Saville32506bc2013-06-29 21:10:57 -07001726 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001727 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001728 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001729 mCarrierPrivilegeAuthenticator =
1730 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001731
Sudheer Shanka9967d462021-03-18 19:09:25 +00001732 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001733 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1734 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001735 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001736
1737 final PowerManager powerManager = (PowerManager) context.getSystemService(
1738 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001739 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001740 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001741
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001742 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1743 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001744 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001745 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001746 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001747 mProtectedNetworks.add(p);
1748 } else {
1749 if (DBG) loge("Ignoring protectedNetwork " + p);
1750 }
1751 }
1752
soma, kawata29444ae2019-05-23 09:30:40 +09001753 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1754
James Mattis02220e22021-03-13 19:27:21 -08001755 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001756 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001757 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001758 final IntentFilter userIntentFilter = new IntentFilter();
1759 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1760 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1761 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1762 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001763
James Mattis02220e22021-03-13 19:27:21 -08001764 // Listen to package add/removes for netd
1765 final IntentFilter packageIntentFilter = new IntentFilter();
1766 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1767 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1768 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1769 packageIntentFilter.addDataScheme("package");
1770 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001771 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001772
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09001773 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
1774 // But reading the trunk stable flags from mainline modules is not supported yet.
1775 // So enabling this feature on V+ release.
1776 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
1777 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
1778 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001779
Chalard Jean46bfbf02022-02-02 00:56:25 +09001780 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001781 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001782 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001783 } catch (RemoteException | ServiceSpecificException e) {
1784 loge("Error registering event listener :" + e);
1785 }
1786
Erik Kline05f2b402015-04-30 12:58:40 +09001787 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1788 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001789
chiachangwang7c17c282023-02-02 05:58:59 +00001790 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001791 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001792 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001793
1794 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001795 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001796 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1797 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001798 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001799 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1800 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001801
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001802 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001803 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001804 mNetworkRanker =
1805 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1806
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001807 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001808
Chiachang Wangc1215d32020-10-20 15:38:58 +08001809 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001810 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001811
Chalard Jean28018572020-12-21 18:36:52 +09001812 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1813 // request that doesn't allow fallback to the default network. It should never be visible
1814 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1815 // arguments like the handler or the DnsResolver.
1816 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001817 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001818 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001819 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001820 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001821 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001822 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1823 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001824
1825 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001826 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1827 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1828 // Even if it could, running on S would at least require mocking out the BPF map,
1829 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1830 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001831 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001832 mDscpPolicyTracker = new DscpPolicyTracker();
1833 }
Tyler Wear72388212021-09-09 14:49:02 -07001834 } catch (ErrnoException e) {
1835 loge("Unable to create DscpPolicyTracker");
1836 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001837
1838 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1839 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001840
Chalard Jeandf29a852023-05-29 17:02:43 +09001841 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001842 mCdmps = new CompanionDeviceManagerProxyService(context);
1843 } else {
1844 mCdmps = null;
1845 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001846
Chalard Jean2fb66f12023-08-25 12:50:37 +09001847 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
1848
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001849 mDestroyFrozenSockets = mDeps.isAtLeastU()
1850 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1851 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1852 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001853 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1854 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001855 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001856 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1857 new UidFrozenStateChangedCallback() {
1858 @Override
1859 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1860 if (uids.length != frozenStates.length) {
1861 Log.wtf(TAG, "uids has length " + uids.length
1862 + " but frozenStates has length " + frozenStates.length);
1863 return;
1864 }
1865
1866 final UidFrozenStateChangedArgs args =
1867 new UidFrozenStateChangedArgs(uids, frozenStates);
1868
1869 mHandler.sendMessage(
1870 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1871 }
1872 };
1873
1874 final ActivityManager activityManager =
1875 mContext.getSystemService(ActivityManager.class);
1876 activityManager.registerUidFrozenStateChangedCallback(
1877 (Runnable r) -> r.run(), frozenStateChangedCallback);
1878 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001879 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001880
Xiao Ma0a171c02022-01-23 16:14:51 +00001881 /**
1882 * Check whether or not the device supports Ethernet transport.
1883 */
1884 public static boolean deviceSupportsEthernet(final Context context) {
1885 final PackageManager pm = context.getPackageManager();
1886 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1887 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1888 }
1889
Chalard Jean46adcf32018-04-18 20:18:38 +09001890 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001891 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1892 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001893 }
1894
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001895 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1896 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001897 final NetworkCapabilities netCap = new NetworkCapabilities();
1898 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001899 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001900 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001901 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001902 return netCap;
1903 }
1904
James Mattis45d81842021-01-10 14:24:24 -08001905 private NetworkRequest createDefaultRequest() {
1906 return createDefaultInternetRequestForTransport(
1907 TYPE_NONE, NetworkRequest.Type.REQUEST);
1908 }
1909
lucaslin3ba7cc22022-12-19 02:35:33 +00001910 private NetworkRequest createVpnRequest() {
1911 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1912 .withoutDefaultCapabilities()
1913 .addTransportType(TRANSPORT_VPN)
1914 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1915 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1916 .build();
1917 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1918 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1919 }
1920
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001921 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001922 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001923 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001924 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001925 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001926 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001927 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001928 netCap.addTransportType(transportType);
1929 }
James Mattis45d81842021-01-10 14:24:24 -08001930 return createNetworkRequest(type, netCap);
1931 }
1932
1933 private NetworkRequest createNetworkRequest(
1934 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001935 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001936 }
1937
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001938 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1939 NetworkRequest.Type type) {
1940 final NetworkCapabilities netCap = new NetworkCapabilities();
1941 netCap.clearAll();
1942 netCap.addCapability(capability);
1943 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1944 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1945 }
1946
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001947 // Used only for testing.
1948 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001949 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001950 // changing ContentResolver to make registerContentObserver non-final).
1951 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1952 // by subclassing SettingsObserver.
1953 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001954 void updateAlwaysOnNetworks() {
1955 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001956 }
1957
Erik Kline9a62f012018-03-21 07:18:33 -07001958 // See FakeSettingsProvider comment above.
1959 @VisibleForTesting
1960 void updatePrivateDnsSettings() {
1961 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1962 }
1963
paulhu51f77dc2021-06-07 02:34:20 +00001964 @VisibleForTesting
1965 void updateMobileDataPreferredUids() {
1966 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1967 }
1968
Patrick Rohr2857ac42022-01-21 14:58:16 +01001969 @VisibleForTesting
1970 void updateIngressRateLimit() {
1971 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1972 }
1973
Aaron Huang40b52442021-06-08 04:34:24 +08001974 @VisibleForTesting
1975 void simulateUpdateProxyInfo(@Nullable final Network network,
1976 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001977 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001978 new Pair<>(network, proxyInfo)).sendToTarget();
1979 }
1980
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001981 private void handleAlwaysOnNetworkRequest(
1982 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001983 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001984 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001985 handleAlwaysOnNetworkRequest(networkRequest, enable);
1986 }
1987
1988 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001989 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001990 if (enable == isEnabled) {
1991 return; // Nothing to do.
1992 }
1993
1994 if (enable) {
1995 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001996 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001997 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001998 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001999 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002000 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2001 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002002 }
2003 }
2004
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002005 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002006 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2007 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2008 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2009 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002010 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2011 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002012 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002013 }
2014
paulhu51f77dc2021-06-07 02:34:20 +00002015 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002016 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002017 private void registerSettingsCallbacks() {
2018 // Watch for global HTTP proxy changes.
2019 mSettingsObserver.observe(
2020 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2021 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2022
Chalard Jean46bfbf02022-02-02 00:56:25 +09002023 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002024 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002025 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002026 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2027
Chalard Jean46bfbf02022-02-02 00:56:25 +09002028 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002029 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002030 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002031 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002032
2033 // Watch for mobile data preferred uids changes.
2034 mSettingsObserver.observe(
2035 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2036 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002037
2038 // Watch for ingress rate limit changes.
2039 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002040 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002041 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2042 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002043 }
2044
Erik Kline31b4a9e2018-01-11 21:07:29 +09002045 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002046 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2047 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002048 }
2049 }
2050
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002051 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002052 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2053 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002054 return mNextNetworkRequestId++;
2055 }
2056
junyulai74f9a8b2018-06-13 15:00:37 +08002057 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002058 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002059 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002060 if (network == null) {
2061 return null;
2062 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002063 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002064 }
2065
2066 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002067 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002068 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002069 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002070 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002071
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002072 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002073 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002074 private NetworkAgentInfo getVpnForUid(int uid) {
2075 synchronized (mNetworkForNetId) {
2076 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2077 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002078 if (nai.isVPN() && nai.everConnected()
2079 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002080 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002081 }
2082 }
2083 }
2084 return null;
2085 }
2086
Chalard Jean46bfbf02022-02-02 00:56:25 +09002087 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002088 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002089 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002090 final NetworkAgentInfo nai = getVpnForUid(uid);
2091 if (nai != null) return nai.declaredUnderlyingNetworks;
2092 return null;
2093 }
2094
Lorenzo Colittia7574052021-01-19 01:33:05 +09002095 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002096 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002097
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002098 final Network[] networks = getVpnUnderlyingNetworks(uid);
2099 if (networks != null) {
2100 // getUnderlyingNetworks() returns:
2101 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2102 // empty array => the VPN explicitly said "no default network".
2103 // non-empty array => the VPN specified one or more default networks; we use the
2104 // first one.
2105 if (networks.length > 0) {
2106 nai = getNetworkAgentInfoForNetwork(networks[0]);
2107 } else {
2108 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002109 }
2110 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002111 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002112 }
2113
2114 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002115 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002116 */
paulhu7aeba372020-12-30 00:42:19 +08002117 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2118 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002119 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002120 if (ignoreBlocked) {
2121 return false;
2122 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002123 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002124 final long ident = Binder.clearCallingIdentity();
2125 try {
2126 final boolean metered = nc == null ? true : nc.isMetered();
2127 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2128 } finally {
2129 Binder.restoreCallingIdentity(ident);
2130 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002131 }
2132
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002133 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002134 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2135 return;
2136 }
Hugo Benichi47011212017-03-30 10:46:05 +09002137 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002138 synchronized (mBlockedAppUids) {
2139 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002140 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002141 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002142 blocked = false;
2143 } else {
2144 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002145 }
2146 }
Hugo Benichi47011212017-03-30 10:46:05 +09002147 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2148 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2149 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002150 }
2151
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002152 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002153 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2154 return;
2155 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002156 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002157 final int requestId = nri.getActiveRequest() != null
2158 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002159 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002160 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002161 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002162 }
2163
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002164 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002165 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002166 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002167 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002168 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002169 @NonNull
2170 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2171 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002172 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2173 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2174 // but only exists if an app asks about them or requests them. Ensure the requesting app
2175 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002176 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002177 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2178 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2179 null /* extraInfo */);
2180 }
2181 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002182 return filtered;
2183 }
2184
2185 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2186 boolean ignoreBlocked) {
2187 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2188 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002189 }
2190
2191 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002192 * Return NetworkInfo for the active (i.e., connected) network interface.
2193 * It is assumed that at most one network is active at a time. If more
2194 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002195 * @return the info for the active network, or {@code null} if none is
2196 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002197 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002198 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002199 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002200 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002201 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002202 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002203 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2204 if (nai == null) return null;
2205 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2206 maybeLogBlockedNetworkInfo(networkInfo, uid);
2207 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002208 }
2209
Paul Jensen1f567382015-02-13 14:18:39 -05002210 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002211 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002212 public Network getActiveNetwork() {
2213 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002214 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002215 }
2216
2217 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002218 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002219 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002220 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002221 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002222 }
2223
Chalard Jean46bfbf02022-02-02 00:56:25 +09002224 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002225 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002226 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2227 if (vpnNai != null) {
2228 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2229 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2230 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002231 }
Paul Jensen1f567382015-02-13 14:18:39 -05002232 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002233
James Mattis2516da32021-01-31 17:06:19 -08002234 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002235 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2236 ignoreBlocked)) {
2237 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002238 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002239 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002240 }
2241
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002242 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002243 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002244 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002245 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002246 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2247 if (nai == null) return null;
2248 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002249 }
2250
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002251 /** Returns a NetworkInfo object for a network that doesn't exist. */
2252 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2253 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2254 getNetworkTypeName(networkType), "" /* subtypeName */);
2255 info.setIsAvailable(true);
2256 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2257 // background data is restricted.
2258 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2259 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2260 ? DetailedState.BLOCKED
2261 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002262 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2263 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002264 return info;
2265 }
2266
Lorenzo Colittia7574052021-01-19 01:33:05 +09002267 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002268 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2269 return null;
2270 }
2271 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002272 if (nai == null) {
2273 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002274 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002275 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2276 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002277 }
2278
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002279 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002280 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002281 public NetworkInfo getNetworkInfo(int networkType) {
2282 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002283 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002284 if (getVpnUnderlyingNetworks(uid) != null) {
2285 // A VPN is active, so we may need to return one of its underlying networks. This
2286 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002287 // getNetworkAgentInfoForUid.
2288 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2289 if (nai == null) return null;
2290 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2291 if (networkInfo.getType() == networkType) {
2292 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002293 }
2294 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002295 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002296 }
2297
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002298 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002299 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002300 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002301 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002302 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002303 if (nai == null) return null;
2304 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002305 }
2306
2307 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002308 public NetworkInfo[] getAllNetworkInfo() {
2309 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002310 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002311 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2312 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002313 NetworkInfo info = getNetworkInfo(networkType);
2314 if (info != null) {
2315 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002316 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002317 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002318 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002319 }
2320
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002321 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002322 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002323 public Network getNetworkForType(int networkType) {
2324 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002325 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2326 return null;
2327 }
2328 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2329 if (nai == null) {
2330 return null;
2331 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002332 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002333 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2334 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002335 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002336 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002337 }
2338
2339 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002340 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002341 public Network[] getAllNetworks() {
2342 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002343 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002344 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002345 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002346 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002347 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002348 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002349 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002350 }
2351
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002352 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002353 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002354 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002355 // The basic principle is: if an app's traffic could possibly go over a
2356 // network, without the app doing anything multinetwork-specific,
2357 // (hence, by "default"), then include that network's capabilities in
2358 // the array.
2359 //
2360 // In the normal case, app traffic only goes over the system's default
2361 // network connection, so that's the only network returned.
2362 //
2363 // With a VPN in force, some app traffic may go into the VPN, and thus
2364 // over whatever underlying networks the VPN specifies, while other app
2365 // traffic may go over the system default network (e.g.: a split-tunnel
2366 // VPN, or an app disallowed by the VPN), so the set of networks
2367 // returned includes the VPN's underlying networks and the system
2368 // default.
2369 enforceAccessPermission();
2370
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002371 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002372
James Mattis2516da32021-01-31 17:06:19 -08002373 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2374 if (!nri.isBeingSatisfied()) {
2375 continue;
2376 }
2377 final NetworkAgentInfo nai = nri.getSatisfier();
2378 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2379 if (null != nc
2380 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2381 && !result.containsKey(nai.network)) {
2382 result.put(
2383 nai.network,
2384 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002385 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002386 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2387 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002388 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002389 }
2390
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002391 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002392 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002393 if (null != networks) {
2394 for (final Network network : networks) {
2395 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2396 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002397 result.put(
2398 network,
2399 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002400 nc,
2401 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002402 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002403 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002404 }
2405 }
2406 }
2407
2408 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2409 out = result.values().toArray(out);
2410 return out;
2411 }
2412
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002413 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2414 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2415 // can call sampleConnectivityState and make the checks on it.
2416 @NonNull
2417 private StatsEvent sampleConnectivityStateToStatsEvent() {
2418 final ConnectivityStateSample sample = sampleConnectivityState();
2419 return ConnectivityStatsLog.buildStatsEvent(
2420 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2421 sample.getNetworkCountPerTransports().toByteArray(),
2422 sample.getConnectionDurationPerTransports().toByteArray(),
2423 sample.getNetworkRequestCount().toByteArray(),
2424 sample.getNetworks().toByteArray());
2425 }
2426
2427 /**
2428 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2429 *
2430 * This is used for metrics. These snapshots will be sampled and constitute a base for
2431 * statistics about connectivity state of devices.
2432 */
2433 @VisibleForTesting
2434 @NonNull
2435 public ConnectivityStateSample sampleConnectivityState() {
2436 ensureRunningOnConnectivityServiceThread();
2437 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2438 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2439 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2440 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2441 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2442 return builder.build();
2443 }
2444
2445 private static NetworkCountPerTransports sampleNetworkCount(
2446 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2447 final SparseIntArray countPerTransports = new SparseIntArray();
2448 for (final NetworkAgentInfo nai : nais) {
2449 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2450 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2451 }
2452 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2453 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2454 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2455 c.setTransportTypes(countPerTransports.keyAt(i));
2456 c.setNetworkCount(countPerTransports.valueAt(i));
2457 builder.addNetworkCountForTransports(c);
2458 }
2459 return builder.build();
2460 }
2461
2462 private static ConnectionDurationPerTransports sampleConnectionDuration(
2463 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2464 final ConnectionDurationPerTransports.Builder builder =
2465 ConnectionDurationPerTransports.newBuilder();
2466 for (final NetworkAgentInfo nai : nais) {
2467 final ConnectionDurationForTransports.Builder c =
2468 ConnectionDurationForTransports.newBuilder();
2469 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2470 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2471 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2472 // Add millisPerSecond/2 to round up or down to the nearest value
2473 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2474 builder.addConnectionDurationForTransports(c);
2475 }
2476 return builder.build();
2477 }
2478
2479 private static NetworkRequestCount sampleNetworkRequestCount(
2480 @NonNull final Collection<NetworkRequestInfo> nris) {
2481 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2482 final SparseIntArray countPerType = new SparseIntArray();
2483 for (final NetworkRequestInfo nri : nris) {
2484 final int type;
2485 if (Process.SYSTEM_UID == nri.mAsUid) {
2486 // The request is filed "as" the system, so it's the system on its own behalf.
2487 type = RequestType.RT_SYSTEM.getNumber();
2488 } else if (Process.SYSTEM_UID == nri.mUid) {
2489 // The request is filed by the system as some other app, so it's the system on
2490 // behalf of an app.
2491 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2492 } else {
2493 // Not the system, so it's an app requesting on its own behalf.
2494 type = RequestType.RT_APP.getNumber();
2495 }
2496 countPerType.put(type, countPerType.get(type, 0));
2497 }
2498 for (int i = countPerType.size() - 1; i >= 0; --i) {
2499 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2500 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2501 r.setRequestCount(countPerType.valueAt(i));
2502 builder.addRequestCountForType(r);
2503 }
2504 return builder.build();
2505 }
2506
2507 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2508 final NetworkList.Builder builder = NetworkList.newBuilder();
2509 for (final NetworkAgentInfo nai : nais) {
2510 final NetworkCapabilities nc = nai.networkCapabilities;
2511 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2512 d.setTransportTypes((int) nc.getTransportTypesInternal());
2513 final MeteredState meteredState;
2514 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2515 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2516 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2517 meteredState = MeteredState.METERED_NO;
2518 } else {
2519 meteredState = MeteredState.METERED_YES;
2520 }
2521 d.setMeteredState(meteredState);
2522 final ValidatedState validatedState;
2523 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2524 validatedState = ValidatedState.VS_PORTAL;
2525 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2526 validatedState = ValidatedState.VS_PARTIAL;
2527 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2528 validatedState = ValidatedState.VS_VALID;
2529 } else {
2530 validatedState = ValidatedState.VS_INVALID;
2531 }
2532 d.setValidatedState(validatedState);
2533 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2534 d.setCapabilities(nc.getCapabilitiesInternal());
2535 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2536 builder.addNetworkDescription(d);
2537 }
2538 return builder.build();
2539 }
2540
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002541 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002542 public boolean isNetworkSupported(int networkType) {
2543 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002544 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002545 }
2546
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002547 /**
2548 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002549 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002550 * @return the ip properties for the active network, or {@code null} if
2551 * none is active
2552 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002553 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002554 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002555 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002556 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002557 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2558 if (nai == null) return null;
2559 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002560 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002561 }
2562
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002563 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002564 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002565 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002566 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002567 final LinkProperties lp = getLinkProperties(nai);
2568 if (lp == null) return null;
2569 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002570 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002571 }
2572
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002573 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002574 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002575 public LinkProperties getLinkProperties(Network network) {
2576 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002577 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2578 if (lp == null) return null;
2579 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002580 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002581 }
2582
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002583 @Nullable
2584 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002585 if (nai == null) {
2586 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002587 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002588 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002589 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002590 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002591 }
2592
lucaslinc582d502022-01-27 09:07:00 +08002593 @Override
2594 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002595 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002596 @NonNull String packageName, @Nullable String callingAttributionTag) {
2597 Objects.requireNonNull(packageName);
2598 Objects.requireNonNull(lp);
2599 enforceNetworkStackOrSettingsPermission();
2600 if (!checkAccessPermission(-1 /* pid */, uid)) {
2601 return null;
2602 }
2603 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2604 }
2605
Qingxi Lib2748102020-01-08 12:51:49 -08002606 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2607 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2608 }
2609
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002610 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002611 if (nai == null) return null;
2612 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002613 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002614 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002615 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002616 }
2617
2618 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002619 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2620 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002621 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002622 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002623 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002624 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002625 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002626 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002627 }
2628
lucaslinc582d502022-01-27 09:07:00 +08002629 @Override
lucaslind2b06132022-03-02 10:56:57 +08002630 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2631 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2632 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002633 Objects.requireNonNull(nc);
2634 Objects.requireNonNull(packageName);
2635 enforceNetworkStackOrSettingsPermission();
2636 if (!checkAccessPermission(-1 /* pid */, uid)) {
2637 return null;
2638 }
2639 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2640 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2641 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2642 callingAttributionTag);
2643 }
2644
lucaslin69e1aa92022-03-22 18:15:09 +08002645 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2646 if (nc.getUnderlyingNetworks() != null
2647 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2648 nc.setUnderlyingNetworks(null);
2649 }
2650 }
2651
Qingxi Libb8da982020-01-17 17:54:27 -08002652 @VisibleForTesting
2653 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002654 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002655 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2656 // this would be expensive (one more permission check every time any NC callback is
2657 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2658 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2659 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002660 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002661 if (!checkSettingsPermission(callerPid, callerUid)) {
2662 newNc.setUids(null);
2663 newNc.setSSID(null);
2664 }
Etan Cohen107ae952018-12-30 17:59:59 -08002665 if (newNc.getNetworkSpecifier() != null) {
2666 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2667 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002668 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2669 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002670 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2671 newNc.setAdministratorUids(new int[0]);
2672 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002673 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002674 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002675 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002676 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002677 }
lucaslin69e1aa92022-03-22 18:15:09 +08002678 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002679
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002680 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002681 }
2682
Roshan Pius98f59ec2021-02-23 08:47:39 -08002683 /**
2684 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002685 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002686 * NetworkCapabilities.
2687 * Note: This wrapper does not support any sort of invalidation and thus must not be
2688 * persistent or long-lived. It may only be used for the time necessary to
2689 * compute the redactions required by one particular NetworkCallback or
2690 * synchronous call.
2691 */
2692 private class RedactionPermissionChecker {
2693 private final int mCallingPid;
2694 private final int mCallingUid;
2695 @NonNull private final String mCallingPackageName;
2696 @Nullable private final String mCallingAttributionTag;
2697
2698 private Boolean mHasLocationPermission = null;
2699 private Boolean mHasLocalMacAddressPermission = null;
2700 private Boolean mHasSettingsPermission = null;
2701
2702 RedactionPermissionChecker(int callingPid, int callingUid,
2703 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2704 mCallingPid = callingPid;
2705 mCallingUid = callingUid;
2706 mCallingPackageName = callingPackageName;
2707 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002708 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002709
2710 private boolean hasLocationPermissionInternal() {
2711 final long token = Binder.clearCallingIdentity();
2712 try {
2713 return mLocationPermissionChecker.checkLocationPermission(
2714 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2715 null /* message */);
2716 } finally {
2717 Binder.restoreCallingIdentity(token);
2718 }
2719 }
2720
2721 /**
2722 * Returns whether the app holds location permission or not (might return cached result
2723 * if the permission was already checked before).
2724 */
2725 public boolean hasLocationPermission() {
2726 if (mHasLocationPermission == null) {
2727 // If there is no cached result, perform the check now.
2728 mHasLocationPermission = hasLocationPermissionInternal();
2729 }
2730 return mHasLocationPermission;
2731 }
2732
2733 /**
2734 * Returns whether the app holds local mac address permission or not (might return cached
2735 * result if the permission was already checked before).
2736 */
2737 public boolean hasLocalMacAddressPermission() {
2738 if (mHasLocalMacAddressPermission == null) {
2739 // If there is no cached result, perform the check now.
2740 mHasLocalMacAddressPermission =
2741 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2742 }
2743 return mHasLocalMacAddressPermission;
2744 }
2745
2746 /**
2747 * Returns whether the app holds settings permission or not (might return cached
2748 * result if the permission was already checked before).
2749 */
2750 public boolean hasSettingsPermission() {
2751 if (mHasSettingsPermission == null) {
2752 // If there is no cached result, perform the check now.
2753 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2754 }
2755 return mHasSettingsPermission;
2756 }
2757 }
2758
2759 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2760 @NetworkCapabilities.NetCapability long redaction) {
2761 return (redactions & redaction) != 0;
2762 }
2763
2764 /**
2765 * Use the provided |applicableRedactions| to check the receiving app's
2766 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2767 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2768 * before being sent to the corresponding app.
2769 */
2770 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2771 @NetworkCapabilities.RedactionType long applicableRedactions,
2772 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2773 boolean includeLocationSensitiveInfo) {
2774 long redactions = applicableRedactions;
2775 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2776 if (includeLocationSensitiveInfo
2777 && redactionPermissionChecker.hasLocationPermission()) {
2778 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2779 }
2780 }
2781 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2782 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2783 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2784 }
2785 }
2786 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2787 if (redactionPermissionChecker.hasSettingsPermission()) {
2788 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2789 }
2790 }
2791 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002792 }
2793
Qingxi Lib2748102020-01-08 12:51:49 -08002794 @VisibleForTesting
2795 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002796 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002797 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002798 int callingPid, int callingUid, @NonNull String callingPkgName,
2799 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002800 if (nc == null) {
2801 return null;
2802 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002803 // Avoid doing location permission check if the transport info has no location sensitive
2804 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002805 final RedactionPermissionChecker redactionPermissionChecker =
2806 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2807 callingAttributionTag);
2808 final long redactions = retrieveRequiredRedactions(
2809 nc.getApplicableRedactions(), redactionPermissionChecker,
2810 includeLocationSensitiveInfo);
2811 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002812 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002813 // TODO : calling UID is redacted because apps should generally not know what UID is
2814 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002815 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002816 newNc.setOwnerUid(INVALID_UID);
2817 return newNc;
2818 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002819 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2820 if (nc.hasTransport(TRANSPORT_VPN)) {
2821 // Owner UIDs already checked above. No need to re-check.
2822 return newNc;
2823 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002824 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2825 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002826 // compatibility for older apps.
2827 if (!includeLocationSensitiveInfo
2828 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002829 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002830 newNc.setOwnerUid(INVALID_UID);
2831 return newNc;
2832 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002833 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002834 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002835 newNc.setOwnerUid(INVALID_UID);
2836 }
Qingxi Lib2748102020-01-08 12:51:49 -08002837 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002838 }
2839
lucaslinc582d502022-01-27 09:07:00 +08002840 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002841 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2842 LinkProperties lp, int callerPid, int callerUid) {
2843 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002844 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2845 // this would be expensive (one more permission check every time any LP callback is
2846 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2847 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2848 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002849
2850 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2851 final boolean needsSanitization =
2852 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2853 if (!needsSanitization) {
2854 return new LinkProperties(lp);
2855 }
2856
2857 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002858 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002859 }
2860
2861 final LinkProperties newLp = new LinkProperties(lp);
2862 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2863 // object gets parceled.
2864 newLp.setCaptivePortalApiUrl(null);
2865 newLp.setCaptivePortalData(null);
2866 return newLp;
2867 }
2868
Roshan Pius08c94fb2020-01-16 12:17:17 -08002869 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2870 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002871 // There is no need to track the effective UID of the request here. If the caller
2872 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002873 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002874 // Unprivileged apps can only pass in null or their own UID.
2875 if (nc.getUids() == null) {
2876 // If the caller passes in null, the callback will also match networks that do not
2877 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2878 // In this case, redact everything in the request immediately. This ensures that the
2879 // app is not able to get any redacted information by filing an unredacted request
2880 // and observing whether the request matches something.
2881 if (nc.getNetworkSpecifier() != null) {
2882 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2883 }
2884 } else {
2885 nc.setSingleUid(callerUid);
2886 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002887 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002888 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002889 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002890
2891 // Clear owner UID; this can never come from an app.
2892 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002893 }
2894
Chalard Jean38354d12018-03-20 19:13:57 +09002895 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002896 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002897 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2898 }
2899 }
2900
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002901 @Override
2902 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2903 enforceAccessPermission();
2904 final int callerUid = Binder.getCallingUid();
2905 final long token = Binder.clearCallingIdentity();
2906 try {
2907 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2908 } finally {
2909 Binder.restoreCallingIdentity(token);
2910 }
2911 }
2912
junyulaiebd15162021-03-03 12:09:05 +08002913 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002914 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002915 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002916 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002917 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002918
Serik Beketayev05130302021-01-15 16:47:25 -08002919 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002920 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002921 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2922 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002923 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002924 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002925 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002926 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2927 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002928 }
2929 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002930 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002931 }
2932
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002933 @Override
junyulaiebd15162021-03-03 12:09:05 +08002934 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002935 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002936 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002937 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002938
2939 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2940 for (Network network : getAllNetworks()) {
2941 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002942 final boolean includeNetwork = (nai != null) && nai.isCreated();
2943 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002944 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2945 // NetworkCapabilities, which may contain UIDs of apps to which the
2946 // network applies. Should the UIDs be cleared so as not to leak or
2947 // interfere ?
2948 result.add(nai.getNetworkStateSnapshot());
2949 }
2950 }
2951 return result;
2952 }
2953
2954 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002955 public boolean isActiveNetworkMetered() {
2956 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002957
Qingxi Lib2748102020-01-08 12:51:49 -08002958 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002959 if (caps != null) {
2960 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2961 } else {
2962 // Always return the most conservative value
2963 return true;
2964 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002965 }
2966
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002967 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002968 * Ensures that the system cannot call a particular method.
2969 */
2970 private boolean disallowedBecauseSystemCaller() {
2971 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002972 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2973 // for devices launched with Q and above. However, existing devices upgrading to Q and
2974 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002975 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002976 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002977 log("This method exists only for app backwards compatibility"
2978 + " and must not be called by system services.");
2979 return true;
2980 }
2981 return false;
2982 }
2983
paulhub2c28682021-08-18 18:35:54 +08002984 private int getAppUid(final String app, final UserHandle user) {
2985 final PackageManager pm =
2986 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2987 final long token = Binder.clearCallingIdentity();
2988 try {
2989 return pm.getPackageUid(app, 0 /* flags */);
2990 } catch (PackageManager.NameNotFoundException e) {
2991 return -1;
2992 } finally {
2993 Binder.restoreCallingIdentity(token);
2994 }
2995 }
2996
2997 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2998 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2999 if (getAppUid(packageName, user) != callingUid) {
3000 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
3001 }
3002 }
3003
Lorenzo Colitti23862912018-09-28 11:31:55 +09003004 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003005 * Ensure that a network route exists to deliver traffic to the specified
3006 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003007 * @param networkType the type of the network over which traffic to the
3008 * specified host is to be routed
3009 * @param hostAddress the IP address of the host to which the route is
3010 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003011 * @return {@code true} on success, {@code false} on failure
3012 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003013 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003014 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3015 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003016 if (disallowedBecauseSystemCaller()) {
3017 return false;
3018 }
paulhub2c28682021-08-18 18:35:54 +08003019 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003020 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003021 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003022 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003023 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003024
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003025 InetAddress addr;
3026 try {
3027 addr = InetAddress.getByAddress(hostAddress);
3028 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003029 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003030 return false;
3031 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003032
The Android Open Source Project28527d22009-03-03 19:31:44 -08003033 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003034 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003035 return false;
3036 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003037
3038 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3039 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003040 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003041 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3042 } else {
3043 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3044 }
3045 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003046 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003047
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003048 DetailedState netState;
3049 synchronized (nai) {
3050 netState = nai.networkInfo.getDetailedState();
3051 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003052
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003053 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003054 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003055 log("requestRouteToHostAddress on down network "
3056 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003057 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003058 }
3059 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003060 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003061
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003062 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003063 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003064 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003065 LinkProperties lp;
3066 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003067 synchronized (nai) {
3068 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003069 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003070 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003071 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003072 if (DBG) {
3073 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3074 }
Wink Saville32506bc2013-06-29 21:10:57 -07003075 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003076 } finally {
3077 Binder.restoreCallingIdentity(token);
3078 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003079 }
3080
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003081 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003082 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003083 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003084 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003085 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003086 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003087 if (bestRoute.getGateway().equals(addr)) {
3088 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003089 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003090 } else {
3091 // if we will connect to this through another route, add a direct route
3092 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003093 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003094 }
3095 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003096 if (DBG) log("Adding legacy route " + bestRoute +
3097 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003098
3099 final String dst = bestRoute.getDestinationLinkAddress().toString();
3100 final String nextHop = bestRoute.hasGateway()
3101 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003102 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003103 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3104 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003105 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003106 return false;
3107 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003108 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003109 }
3110
paulhu7c0a2e62021-01-08 00:51:49 +08003111 class DnsResolverUnsolicitedEventCallback extends
3112 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003113 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003114 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003115 try {
3116 mHandler.sendMessage(mHandler.obtainMessage(
3117 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003118 new PrivateDnsValidationUpdate(event.netId,
3119 InetAddresses.parseNumericAddress(event.ipAddress),
3120 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003121 } catch (IllegalArgumentException e) {
3122 loge("Error parsing ip address in validation event");
3123 }
3124 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003125
3126 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003127 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3128 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003129 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3130 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3131 // event callback for certain nai. e.g. cellular. Register here to pass to
3132 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003133 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003134 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3135 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003136 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003137 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003138 }
3139 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003140
3141 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003142 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3143 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3144 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003145 }
dalyk1720e542018-03-05 12:42:22 -05003146
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003147 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003148 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003149 return this.VERSION;
3150 }
3151
3152 @Override
3153 public String getInterfaceHash() {
3154 return this.HASH;
3155 }
paulhu7c0a2e62021-01-08 00:51:49 +08003156 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003157
3158 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003159 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3160 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003161
paulhu7c0a2e62021-01-08 00:51:49 +08003162 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003163 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003164 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003165 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003166 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003167 }
3168 }
3169
Sudheer Shanka9967d462021-03-18 19:09:25 +00003170 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003171 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003172 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003173 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3174 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003175 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003176 };
3177
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003178 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003179 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003180 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003181 }
3182
Mark Fasheh7c999d82023-05-04 20:23:11 +00003183 static final class UidFrozenStateChangedArgs {
3184 final int[] mUids;
3185 final int[] mFrozenStates;
3186
3187 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3188 mUids = uids;
3189 mFrozenStates = frozenStates;
3190 }
3191 }
3192
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003193 /**
3194 * Check if the cell network is idle.
3195 * @return true if the cell network state is idle
3196 * false if the cell network state is active or unknown
3197 */
3198 private boolean isCellNetworkIdle() {
3199 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3200 if (defaultNai == null
3201 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3202 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3203 // cell network is not the default network, cell network state is unknown.
3204 // TODO(b/279380356): Track cell network state when the cell is not the default network
3205 return false;
3206 }
3207
3208 return !mNetworkActivityTracker.isDefaultNetworkActive();
3209 }
3210
Mark Fasheh7c999d82023-05-04 20:23:11 +00003211 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003212 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003213
3214 for (int i = 0; i < uids.length; i++) {
3215 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003216 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003217 } else {
3218 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003219 }
3220 }
3221
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003222 if (ownerUids.isEmpty()) {
3223 return;
3224 }
3225
3226 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3227 // Delay closing sockets to avoid waking the cell modem up.
3228 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3229 // than waking cell modem up.
3230 mPendingFrozenUids.addAll(ownerUids);
3231 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003232 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003233 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003234 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003235 loge("Exception in socket destroy: " + e);
3236 }
3237 }
3238 }
3239
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003240 private void closePendingFrozenSockets() {
3241 ensureRunningOnConnectivityServiceThread();
3242
3243 try {
3244 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3245 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3246 loge("Failed to close pending frozen app sockets: " + e);
3247 }
3248 mPendingFrozenUids.clear();
3249 }
3250
3251 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3252 mNetworkActivityTracker.handleReportNetworkActivity(params);
3253
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003254 final boolean isCellNetworkActivity;
3255 if (mTrackMultiNetworkActivities) {
3256 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3257 // nai could be null if netd receives a netlink message and calls the network
3258 // activity change callback after the network is unregistered from ConnectivityService.
3259 isCellNetworkActivity = nai != null
3260 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3261 } else {
3262 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3263 }
3264
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003265 if (mDelayDestroyFrozenSockets
3266 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003267 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003268 && !mPendingFrozenUids.isEmpty()) {
3269 closePendingFrozenSockets();
3270 }
3271 }
3272
3273 /**
3274 * If the cellular network is no longer the default network, close pending frozen sockets.
3275 *
3276 * @param newNetwork new default network
3277 * @param oldNetwork old default network
3278 */
3279 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3280 NetworkAgentInfo oldNetwork) {
3281 final boolean isOldNetworkCellular = oldNetwork != null
3282 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3283 final boolean isNewNetworkCellular = newNetwork != null
3284 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3285
3286 if (isOldNetworkCellular
3287 && !isNewNetworkCellular
3288 && !mPendingFrozenUids.isEmpty()) {
3289 closePendingFrozenSockets();
3290 }
3291 }
3292
3293 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3294 pw.println("CloseFrozenAppSockets:");
3295 pw.increaseIndent();
3296 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3297 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3298 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3299 pw.decreaseIndent();
3300 }
3301
Junyu Lai155760b2023-10-05 14:51:00 +08003302 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3303 pw.println("Bpf Program Status:");
3304 pw.increaseIndent();
3305 try {
3306 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003307 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003308 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003309 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003310 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003311 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003312 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003313 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003314 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003315 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003316 } catch (IOException e) {
3317 pw.println(" IOException");
3318 }
3319 pw.decreaseIndent();
3320 }
3321
Mark Fasheh7c999d82023-05-04 20:23:11 +00003322 @VisibleForTesting
3323 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003324 @VisibleForTesting
3325 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3326 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003327
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003328 @VisibleForTesting
3329 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3330 "allow_sysui_connectivity_reports";
3331
Paul Jensen83f5d572014-08-29 09:54:01 -04003332 private void enforceInternetPermission() {
3333 mContext.enforceCallingOrSelfPermission(
3334 android.Manifest.permission.INTERNET,
3335 "ConnectivityService");
3336 }
3337
The Android Open Source Project28527d22009-03-03 19:31:44 -08003338 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003339 mContext.enforceCallingOrSelfPermission(
3340 android.Manifest.permission.ACCESS_NETWORK_STATE,
3341 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003342 }
3343
lucaslinc582d502022-01-27 09:07:00 +08003344 private boolean checkAccessPermission(int pid, int uid) {
3345 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3346 == PERMISSION_GRANTED;
3347 }
3348
paulhua6ee2122021-02-22 15:40:43 +08003349 /**
3350 * Performs a strict and comprehensive check of whether a calling package is allowed to
3351 * change the state of network, as the condition differs for pre-M, M+, and
3352 * privileged/preinstalled apps. The caller is expected to have either the
3353 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3354 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3355 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3356 * permission and cannot be revoked. See http://b/23597341
3357 *
3358 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3359 * of this app will be updated to the current time.
3360 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003361 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003362 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3363 == PackageManager.PERMISSION_GRANTED) {
3364 return;
3365 }
3366
3367 if (callingPkg == null) {
3368 throw new SecurityException("Calling package name is null.");
3369 }
3370
3371 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3372 final int uid = mDeps.getCallingUid();
3373 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3374 callingPkg, callingAttributionTag, null /* message */);
3375
3376 if (mode == AppOpsManager.MODE_ALLOWED) {
3377 return;
3378 }
3379
3380 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3381 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3382 return;
3383 }
3384
3385 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3386 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3387 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003388 }
3389
Charles He9369e612017-05-15 17:07:18 +01003390 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003391 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003392 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003393 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003394 }
3395
Quang Luong98858d62023-02-11 00:25:24 +00003396 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003397 enforceAnyPermissionOf(mContext,
3398 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003399 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003400 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3401 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3402 }
3403
paulhu8e96a752019-08-12 16:25:11 +08003404 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003405 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003406 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003407 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003408 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003409 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003410 }
3411
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003412 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003413 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003414 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003415 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003416 android.Manifest.permission.NETWORK_SETTINGS,
3417 android.Manifest.permission.NETWORK_FACTORY,
3418 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3419 }
3420
3421 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003422 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003423 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003424 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003425 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3426 android.Manifest.permission.NETWORK_FACTORY,
3427 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3428 }
3429
lucaslin69e1aa92022-03-22 18:15:09 +08003430 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3431 return PERMISSION_GRANTED == mContext.checkPermission(
3432 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3433 || PERMISSION_GRANTED == mContext.checkPermission(
3434 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3435 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003436 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003437 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003438 }
3439
Chalard Jean9a396cc2018-02-21 18:43:54 +09003440 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003441 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003442 android.Manifest.permission.NETWORK_SETTINGS,
3443 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003444 }
3445
3446 private boolean checkSettingsPermission(int pid, int uid) {
3447 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003448 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3449 || PERMISSION_GRANTED == mContext.checkPermission(
3450 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003451 }
3452
paulhu8e96a752019-08-12 16:25:11 +08003453 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003454 enforceNetworkStackPermissionOr(mContext,
3455 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003456 }
3457
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003458 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003459 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003460 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003461 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003462 }
3463
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003464 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003465 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003466 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3467 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003468 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003469 }
3470
James Mattis8378aec2021-01-26 14:05:36 -08003471 private void enforceOemNetworkPreferencesPermission() {
3472 mContext.enforceCallingOrSelfPermission(
3473 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3474 "ConnectivityService");
3475 }
3476
James Mattisfa270db2021-05-31 17:11:10 -07003477 private void enforceManageTestNetworksPermission() {
3478 mContext.enforceCallingOrSelfPermission(
3479 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3480 "ConnectivityService");
3481 }
3482
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003483 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003484 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003485 android.Manifest.permission.NETWORK_STACK,
3486 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003487 }
3488
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003489 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003490 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003491 android.Manifest.permission.NETWORK_STACK,
3492 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3493 }
3494
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003495 private boolean checkSystemBarServicePermission(int pid, int uid) {
3496 return checkAnyPermissionOf(mContext, pid, uid,
3497 android.Manifest.permission.STATUS_BAR_SERVICE);
3498 }
3499
paulhu1a407652019-03-22 16:35:06 +08003500 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003501 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003502 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003503 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3504 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003505 }
3506
Paul Hu8fc2a552022-05-04 18:44:42 +08003507 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3508 boolean checkUidsAllowedList) {
3509 if (PermissionUtils.checkAnyPermissionOf(mContext,
3510 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3511 return true;
3512 }
3513
3514 // fallback to ConnectivityInternalPermission
3515 // TODO: Remove this fallback check after all apps have declared
3516 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3517 if (PermissionUtils.checkAnyPermissionOf(mContext,
3518 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3519 return true;
3520 }
3521
3522 // Check whether uid is in allowed on restricted networks list.
3523 if (checkUidsAllowedList
3524 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3525 return true;
3526 }
3527 return false;
3528 }
3529
3530 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3531 final int callingUid = mDeps.getCallingUid();
3532 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3533 throw new SecurityException("ConnectivityService: user " + callingUid
3534 + " has no permission to access restricted network.");
3535 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003536 }
3537
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003538 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003539 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003540 }
3541
Roshan Pius98f59ec2021-02-23 08:47:39 -08003542 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3543 return PERMISSION_GRANTED == mContext.checkPermission(
3544 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3545 }
3546
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003547 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003548 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003549 }
3550
3551 private void sendInetConditionBroadcast(NetworkInfo info) {
3552 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3553 }
3554
Wink Saville4f0de1e2011-08-04 15:01:58 -07003555 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003556 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003557 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003558 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003559 if (info.isFailover()) {
3560 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3561 info.setFailover(false);
3562 }
3563 if (info.getReason() != null) {
3564 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3565 }
3566 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003567 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3568 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003569 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003570 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003571 return intent;
3572 }
3573
3574 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3575 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3576 }
3577
Michael Groover73f69482023-01-27 11:01:25 -06003578 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3579 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003580 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3581 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003582 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003583 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003584 if (!mSystemReady
3585 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003586 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003587 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003588 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003589 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003590 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003591 }
3592
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003593 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003594 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003595 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003596 final NetworkInfo ni = intent.getParcelableExtra(
3597 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003598 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3599 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003600 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003601 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003602 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003603 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003604 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003605 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003606 } finally {
3607 Binder.restoreCallingIdentity(ident);
3608 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003609 }
3610 }
3611
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003612 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3613 NetworkInfo info) {
3614 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003615 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003616
3617 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3618 try {
3619 // This allows us to discard older broadcasts still waiting to be delivered
3620 // which have the same namespace and key.
3621 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3622 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3623 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003624 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003625 } catch (UnsupportedApiLevelException e) {
3626 Log.wtf(TAG, "Using unsupported API" + e);
3627 }
3628 }
3629
3630 @VisibleForTesting
3631 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3632 final StringBuilder sb = new StringBuilder();
3633 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3634 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3635 sb.append(info.getExtraInfo());
3636 return sb.toString();
3637 }
3638
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003639 /**
Aaron Huang96011892020-06-27 07:18:23 +08003640 * Called by SystemServer through ConnectivityManager when the system is ready.
3641 */
3642 @Override
3643 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003644 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003645 throw new SecurityException("Calling Uid is not system uid.");
3646 }
3647 systemReadyInternal();
3648 }
3649
3650 /**
3651 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003652 */
3653 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003654 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003655 // Load flags after PackageManager is ready to query module version
3656 mFlags.loadFlags(mDeps, mContext);
3657
Aaron Huang9a57acf2020-12-08 10:03:29 +08003658 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3659 // listening network request which is sent by MultipathPolicyTracker won't be added
3660 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3661 // be called after PermissionMonitor#startMonitoring().
3662 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3663 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3664 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003665 final ConditionVariable startMonitoringDone = new ConditionVariable();
3666 mHandler.post(() -> {
3667 mPermissionMonitor.startMonitoring();
3668 startMonitoringDone.open();
3669 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003670 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003671 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003672
Hugo Benichie5220992017-04-26 14:53:28 +09003673 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003674 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003675 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003676 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003677 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003678 }
3679 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003680
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003681 // Create network requests for always-on networks.
3682 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003683
3684 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003685 // Note that updating can be skipped here if the list is empty only because no uid
3686 // rules are applied before system ready. Normally, the empty uid list means to clear
3687 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003688 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3689 updateMobileDataPreferredUids();
3690 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003691
3692 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003693 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003694 mBpfNetMaps.setPullAtomCallback(mContext);
3695 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003696 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3697 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003698 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3699 // have permission problem. While CV#block() is unbounded in time and can in principle block
3700 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3701 // could have blocked forever too.
3702 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003703 }
3704
The Android Open Source Project28527d22009-03-03 19:31:44 -08003705 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003706 * Start listening for default data network activity state changes.
3707 */
3708 @Override
3709 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003710 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003711 }
3712
3713 /**
3714 * Stop listening for default data network activity state changes.
3715 */
3716 @Override
3717 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003718 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003719 }
3720
3721 /**
3722 * Check whether the default network radio is currently active.
3723 */
3724 @Override
3725 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003726 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003727 }
3728
3729 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003730 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003731 * and set it on it's iface.
3732 */
Junyu Lai970963e2022-10-25 15:46:47 +08003733 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003734 final String iface = newLp.getInterfaceName();
3735 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003736 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003737 // Silently ignore unset MTU value.
3738 return;
3739 }
Hansen Kurli04252032022-12-07 11:21:49 +00003740 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3741 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3742 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003743 return;
3744 }
Hansen Kurli04252032022-12-07 11:21:49 +00003745 // Cannot set MTU without interface name
3746 if (TextUtils.isEmpty(iface)) {
3747 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003748 return;
3749 }
sy.yun4aa73922013-09-02 05:24:09 +09003750
Hansen Kurli04252032022-12-07 11:21:49 +00003751 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3752 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003753 return;
3754 }
3755
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003756 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003757 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003758 mNetd.interfaceSetMtu(iface, mtu);
3759 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003760 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003761 }
3762 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003763
Chenbo Feng15416292018-11-08 17:36:21 -08003764 @VisibleForTesting
3765 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003766
Junyu Lai970963e2022-10-25 15:46:47 +08003767 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003768 String[] values = null;
3769 if (tcpBufferSizes != null) {
3770 values = tcpBufferSizes.split(",");
3771 }
3772
3773 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003774 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003775 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3776 values = tcpBufferSizes.split(",");
3777 }
3778
3779 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3780
3781 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003782 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003783
Chenbo Feng15416292018-11-08 17:36:21 -08003784 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3785 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3786 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003787 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003788 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003789 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003790 }
3791 }
3792
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003793 @Override
3794 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003795 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003796 NETWORK_RESTORE_DELAY_PROP_NAME);
3797 if(restoreDefaultNetworkDelayStr != null &&
3798 restoreDefaultNetworkDelayStr.length() != 0) {
3799 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003800 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003801 } catch (NumberFormatException e) {
3802 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003803 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003804 // if the system property isn't set, use the value for the apn type
3805 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3806
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003807 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3808 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003809 }
3810 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003811 }
3812
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003813 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003814 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003815 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003816 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003817 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003818 // Start gathering diagnostic information.
3819 netDiags.add(new NetworkDiagnostics(
3820 nai.network,
3821 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003822 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003823 DIAG_TIME_MS));
3824 }
3825
3826 for (NetworkDiagnostics netDiag : netDiags) {
3827 pw.println();
3828 netDiag.waitForMeasurements();
3829 netDiag.dump(pw);
3830 }
3831 }
3832
The Android Open Source Project28527d22009-03-03 19:31:44 -08003833 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003834 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3835 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003836 if (!checkDumpPermission(mContext, TAG, writer)) return;
3837
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003838 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003839 }
3840
lucaslin99473f62020-12-10 15:10:54 +08003841 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3842 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3843 != PackageManager.PERMISSION_GRANTED) {
3844 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003845 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003846 + " due to missing android.permission.DUMP permission");
3847 return false;
3848 } else {
3849 return true;
3850 }
3851 }
3852
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003853 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003854 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003855
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003856 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003857 dumpNetworkDiagnostics(pw);
3858 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003859 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003860 dumpNetworks(pw);
3861 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003862 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003863 dumpNetworkRequests(pw);
3864 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003865 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3866 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3867 dumpTrafficController(pw, fd, verbose);
3868 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003869 }
Erik Kline9647f382015-06-05 17:47:34 +09003870
Junyu Lai0da479b2022-04-20 15:06:29 +08003871 pw.println("NetworkProviders for:");
3872 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003873 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003874 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003875 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003876 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003877 pw.println();
3878
Chalard Jean5b409c72021-02-04 13:12:59 +09003879 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003880 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003881 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003882 pw.println("none");
3883 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003884 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003885 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003886 pw.println();
3887
James Mattis8b298a02021-06-01 22:34:04 -07003888 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003889 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003890 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003891 pw.decreaseIndent();
3892 pw.println();
3893
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003894 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003895 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003896 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003897 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003898 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003899
junyulaif2c67e42018-08-07 19:50:45 +08003900 pw.println("Status for known UIDs:");
3901 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003902 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003903 for (int i = 0; i < size; i++) {
3904 // Don't crash if the array is modified while dumping in bugreports.
3905 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003906 final int uid = mUidBlockedReasons.keyAt(i);
3907 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3908 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003909 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003910 } catch (ArrayIndexOutOfBoundsException e) {
3911 pw.println(" ArrayIndexOutOfBoundsException");
3912 } catch (ConcurrentModificationException e) {
3913 pw.println(" ConcurrentModificationException");
3914 }
3915 }
3916 pw.println();
3917 pw.decreaseIndent();
3918
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003919 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003920 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003921 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003922 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003923 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003924
Junyu Lai0da479b2022-04-20 15:06:29 +08003925 pw.println("Network Offers:");
3926 pw.increaseIndent();
3927 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3928 pw.println(offerInfo.offer);
3929 }
3930 pw.decreaseIndent();
3931 pw.println();
3932
Robert Greenwalt94e22142014-07-30 16:31:24 -07003933 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003934
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003935 pw.println();
markchien5e866652019-09-30 14:40:57 +08003936 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003937
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003938 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003939 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003940
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003941 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003942 dumpCloseFrozenAppSockets(pw);
3943
3944 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003945 dumpBpfProgramStatus(pw);
3946
3947 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003948
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003949 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003950 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003951 pw.println("mNetworkRequestInfoLogs (most recent first):");
3952 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003953 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003954 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003955
3956 pw.println();
3957 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3958 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003959 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003960 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003961
3962 pw.println();
3963 pw.println("NetTransition WakeLock activity (most recent first):");
3964 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003965 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3966 pw.println("total releases: " + mTotalWakelockReleases);
3967 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3968 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3969 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3970 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3971 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3972 }
James Mattiscb1e0362021-04-06 17:07:42 -07003973 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003974
3975 pw.println();
3976 pw.println("bandwidth update requests (by uid):");
3977 pw.increaseIndent();
3978 synchronized (mBandwidthRequests) {
3979 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3980 pw.println("[" + mBandwidthRequests.keyAt(i)
3981 + "]: " + mBandwidthRequests.valueAt(i));
3982 }
3983 }
3984 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003985 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003986
James Mattiscb1e0362021-04-06 17:07:42 -07003987 pw.println();
3988 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3989 pw.increaseIndent();
3990 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003991 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003992 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003993
3994 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003995
3996 pw.println();
3997 pw.println("Permission Monitor:");
3998 pw.increaseIndent();
3999 mPermissionMonitor.dump(pw);
4000 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004001
4002 pw.println();
4003 pw.println("Legacy network activity:");
4004 pw.increaseIndent();
4005 mNetworkActivityTracker.dump(pw);
4006 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08004007 }
4008
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004009 private void dumpNetworks(IndentingPrintWriter pw) {
4010 for (NetworkAgentInfo nai : networksSortedById()) {
4011 pw.println(nai.toString());
4012 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004013 pw.println("Nat464Xlat:");
4014 pw.increaseIndent();
4015 nai.dumpNat464Xlat(pw);
4016 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004017 pw.println(String.format(
4018 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4019 nai.numForegroundNetworkRequests(),
4020 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4021 nai.numBackgroundNetworkRequests(),
4022 nai.numNetworkRequests()));
4023 pw.increaseIndent();
4024 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4025 pw.println(nai.requestAt(i).toString());
4026 }
4027 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004028 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004029 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004030 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004031 pw.decreaseIndent();
4032 pw.decreaseIndent();
4033 }
4034 }
4035
James Mattis8b298a02021-06-01 22:34:04 -07004036 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4037 if (!mProfileNetworkPreferences.isEmpty()) {
4038 pw.println("Profile preferences:");
4039 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004040 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004041 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004042 }
James Mattis8b298a02021-06-01 22:34:04 -07004043 if (!mOemNetworkPreferences.isEmpty()) {
4044 pw.println("OEM preferences:");
4045 pw.increaseIndent();
4046 pw.println(mOemNetworkPreferences);
4047 pw.decreaseIndent();
4048 }
4049 if (!mMobileDataPreferredUids.isEmpty()) {
4050 pw.println("Mobile data preferred UIDs:");
4051 pw.increaseIndent();
4052 pw.println(mMobileDataPreferredUids);
4053 pw.decreaseIndent();
4054 }
James Mattis45d81842021-01-10 14:24:24 -08004055
James Mattis8b298a02021-06-01 22:34:04 -07004056 pw.println("Default requests:");
4057 pw.increaseIndent();
4058 dumpPerAppDefaultRequests(pw);
4059 pw.decreaseIndent();
4060 }
4061
4062 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004063 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4064 if (mDefaultRequest == defaultRequest) {
4065 continue;
4066 }
4067
James Mattis8b298a02021-06-01 22:34:04 -07004068 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4069 final String networkOutput;
4070 if (null == satisfier) {
4071 networkOutput = "null";
4072 } else if (mNoServiceNetwork.equals(satisfier)) {
4073 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004074 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004075 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004076 }
James Mattis8b298a02021-06-01 22:34:04 -07004077 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4078 ? "" : " asUid: " + defaultRequest.mAsUid;
4079 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4080 + defaultRequest.mPid + asUidString + "]";
4081 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4082 + " Preference order: " + defaultRequest.mPreferenceOrder
4083 + " Tracked UIDs: " + defaultRequest.getUids();
4084 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004085 }
4086 }
4087
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004088 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004089 NetworkRequestInfo[] infos = null;
4090 while (infos == null) {
4091 try {
4092 infos = requestsSortedById();
4093 } catch (ConcurrentModificationException e) {
4094 // mNetworkRequests should only be accessed from handler thread, except dump().
4095 // As dump() is never called in normal usage, it would be needlessly expensive
4096 // to lock the collection only for its benefit. Instead, retry getting the
4097 // requests if ConcurrentModificationException is thrown during dump().
4098 }
4099 }
4100 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004101 pw.println(nri.toString());
4102 }
4103 }
4104
Ken Chene6d511f2022-01-25 11:10:42 +08004105 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4106 boolean verbose) {
4107 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004108 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004109 } catch (ServiceSpecificException e) {
4110 pw.println(e.getMessage());
4111 } catch (IOException e) {
4112 loge("Dump BPF maps failed, " + e);
4113 }
4114 }
4115
Chalard Jean524f0b12021-10-25 21:11:56 +09004116 private void dumpAllRequestInfoLogsToLogcat() {
4117 try (PrintWriter logPw = new PrintWriter(new Writer() {
4118 @Override
4119 public void write(final char[] cbuf, final int off, final int len) {
4120 // This method is called with 0-length and 1-length arrays for empty strings
4121 // or strings containing only the DEL character.
4122 if (len <= 1) return;
4123 Log.e(TAG, new String(cbuf, off, len));
4124 }
4125 @Override public void flush() {}
4126 @Override public void close() {}
4127 })) {
4128 mNetworkRequestInfoLogs.dump(logPw);
4129 }
4130 }
4131
Hugo Benichia480ba52018-09-03 08:19:02 +09004132 /**
4133 * Return an array of all current NetworkAgentInfos sorted by network id.
4134 */
4135 private NetworkAgentInfo[] networksSortedById() {
4136 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004137 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004138 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004139 return networks;
4140 }
4141
4142 /**
4143 * Return an array of all current NetworkRequest sorted by request id.
4144 */
James Mattis258ea3c2020-11-15 15:04:40 -08004145 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004146 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004147 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004148 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004149 // Sort the array based off the NRI containing the min requestId in its requests.
4150 Arrays.sort(requests,
4151 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4152 Comparator.comparingInt(req -> req.requestId)).requestId
4153 )
4154 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004155 return requests;
4156 }
4157
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004158 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004159 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004160 if (officialNai != null && officialNai.equals(nai)) return true;
4161 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004162 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004163 " - " + nai);
4164 }
4165 return false;
4166 }
4167
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004168 private boolean isDisconnectRequest(Message msg) {
4169 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4170 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4171 return info.getState() == NetworkInfo.State.DISCONNECTED;
4172 }
4173
Robert Greenwalt2034b912009-08-12 16:08:25 -07004174 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004175 private class NetworkStateTrackerHandler extends Handler {
4176 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004177 super(looper);
4178 }
4179
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004180 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004181 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4182 final NetworkAgentInfo nai = arg.first;
4183 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004184 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004185 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004186 }
4187 return;
4188 }
4189
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004190 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004191 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004192 return;
4193 }
4194
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004195 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004196 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004197 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4198 if (!nai.respectsNcStructuralConstraints(proposed)) {
4199 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4200 + nai.networkCapabilities + " -> " + proposed);
4201 disconnectAndDestroyNetwork(nai);
4202 return;
4203 }
4204 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004205 final NetworkCapabilities sanitized =
4206 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004207 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004208 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004209 break;
4210 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004211 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004212 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004213 processLinkPropertiesFromAgent(nai, newLp);
4214 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004215 break;
4216 }
4217 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004218 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004219 updateNetworkInfo(nai, info);
4220 break;
4221 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004222 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4223 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004224 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004225 break;
4226 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004227 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004228 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004229 break;
4230 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004231 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004232 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004233 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004234 // Note that if the NAI had been connected, this would affect the
4235 // score, and therefore would require re-mixing the score and performing
4236 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004237 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004238 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4239 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004240 // Mark the network as temporarily accepting partial connectivity so that it
4241 // will be validated (and possibly become default) even if it only provides
4242 // partial internet access. Note that if user connects to partial connectivity
4243 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4244 // out of wifi coverage) and if the same wifi is available again, the device
4245 // will auto connect to this wifi even though the wifi has "no internet".
4246 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004247 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004248 break;
4249 }
junyulai011b1f12019-01-03 18:50:15 +08004250 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004251 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004252 break;
4253 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004254 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004255 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004256 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004257
4258 if (isLegacyLockdownNai(nai)
4259 && (underlying == null || underlying.size() != 1)) {
4260 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4261 + " must have exactly one underlying network: " + underlying);
4262 }
4263
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004264 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4265 nai.declaredUnderlyingNetworks = (underlying != null)
4266 ? underlying.toArray(new Network[0]) : null;
4267
4268 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4269 if (DBG) {
4270 log(nai.toShortString() + " changed underlying networks to "
4271 + Arrays.toString(nai.declaredUnderlyingNetworks));
4272 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004273 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004274 notifyIfacesChangedForNetworkStats();
4275 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004276 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004277 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004278 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4279 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4280 nai.teardownDelayMs = msg.arg1;
4281 } else {
4282 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4283 }
Chalard Jean550b5212021-03-05 23:07:53 +09004284 break;
4285 }
4286 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4287 nai.setLingerDuration((int) arg.second);
4288 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004289 }
Tyler Wear72388212021-09-09 14:49:02 -07004290 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4291 DscpPolicy policy = (DscpPolicy) arg.second;
4292 if (mDscpPolicyTracker != null) {
4293 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4294 }
4295 break;
4296 }
4297 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4298 if (mDscpPolicyTracker != null) {
4299 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4300 }
4301 break;
4302 }
4303 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4304 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004305 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004306 }
4307 break;
4308 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004309 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004310 if (!nai.everConnected()) {
4311 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4312 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004313 teardownUnneededNetwork(nai);
4314 break;
4315 }
4316
4317 if (nai.isDestroyed()) {
4318 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4319 + ", ignoring");
4320 break;
4321 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004322
4323 final int timeoutMs = (int) arg.second;
4324 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4325 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4326 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4327 }
4328
4329 // Marking a network awaiting replacement is used to ensure that any requests
4330 // satisfied by the network do not switch to another network until a
4331 // replacement is available or the wait for a replacement times out.
4332 // If the network is inactive (i.e., nascent or lingering), then there are no
4333 // such requests, and there is no point keeping it. Just tear it down.
4334 // Note that setLingerDuration(0) cannot be used to do this because the network
4335 // could be nascent.
4336 nai.clearInactivityState();
4337 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4338 Log.d(TAG, nai.toShortString()
4339 + " marked awaiting replacement is unneeded, tearing down instead");
4340 teardownUnneededNetwork(nai);
4341 break;
4342 }
4343
4344 Log.d(TAG, "Marking " + nai.toShortString()
4345 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4346 destroyNativeNetwork(nai);
4347
4348 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4349 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4350 // consider the fact that the network could already have disconnected or been
4351 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4352 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4353 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4354 mKeepaliveTracker.handleStopAllKeepalives(nai,
4355 SocketKeepalive.ERROR_INVALID_NETWORK);
4356
4357 nai.updateScoreForNetworkAgentUpdate();
4358 // This rematch is almost certainly not going to result in any changes, because
4359 // the destroyed flag is only just above the "current satisfier wins"
4360 // tie-breaker. But technically anything that affects scoring should rematch.
4361 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004362 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004363 break;
4364 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004365 }
4366 }
4367
4368 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004369 final int netId = msg.arg2;
4370 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004371 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004372 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004373 switch (msg.what) {
4374 default:
4375 return false;
lucasline117e2e2019-10-22 18:27:33 +08004376 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004377 if (nai == null) {
4378 break;
4379 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004380 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4381 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004382 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004383 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004384 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004385 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004386 if (probePrivateDnsCompleted) {
4387 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4388 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004389 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004390 }
4391 // Only show the notification when the private DNS is broken and the
4392 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004393 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004394 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4395 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004396 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004397 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4398 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4399 // private DNS is broken, it means this network is being reevaluated.
4400 // Either probing private DNS is not necessary any more or it hasn't been
4401 // done yet. In either case, the networkCapabilities should be updated to
4402 // reflect the new status.
4403 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004404 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004405 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004406 }
4407 break;
4408 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004409 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004410 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4411
Erik Kline31b4a9e2018-01-11 21:07:29 +09004412 if (nai == null) break;
4413
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004414 handleNetworkTested(nai, results.mTestResult,
4415 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004416 break;
4417 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004418 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004419 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004420 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004421 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004422 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004423 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004424 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4425 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004426 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004427 if (nai == null) {
4428 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4429 break;
4430 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004431 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004432 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004433 (PendingIntent) msg.obj,
4434 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004435 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004436 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004437 break;
4438 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004439 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004440 if (nai == null) break;
4441
Erik Kline9a62f012018-03-21 07:18:33 -07004442 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004443 break;
4444 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004445 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004446 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004447 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004448 break;
4449 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004450 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004451 return true;
4452 }
4453
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004454 private void handleNetworkTested(
4455 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004456 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4457 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004458 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004459
4460 // If there is any kind of working networking, then the NAI has been evaluated
4461 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4462 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004463 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004464 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004465 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4466 // any callback that receives onAvailable for that rematch receives an extra caps
4467 // callback. To prevent that, update the score in the agent so the updates below won't
4468 // see an update to both caps and score at the same time.
4469 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004470 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4471
he_won.hwang881307a2022-03-15 21:23:52 +09004472 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4473 // Assume the validation failure is due to a temporary failure after roaming
4474 // and ignore it. NetworkMonitor will continue to retry validation. If it
4475 // continues to fail after the block timeout expires, the network will be
4476 // marked unvalidated. If it succeeds, then validation state will not change.
4477 return;
4478 }
4479
Chalard Jean254bd162022-08-25 13:04:51 +09004480 final boolean wasValidated = nai.isValidated();
4481 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004482 final boolean wasPortal = nai.captivePortalDetected();
4483 nai.setPartialConnectivity(partial);
4484 nai.setCaptivePortalDetected(portal);
4485 nai.updateScoreForNetworkAgentUpdate();
4486 final boolean partialConnectivityChanged = (wasPartial != partial);
4487 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004488
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004489 if (DBG) {
4490 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4491 ? " with redirect to " + redirectUrl
4492 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004493 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004494 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004495 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004496 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004497 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004498 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004499 if (valid) {
4500 handleFreshlyValidatedNetwork(nai);
4501 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4502 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004503 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004504 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004505 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004506 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004507 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004508 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004509 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004510 NotificationType.PRIVATE_DNS_BROKEN);
4511 // If network becomes valid, the hasShownBroken should be reset for
4512 // that network so that the notification will be fired when the private
4513 // DNS is broken again.
4514 nai.networkAgentConfig.hasShownBroken = false;
4515 }
4516 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004517 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004518 } else if (portalChanged) {
4519 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004520 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004521 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4522 nai.onPreventAutomaticReconnect();
4523 teardownUnneededNetwork(nai);
4524 return;
4525 } else {
4526 updateCapabilitiesForNetwork(nai);
4527 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004528 } else if (becameEvaluated) {
4529 // If valid or partial connectivity changed, updateCapabilities* has
4530 // done the rematch.
4531 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004532 }
4533 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004534
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004535 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004536 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004537 nai.onValidationStatusChanged(
4538 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4539 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004540
4541 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004542 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004543 // immediately. Re-notify partial connectivity silently if no internet
4544 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004545 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004546 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004547 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4548 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004549 }
4550
Chalard Jean254bd162022-08-25 13:04:51 +09004551 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004552 handleNetworkUnvalidated(nai);
4553 }
4554 }
4555
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004556 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4557 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4558 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4559 // Do not avoid captive portal when network is wear proxy.
4560 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4561 }
4562
Calvin Ondada1452016-10-11 15:10:46 -07004563 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004564 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4565 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004566 }
4567
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004568 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4569 switch (msg.what) {
4570 default:
4571 return false;
4572 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4573 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4574 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4575 handleLingerComplete(nai);
4576 }
4577 break;
4578 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004579 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4580 handleNetworkAgentRegistered(msg);
4581 break;
4582 }
4583 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4584 handleNetworkAgentDisconnected(msg);
4585 break;
4586 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004587 }
4588 return true;
4589 }
4590
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004591 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004592 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004593 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004594 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004595 maybeHandleNetworkAgentMessage(msg);
4596 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004597 }
4598 }
4599
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004600 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004601 private final int mNetId;
4602 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004603
4604 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004605 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004606 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004607 }
4608
4609 @Override
4610 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4611 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004612 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004613 }
4614
4615 @Override
4616 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004617 // Legacy version of notifyNetworkTestedWithExtras.
4618 // Would only be called if the system has a NetworkStack module older than the
4619 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004620 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004621 }
4622
4623 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004624 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004625 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4626 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004627 final Message msg = mTrackerHandler.obtainMessage(
4628 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004629 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004630 new NetworkTestedResults(
4631 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004632 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004633
4634 // Invoke ConnectivityReport generation for this Network test event.
4635 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4636 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004637
Cody Kestingf1120be2020-08-03 18:01:40 -07004638 // NetworkMonitor reports the network validation result as a bitmask while
4639 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4640 // logical value for ConnectivityDiagnostics.
4641 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4642 p.result);
4643
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004644 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004645 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004646 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4647 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4648
Aaron Huang959d3642021-01-21 15:47:41 +08004649 ConnectivityReportEvent reportEvent =
4650 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4651 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004652 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004653 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004654 }
4655
4656 @Override
4657 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4658 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4659 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004660 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004661 }
4662
4663 @Override
lucasline117e2e2019-10-22 18:27:33 +08004664 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4665 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4666 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004667 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004668 }
4669
4670 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004671 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4672 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4673 EVENT_CAPPORT_DATA_CHANGED,
4674 0, mNetId, data));
4675 }
4676
4677 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004678 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004679 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004680 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004681
4682 final PendingIntent pendingIntent;
4683 // Only the system server can register notifications with package "android"
4684 final long token = Binder.clearCallingIdentity();
4685 try {
paulhu7746e4e2020-06-09 19:07:03 +08004686 pendingIntent = PendingIntent.getBroadcast(
4687 mContext,
4688 0 /* requestCode */,
4689 intent,
4690 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004691 } finally {
4692 Binder.restoreCallingIdentity(token);
4693 }
4694 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4695 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004696 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004697 }
4698
4699 @Override
4700 public void hideProvisioningNotification() {
4701 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004702 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004703 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004704
4705 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004706 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004707 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004708 }
4709
4710 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004711 public int getInterfaceVersion() {
4712 return this.VERSION;
4713 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004714
4715 @Override
4716 public String getInterfaceHash() {
4717 return this.HASH;
4718 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004719 }
4720
Cody Kestingf1120be2020-08-03 18:01:40 -07004721 /**
4722 * Converts the given NetworkMonitor-specific validation result bitmask to a
4723 * ConnectivityDiagnostics-specific validation result int.
4724 */
4725 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4726 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4727 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4728 }
4729 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4730 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4731 }
4732 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4733 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4734 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4735 }
4736
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004737 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004738 log("Data stall detected with methods: " + p.detectionMethod);
4739
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004740 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004741 int detectionMethod = 0;
4742 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4743 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4744 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4745 }
4746 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4747 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4748 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4749 p.tcpMetricsCollectionPeriodMillis);
4750 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004751 }
4752
Cody Kestingf53a0752020-04-15 12:33:28 -07004753 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004754 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004755 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004756
4757 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4758 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4759 // the cost of going through two handlers.
4760 mConnectivityDiagnosticsHandler.sendMessage(msg);
4761 }
4762
Cody Kestingb37958e2020-05-15 10:36:01 -07004763 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4764 return (p.detectionMethod & detectionMethod) != 0;
4765 }
4766
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004767 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4768 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004769 }
4770
Erik Klinea73af002018-06-26 18:53:43 +09004771 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4772 if (nai == null) return;
4773 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4774 // in order to restart a validation pass from within netd.
4775 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4776 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004777 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004778 }
4779 }
4780
Erik Kline31b4a9e2018-01-11 21:07:29 +09004781 private void handlePrivateDnsSettingsChanged() {
4782 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4783
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004784 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004785 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004786 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004787 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4788 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004789 }
4790 }
4791
Erik Kline9a62f012018-03-21 07:18:33 -07004792 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4793 // Private DNS only ever applies to networks that might provide
4794 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004795 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004796
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004797 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004798 // schedule DNS resolutions. If a DNS resolution is required the
4799 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004800 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004801
4802 // With Private DNS bypass support, we can proceed to update the
4803 // Private DNS config immediately, even if we're in strict mode
4804 // and have not yet resolved the provider name into a set of IPs.
4805 updatePrivateDns(nai, cfg);
4806 }
4807
4808 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4809 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004810 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004811 }
4812
dalyk1720e542018-03-05 12:42:22 -05004813 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4814 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4815 if (nai == null) {
4816 return;
4817 }
4818 mDnsManager.updatePrivateDnsValidation(update);
4819 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4820 }
4821
paulhu7c0a2e62021-01-08 00:51:49 +08004822 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004823 int prefixLength) {
4824 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4825 if (nai == null) return;
4826
paulhu7c0a2e62021-01-08 00:51:49 +08004827 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4828 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004829
4830 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004831 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004832 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004833 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004834 prefixLength);
4835 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004836 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004837 return;
4838 }
4839 }
4840
Lorenzo Colittid523d142020-04-01 20:16:30 +09004841 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004842 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4843 }
4844
Hai Shalome58bdc62021-01-11 18:45:34 -08004845 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004846 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004847 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004848 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4849 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4850 }
4851
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004852 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004853 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004854 * @param nai the agent info to update
4855 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004856 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004857 */
junyulai2b6f0c22021-02-03 20:15:30 +08004858 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4859 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4860 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004861 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004862 // one lingered request, set inactive.
4863 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004864 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004865 if (DBG) log("Unsetting inactive " + nai.toShortString());
4866 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004867 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004868 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004869 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004870 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4871 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004872 }
junyulai2b6f0c22021-02-03 20:15:30 +08004873 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004874 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004875 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004876 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004877 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004878 }
4879
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004880 private void handleNetworkAgentRegistered(Message msg) {
4881 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4882 if (!mNetworkAgentInfos.contains(nai)) {
4883 return;
4884 }
4885
4886 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4887 if (VDBG) log("NetworkAgent registered");
4888 } else {
4889 loge("Error connecting NetworkAgent");
4890 mNetworkAgentInfos.remove(nai);
4891 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004892 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004893 synchronized (mNetworkForNetId) {
4894 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004895 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004896 mNetIdManager.releaseNetId(nai.network.getNetId());
4897 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004898 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004899 }
4900 }
4901 }
Paul Jensend5f53392014-11-25 15:26:53 -05004902
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004903 @VisibleForTesting
4904 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004905 // The feature of creating the networks immediately was slated for U, but race conditions
4906 // detected late required this was flagged off.
4907 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4908 // in NetworkAgentTest.
4909 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004910 }
4911
4912 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4913 @NonNull NetworkInfo.State state) {
4914 if (nai.isCreated()) return false;
4915 if (state == NetworkInfo.State.CONNECTED) return true;
4916 if (state != NetworkInfo.State.CONNECTING) {
4917 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004918 if (shouldCreateNetworksImmediately()) {
4919 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4920 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004921 return false;
4922 }
4923 return nai.isVPN() || shouldCreateNetworksImmediately();
4924 }
4925
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004926 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004927 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004928 }
4929
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004930 @VisibleForTesting
4931 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004932 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004933 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004934
4935 // If the network never roamed, return false. The check below is not sufficient if time
4936 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4937 if (nai.lastRoamTime == 0) return false;
4938
he_won.hwang881307a2022-03-15 21:23:52 +09004939 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4940 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004941 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004942 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004943 final long currentTimeMs = SystemClock.elapsedRealtime();
4944 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004945 if (timeSinceLastRoam <= blockTimeOut) {
4946 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4947 return true;
4948 }
4949 }
4950 return false;
4951 }
4952
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004953 private void handleNetworkAgentDisconnected(Message msg) {
4954 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004955 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004956 }
4957
Chalard Jeand9fffc32018-05-11 20:19:20 +09004958 // Destroys a network, remove references to it from the internal state managed by
4959 // ConnectivityService, free its interfaces and clean up.
4960 // Must be called on the Handler thread.
4961 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004962 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004963
4964 if (!mNetworkAgentInfos.contains(nai)) return;
4965
Chalard Jeand9fffc32018-05-11 20:19:20 +09004966 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004967 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004968 }
lucaslinb25c9a62019-02-12 15:30:13 +08004969 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004970 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004971 // A network agent has disconnected.
4972 // TODO - if we move the logic to the network agent (have them disconnect
4973 // because they lost all their requests or because their score isn't good)
4974 // then they would disconnect organically, report their new state and then
4975 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004976 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004977 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4978 null, null);
4979 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004980 final boolean wasDefault = isDefaultNetwork(nai);
4981 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004982 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004983 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09004984 if (mTrackMultiNetworkActivities) {
4985 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
4986 // the network becomes no longer the default network.
4987 mNetworkActivityTracker.removeDataActivityTracking(nai);
4988 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004989 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09004990 // If this was a local network forwarded to some upstream, or if some local network was
4991 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09004992 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09004993 // If this is a local network with an upstream selector, remove the associated network
4994 // request.
4995 if (nai.isLocalNetwork()) {
4996 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
4997 if (null != selector) {
4998 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
4999 }
5000 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005001 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5002 // by other networks that are already connected. Perhaps that can be done by
5003 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5004 // of rematchAllNetworksAndRequests
5005 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005006 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005007
5008 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005009 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5010 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005011 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005012 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005013 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005014 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005015 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005016 synchronized (mNetworkForNetId) {
5017 // Remove the NetworkAgent, but don't mark the netId as
5018 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005019 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005020 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005021 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005022 // Update allowed network lists in netd. This should be called after removing nai
5023 // from mNetworkAgentInfos.
5024 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005025 // Remove all previously satisfied requests.
5026 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005027 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005028 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005029 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005030 if (currentNetwork != null
5031 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005032 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005033 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5034 // rematch not to keep disconnected agents instead of setting it here ; this
5035 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005036 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005037 for (final NetworkOfferInfo noi : mNetworkOffers) {
5038 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005039 }
James Mattise3ef1912020-12-20 11:09:58 -08005040
Chalard Jean5b409c72021-02-04 13:12:59 +09005041 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005042 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005043 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005044 ensureNetworkTransitionWakelock(nai.toShortString());
5045 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005046 }
5047 }
junyulai2b6f0c22021-02-03 20:15:30 +08005048 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005049 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005050 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005051 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005052 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005053 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005054 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005055
Aaron Huang9fe47be2021-06-08 13:11:45 +08005056 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5057 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5058 // not called by the rematch in this case. This is because the code above unset
5059 // this network from the default request's satisfier, and that is what the rematch
5060 // is using as its source data to know what the old satisfier was. So as far as the
5061 // rematch above is concerned, the old default network was null.
5062 // Therefore if there is no new default, the default network was null and is still
5063 // null, thus there was no change so makeDefault() is not called. So if the old
5064 // network had a proxy and there is no new default, the proxy tracker should be told
5065 // that there is no longer a default proxy.
5066 // Strictly speaking this is not essential because having a proxy setting when
5067 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5068 mProxyTracker.setDefaultProxy(null);
5069 }
5070
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005071 // Immediate teardown.
5072 if (nai.teardownDelayMs == 0) {
5073 destroyNetwork(nai);
5074 return;
5075 }
5076
5077 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005078 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305079 try {
5080 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5081 } catch (RemoteException e) {
5082 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5083 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005084 }
5085 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5086 }
5087
5088 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005089 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005090 // Tell netd to clean up the configuration for this network
5091 // (routing rules, DNS, etc).
5092 // This may be slow as it requires a lot of netd shelling out to ip and
5093 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005094 // after we've rematched networks with requests (which might change the default
5095 // network or service a new request from an app), so network traffic isn't interrupted
5096 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005097 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005098 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005099 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005100 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5101 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5102 // false if the network was never created.
5103 // TODO: delete when S is no longer supported.
5104 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005105 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005106 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005107 }
5108
Chalard Jean1e4c2182023-10-06 18:45:53 +09005109 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005110 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005111 // Step 1 : maybe this network was the upstream for one or more local networks.
5112 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5113 if (!local.isLocalNetwork()) continue;
5114 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5115 if (null == selector) continue;
5116 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5117 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5118 // called after removing all associated NRIs from mNetworkRequests.
5119 if (null == nri) continue;
5120 final NetworkAgentInfo satisfier = nri.getSatisfier();
5121 if (disconnecting != satisfier) continue;
5122 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005123 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5124 // correctly contains null as an upstream.
5125 if (sendCallbacks) {
5126 nri.setSatisfier(null, null);
5127 notifyNetworkCallbacks(local,
5128 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5129 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005130 }
5131
5132 // Step 2 : maybe this is a local network that had an upstream.
5133 if (!disconnecting.isLocalNetwork()) return;
5134 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5135 if (null == selector) return;
5136 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5137 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5138 // is called after removing all associated NRIs from mNetworkRequests.
5139 if (null == nri) return;
5140 final NetworkAgentInfo satisfier = nri.getSatisfier();
5141 if (null == satisfier) return;
5142 removeLocalNetworkUpstream(disconnecting, satisfier);
5143 }
5144
5145 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5146 @NonNull final NetworkAgentInfo upstream) {
5147 try {
5148 mRoutingCoordinatorService.removeInterfaceForward(
5149 localAgent.linkProperties.getInterfaceName(),
5150 upstream.linkProperties.getInterfaceName());
5151 } catch (RemoteException e) {
5152 loge("Couldn't remove interface forward for "
5153 + localAgent.linkProperties.getInterfaceName() + " to "
5154 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5155 }
5156 }
5157
Ken Chen6df7a902021-04-09 15:08:42 +08005158 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005159 try {
5160 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005161 final NativeNetworkConfig config;
5162 if (nai.isVPN()) {
5163 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005164 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005165 return false;
5166 }
5167 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5168 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005169 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005170 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005171 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005172 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005173 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5174 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005175 getNetworkPermission(nai.networkCapabilities),
5176 false /* secure */,
5177 VpnManager.TYPE_VPN_NONE,
5178 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005179 }
Ken Chen6df7a902021-04-09 15:08:42 +08005180 mNetd.networkCreate(config);
5181 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005182 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5183 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005184 return true;
5185 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005186 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005187 return false;
5188 }
5189 }
5190
Ken Chen6df7a902021-04-09 15:08:42 +08005191 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005192 if (mDscpPolicyTracker != null) {
5193 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5194 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005195 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005196 // the interface is going to go away. Don't send the callbacks however ; if the network
5197 // was is being disconnected the callbacks have already been sent, and if it is being
5198 // destroyed pending replacement they will be sent when it is disconnected.
5199 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005200 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005201 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005202 } catch (RemoteException | ServiceSpecificException e) {
5203 loge("Exception destroying network(networkDestroy): " + e);
5204 }
5205 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005206 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005207 } catch (RemoteException | ServiceSpecificException e) {
5208 loge("Exception destroying network: " + e);
5209 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005210 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5211 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5212 // gets created, could add data to DnsManager data structures that will never get deleted.
5213 mDnsManager.removeNetwork(nai.network);
5214
5215 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005216 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005217 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5218 }
5219
Chalard Jean254bd162022-08-25 13:04:51 +09005220 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005221 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005222 }
5223
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005224 // If this method proves to be too slow then we can maintain a separate
5225 // pendingIntent => NetworkRequestInfo map.
5226 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5227 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005228 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5229 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5230 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005231 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005232 return entry.getValue();
5233 }
5234 }
5235 return null;
5236 }
5237
Chalard Jean524f0b12021-10-25 21:11:56 +09005238 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005239 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005240 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5241 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5242 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5243 // bug is fixed.
5244 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005245 throw new IllegalStateException("This NRI is already registered. New : " + nri
5246 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005247 }
5248 }
5249 }
5250 }
5251
Chalard Jeanac9ace02022-01-26 16:54:05 +09005252 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5253 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005254 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005255 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5256 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005257 }
5258 return false;
5259 }
5260
James Mattisf7027322020-12-13 16:28:14 -08005261 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005262 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005263 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5264 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5265 final NetworkRequestInfo existingRequest =
5266 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005267 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005268 if (DBG) {
5269 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5270 + nri.mRequests.get(0) + " because their intents matched.");
5271 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005272 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005273 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005274 }
Erik Kline05f2b402015-04-30 12:58:40 +09005275 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005276 }
5277
James Mattisf7027322020-12-13 16:28:14 -08005278 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005279 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005280 }
5281
James Mattis3ce3d3c2021-02-09 18:18:28 -08005282 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005283 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005284 for (final NetworkRequestInfo nri : nris) {
5285 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005286 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005287 for (final NetworkRequest req : nri.mRequests) {
5288 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005289 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005290 if (req.isListen()) {
5291 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5292 if (req.networkCapabilities.hasSignalStrength()
5293 && network.satisfiesImmutableCapabilitiesOf(req)) {
5294 updateSignalStrengthThresholds(network, "REGISTER", req);
5295 }
James Mattisf7027322020-12-13 16:28:14 -08005296 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005297 }
5298 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005299
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005300 // If this NRI has a satisfier already, it is replacing an older request that
5301 // has been removed. Track it.
5302 final NetworkRequest activeRequest = nri.getActiveRequest();
5303 if (null != activeRequest) {
5304 // If there is an active request, then for sure there is a satisfier.
5305 nri.getSatisfier().addRequest(activeRequest);
5306 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005307 }
James Mattisf7027322020-12-13 16:28:14 -08005308
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005309 if (mFlags.noRematchAllRequestsOnRegister()) {
5310 rematchNetworksAndRequests(nris);
5311 } else {
5312 rematchAllNetworksAndRequests();
5313 }
James Mattis45d81842021-01-10 14:24:24 -08005314
Chalard Jean0354d8c2021-01-12 10:58:56 +09005315 // Requests that have not been matched to a network will not have been sent to the
5316 // providers, because the old satisfier and the new satisfier are the same (null in this
5317 // case). Send these requests to the providers.
5318 for (final NetworkRequestInfo nri : nris) {
5319 for (final NetworkOfferInfo noi : mNetworkOffers) {
5320 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005321 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005322 }
5323 }
5324
James Mattisf7027322020-12-13 16:28:14 -08005325 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5326 final int callingUid) {
5327 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005328 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005329 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5330 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5331 handleReleaseNetworkRequest(
5332 nri.mRequests.get(0),
5333 callingUid,
5334 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005335 }
5336 }
5337
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005338 // Determines whether the network is the best (or could become the best, if it validated), for
5339 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5340 // on the value of reason:
5341 //
5342 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5343 // then it should be torn down.
5344 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5345 // then it should be lingered.
5346 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005347 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005348
Chalard Jean254bd162022-08-25 13:04:51 +09005349 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005350 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5351 return false;
5352 }
5353
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005354 final int numRequests;
5355 switch (reason) {
5356 case TEARDOWN:
5357 numRequests = nai.numRequestNetworkRequests();
5358 break;
5359 case LINGER:
5360 numRequests = nai.numForegroundNetworkRequests();
5361 break;
5362 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005363 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005364 return true;
5365 }
5366
Chalard Jean947acd42021-03-08 22:29:27 +09005367 if (numRequests > 0) return false;
5368
Paul Jensende49eb12015-06-25 15:30:08 -04005369 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005370 if (reason == UnneededFor.LINGER
5371 && !nri.isMultilayerRequest()
5372 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005373 // Background requests don't affect lingering.
5374 continue;
5375 }
5376
James Mattis3d229892020-11-16 16:46:28 -08005377 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005378 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005379 }
5380 }
Paul Jensende49eb12015-06-25 15:30:08 -04005381 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005382 }
5383
James Mattis3d229892020-11-16 16:46:28 -08005384 private boolean isNetworkPotentialSatisfier(
5385 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005386 // While destroyed network sometimes satisfy requests (including occasionally newly
5387 // satisfying requests), *potential* satisfiers are networks that might beat a current
5388 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5389 // because it's never a good idea to keep a destroyed network in case it validates.
5390 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5391 // candidate after it's been replaced by another unvalidated network.
5392 if (candidate.isDestroyed()) return false;
5393 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005394 // request, return immediately. For multilayer requests, check to see if any of the
5395 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005396 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5397 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005398 return false;
5399 }
5400 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005401 // This multilayer listen request is satisfied therefore no further requests need to be
5402 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005403 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005404 return false;
5405 }
James Mattis3d229892020-11-16 16:46:28 -08005406 // As non-multilayer listen requests have already returned, the below would only happen
5407 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005408 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005409 continue;
5410 }
Chalard Jean80685f42023-10-30 18:31:27 +09005411 // If there is hope for this network might validate and subsequently become the best
5412 // network for that request, then it is needed. Note that this network can't already
5413 // be the best for this request, or it would be the current satisfier, and therefore
5414 // there would be no need to call this method to find out if it is a *potential*
5415 // satisfier ("unneeded", the only caller, only calls this if this network currently
5416 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005417 if (candidate.satisfies(req)) {
5418 // As soon as a network is found that satisfies a request, return. Specifically for
5419 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5420 // is important so as to not evaluate lower priority requests further in
5421 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005422 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5423 ? nri.getSatisfier() : null;
5424 // Note that this catches two important cases:
5425 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5426 // is currently satisfying the request. This is desirable when
5427 // cellular ends up validating but WiFi does not.
5428 // 2. Unvalidated WiFi will not be reaped when validated cellular
5429 // is currently satisfying the request. This is desirable when
5430 // WiFi ends up validating and out scoring cellular.
5431 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005432 }
5433 }
5434
5435 return false;
5436 }
5437
Erik Kline0c04b742016-07-07 16:50:58 +09005438 private NetworkRequestInfo getNriForAppRequest(
5439 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005440 // Looking up the app passed param request in mRequests isn't possible since it may return
5441 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5442 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005443 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5444 // to avoid potential race conditions when validating a package->uid mapping when sending
5445 // the callback on the very low-chance that an application shuts down prior to the callback
5446 // being sent.
5447 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5448 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005449
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005450 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005451 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005452 log(String.format("UID %d attempted to %s for unowned request %s",
5453 callingUid, requestedOperation, nri));
5454 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005455 }
Erik Kline0c04b742016-07-07 16:50:58 +09005456 }
5457
5458 return nri;
5459 }
5460
James Mattisf7027322020-12-13 16:28:14 -08005461 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5462 final String callingMethod) {
5463 if (nri.isMultilayerRequest()) {
5464 throw new IllegalStateException(
5465 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005466 }
5467 }
5468
James Mattisf7027322020-12-13 16:28:14 -08005469 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005470 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005471 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5472 // single NetworkRequest and thus does not apply to multilayer requests.
5473 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5474 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005475 return;
5476 }
James Mattis2516da32021-01-31 17:06:19 -08005477 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005478 return;
5479 }
James Mattisf7027322020-12-13 16:28:14 -08005480 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5481 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005482 }
5483 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005484 callCallbackForRequest(
5485 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005486 }
5487
James Mattisf7027322020-12-13 16:28:14 -08005488 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5489 final int callingUid,
5490 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005491 final NetworkRequestInfo nri =
5492 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5493 if (nri == null) {
5494 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005495 }
James Mattisf7027322020-12-13 16:28:14 -08005496 if (VDBG || (DBG && request.isRequest())) {
5497 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005498 }
5499 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005500 if (callOnUnavailable) {
5501 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5502 }
Erik Kline155a59a2015-11-25 12:49:38 +09005503 }
Erik Kline0c04b742016-07-07 16:50:58 +09005504
James Mattisa076c532020-12-02 14:12:41 -08005505 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005506 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005507 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005508 if (null == mNetworkRequests.remove(req)) {
5509 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5510 continue;
5511 }
James Mattisa076c532020-12-02 14:12:41 -08005512 if (req.isListen()) {
5513 removeListenRequestFromNetworks(req);
5514 }
5515 }
James Mattis8f036802021-06-20 16:26:01 -07005516 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005517 if (mDefaultNetworkRequests.remove(nri)) {
5518 // If this request was one of the defaults, then the UID rules need to be updated
5519 // WARNING : if the app(s) for which this network request is the default are doing
5520 // traffic, this will kill their connected sockets, even if an equivalent request
5521 // is going to be reinstated right away ; unconnected traffic will go on the default
5522 // until the new default is set, which will happen very soon.
5523 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5524 // remove ranges for those requests that won't have a replacement
5525 final NetworkAgentInfo satisfier = nri.getSatisfier();
5526 if (null != satisfier) {
5527 try {
paulhu0e79d952021-06-09 16:11:35 +08005528 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5529 satisfier.network.getNetId(),
5530 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005531 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005532 } catch (RemoteException e) {
5533 loge("Exception setting network preference default network", e);
5534 }
5535 }
5536 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005537
Junyu Lai00d92df2022-07-05 11:01:52 +08005538 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005539 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005540 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005541
5542 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005543 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005544 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005545 }
5546 }
5547
Chalard Jean0354d8c2021-01-12 10:58:56 +09005548 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5549 // needed for this offer.
5550 for (final NetworkOfferInfo noi : mNetworkOffers) {
5551 for (final NetworkRequest req : nri.mRequests) {
5552 if (req.isRequest() && noi.offer.neededFor(req)) {
5553 noi.offer.onNetworkUnneeded(req);
5554 }
5555 }
5556 }
James Mattisa076c532020-12-02 14:12:41 -08005557 }
5558
James Mattis3ce3d3c2021-02-09 18:18:28 -08005559 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5560 for (final NetworkRequestInfo nri : nris) {
5561 if (mDefaultRequest == nri) {
5562 // Make sure we never remove the default request.
5563 continue;
5564 }
5565 handleRemoveNetworkRequest(nri);
5566 }
5567 }
5568
James Mattisa076c532020-12-02 14:12:41 -08005569 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5570 // listens don't have a singular affected Network. Check all networks to see
5571 // if this listen request applies and remove it.
5572 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5573 nai.removeRequest(req.requestId);
5574 if (req.networkCapabilities.hasSignalStrength()
5575 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5576 updateSignalStrengthThresholds(nai, "RELEASE", req);
5577 }
5578 }
5579 }
5580
5581 /**
5582 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5583 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5584 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5585 */
5586 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5587 boolean wasKept = false;
5588 final NetworkAgentInfo nai = nri.getSatisfier();
5589 if (nai != null) {
5590 final int requestLegacyType = nri.getActiveRequest().legacyType;
5591 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5592 nai.removeRequest(nri.getActiveRequest().requestId);
5593 if (VDBG || DDBG) {
5594 log(" Removing from current network " + nai.toShortString()
5595 + ", leaving " + nai.numNetworkRequests() + " requests.");
5596 }
5597 // If there are still lingered requests on this network, don't tear it down,
5598 // but resume lingering instead.
5599 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005600 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005601 notifyNetworkLosing(nai, now);
5602 }
5603 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5604 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5605 teardownUnneededNetwork(nai);
5606 } else {
5607 wasKept = true;
5608 }
James Mattisa076c532020-12-02 14:12:41 -08005609 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5610 // Went from foreground to background.
5611 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005612 }
5613
Erik Kline0c04b742016-07-07 16:50:58 +09005614 // Maintain the illusion. When this request arrived, we might have pretended
5615 // that a network connected to serve it, even though the network was already
5616 // connected. Now that this request has gone away, we might have to pretend
5617 // that the network disconnected. LegacyTypeTracker will generate that
5618 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005619 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005620 boolean doRemove = true;
5621 if (wasKept) {
5622 // check if any of the remaining requests for this network are for the
5623 // same legacy type - if so, don't remove the nai
5624 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5625 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005626 if (otherRequest.legacyType == requestLegacyType
5627 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005628 if (DBG) log(" still have other legacy request - leaving");
5629 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005630 }
5631 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005632 }
5633
Erik Kline0c04b742016-07-07 16:50:58 +09005634 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005635 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005636 }
5637 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005638 }
5639 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005640
Junyu Lai00d92df2022-07-05 11:01:52 +08005641 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005642 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005643 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5644 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5645 }
5646
Lorenzo Colittid6459092016-07-04 12:55:44 +09005647 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005648 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005649 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005650 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005651 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005652 }
5653
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005654 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005655 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5656 enforceNetworkStackSettingsOrSetup();
5657 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5658 encodeBool(accept), encodeBool(always), network));
5659 }
5660
5661 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005662 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005663 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005664 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5665 }
5666
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005667 @Override
5668 public void setTestAllowBadWifiUntil(long timeMs) {
5669 enforceSettingsPermission();
5670 if (!Build.isDebuggable()) {
5671 throw new IllegalStateException("Does not support in non-debuggable build");
5672 }
5673
5674 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5675 throw new IllegalArgumentException("It should not exceed "
5676 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5677 }
5678
5679 mHandler.sendMessage(
5680 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5681 }
5682
chiachangwange0192a72023-02-06 13:25:01 +00005683 @Override
5684 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5685 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005686
5687 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5688 throw new IllegalArgumentException("Argument should not exceed "
5689 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5690 }
5691
5692 mHandler.sendMessage(
5693 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5694 }
5695
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005696 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5697 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5698 " accept=" + accept + " always=" + always);
5699
5700 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5701 if (nai == null) {
5702 // Nothing to do.
5703 return;
5704 }
5705
Chalard Jean254bd162022-08-25 13:04:51 +09005706 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005707 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005708 return;
5709 }
5710
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005711 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005712 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005713 }
5714
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005715 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5716 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005717 // If network becomes partial connectivity and user already accepted to use this
5718 // network, we should respect the user's option and don't need to popup the
5719 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005720 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005721 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005722 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005723 }
5724
5725 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005726 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005727 }
5728
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005729 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005730 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005731 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005732 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005733 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005734 }
5735
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005736 }
5737
lucaslin2240ef62019-03-12 13:08:03 +08005738 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5739 boolean always) {
5740 if (DBG) {
5741 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5742 + " always=" + always);
5743 }
5744
5745 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5746 if (nai == null) {
5747 // Nothing to do.
5748 return;
5749 }
5750
Chalard Jean254bd162022-08-25 13:04:51 +09005751 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005752 // The network validated while the dialog box was up. Take no action.
5753 return;
5754 }
5755
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005756 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5757 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005758 }
5759
5760 // TODO: Use the current design or save the user choice into IpMemoryStore.
5761 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005762 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005763 }
5764
5765 if (!accept) {
5766 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005767 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005768 // Tear down the network.
5769 teardownUnneededNetwork(nai);
5770 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005771 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5772 // result in a partial connectivity result which will be processed by
5773 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005774 //
5775 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5776 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005777 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005778 }
5779 }
5780
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005781 private void handleSetAvoidUnvalidated(Network network) {
5782 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005783 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005784 // Nothing to do. The network either disconnected or revalidated.
5785 return;
5786 }
Chalard Jean254bd162022-08-25 13:04:51 +09005787 if (0L == nai.getAvoidUnvalidated()) {
5788 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005789 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005790 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005791 }
5792 }
5793
Chalard Jean5fb43c72022-09-08 19:03:14 +09005794 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005795 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005796 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005797 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005798 }
5799
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005800 @Override
5801 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005802 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005803 mHandler.post(() -> {
5804 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5805 if (nai == null) return;
5806 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005807 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005808 });
5809 }
5810
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005811 /**
5812 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5813 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005814 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005815 * @param appExtras Bundle to use as intent extras for the captive portal application.
5816 * Must be treated as opaque to avoid preventing the captive portal app to
5817 * update its arguments.
5818 */
5819 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005820 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005821 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5822 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005823
5824 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5825 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005826 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5827 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005828 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5829
lucaslin75ff7022020-12-17 04:14:35 +08005830 final long token = Binder.clearCallingIdentity();
5831 try {
5832 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5833 } finally {
5834 Binder.restoreCallingIdentity(token);
5835 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005836 }
5837
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005838 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5839 private final Network mNetwork;
5840
5841 private CaptivePortalImpl(Network network) {
5842 mNetwork = network;
5843 }
5844
5845 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005846 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005847 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5848 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005849 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5850 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5851 // Since the network will be disconnected, skip notifying NetworkMonitor
5852 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005853 }
5854
Chiachang Wang938bfba2020-01-09 13:50:55 +08005855 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005856 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005857 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005858 }
5859
5860 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005861 public void appRequest(final int request) {
5862 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5863 if (nm == null) return;
5864
5865 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005866 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005867 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005868 }
5869 }
5870
5871 @Nullable
5872 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5873 // getNetworkAgentInfoForNetwork is thread-safe
5874 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5875 if (nai == null) return null;
5876
5877 // nai.networkMonitor() is thread-safe
5878 return nai.networkMonitor();
5879 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005880 }
5881
Hugo Benichic9048bc2016-09-14 23:23:08 +00005882 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005883 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005884 }
5885
Chalard Jean020b93a2022-09-01 13:20:14 +09005886 private boolean activelyPreferBadWifi() {
5887 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5888 }
5889
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005890 /**
5891 * Return whether the device should maintain continuous, working connectivity by switching away
5892 * from WiFi networks having no connectivity.
5893 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5894 */
5895 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005896 if (!checkNetworkStackPermission()) {
5897 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5898 }
5899 return avoidBadWifi();
5900 }
5901
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005902 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005903 ensureRunningOnConnectivityServiceThread();
5904 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005905 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005906 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005907 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005908 if (avoidBadWifi) {
5909 // If the device is now avoiding bad wifi, remove notifications that might have
5910 // been put up when the device didn't.
5911 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5912 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005913 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005914 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5915 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5916 for (final NetworkOfferInfo noi : offersToUpdate) {
5917 updateOfferScore(noi.offer);
5918 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005919 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005920 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005921 }
5922
Erik Kline95ecfee2016-10-02 18:02:14 +09005923 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005924 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005925 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005926 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005927 if (!configRestrict) {
5928 pw.println("Bad Wi-Fi avoidance: unrestricted");
5929 return;
5930 }
5931
5932 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5933 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005934 pw.println("Config restrict: " + configRestrict);
5935 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005936
Chalard Jeane0fdea32022-09-14 21:44:22 +09005937 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005938 String description;
5939 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005940 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005941 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005942 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005943 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005944 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005945 description = "avoid";
5946 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005947 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005948 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005949 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005950
5951 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5952 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005953 if (null == configValue) {
5954 description = "unset";
5955 } else if (configValue) {
5956 description = "force true";
5957 } else {
5958 description = "force false";
5959 }
5960 pw.println("Actively prefer bad wifi conf: " + description);
5961 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005962 pw.println("Network overrides:");
5963 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005964 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005965 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005966 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005967 }
5968 }
5969 pw.decreaseIndent();
5970 pw.decreaseIndent();
5971 }
5972
paulhu7746e4e2020-06-09 19:07:03 +08005973 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5974 // unify the method.
5975 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5976 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5977 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5978 return settingsComponent != null
5979 ? settingsComponent.getPackageName() : "com.android.settings";
5980 }
5981
lucaslinb1e8e382019-01-24 15:55:30 +08005982 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005983 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005984 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005985 switch (type) {
5986 case NO_INTERNET:
5987 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005988 // High priority because it is only displayed for explicitly selected networks.
5989 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005990 break;
lucasline117e2e2019-10-22 18:27:33 +08005991 case PRIVATE_DNS_BROKEN:
5992 action = Settings.ACTION_WIRELESS_SETTINGS;
5993 // High priority because we should let user know why there is no internet.
5994 highPriority = true;
5995 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005996 case LOST_INTERNET:
5997 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005998 // High priority because it could help the user avoid unexpected data usage.
5999 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006000 break;
lucaslin2240ef62019-03-12 13:08:03 +08006001 case PARTIAL_CONNECTIVITY:
6002 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006003 // Don't bother the user with a high-priority notification if the network was not
6004 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006005 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006006 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006007 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006008 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006009 return;
6010 }
6011
6012 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006013 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006014 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006015 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006016 // Some OEMs have their own Settings package. Thus, need to get the current using
6017 // Settings package name instead of just use default name "com.android.settings".
6018 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6019 intent.setClassName(settingsPkgName,
6020 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006021 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006022
paulhu2af50222020-10-11 22:52:27 +08006023 PendingIntent pendingIntent = PendingIntent.getActivity(
6024 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006025 0 /* requestCode */,
6026 intent,
paulhu2af50222020-10-11 22:52:27 +08006027 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006028
Serik Beketayevec8ad212020-12-07 22:43:07 -08006029 mNotifier.showNotification(
6030 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006031 }
6032
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006033 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6034 // Don't prompt if the network is validated, and don't prompt on captive portals
6035 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006036 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006037 return false;
6038 }
6039
6040 // If a network has partial connectivity, always prompt unless the user has already accepted
6041 // partial connectivity and selected don't ask again. This ensures that if the device
6042 // automatically connects to a network that has partial Internet access, the user will
6043 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006044 // because we have prompted them.
6045 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006046 return true;
6047 }
6048
6049 // If a network has no Internet access, only prompt if the network was explicitly selected
6050 // and if the user has not already told us to use the network regardless of whether it
6051 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006052 if (nai.networkAgentConfig.explicitlySelected
6053 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006054 return true;
6055 }
6056
6057 return false;
6058 }
6059
Chalard Jean5fb43c72022-09-08 19:03:14 +09006060 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6061 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006062
Chalard Jean5fb43c72022-09-08 19:03:14 +09006063 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6064 if (null == nai) return;
6065
6066 if (nai.setEvaluated()) {
6067 // If setEvaluated() returned true, the network never had any form of connectivity.
6068 // This may have an impact on request matching if bad WiFi avoidance is off and the
6069 // network was found not to have Internet access.
6070 nai.updateScoreForNetworkAgentUpdate();
6071 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006072
6073 // Also, if this is WiFi and it should be preferred actively, now is the time to
6074 // prompt the user that they walked past and connected to a bad WiFi.
6075 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6076 && !avoidBadWifi()
6077 && activelyPreferBadWifi()) {
6078 // The notification will be removed if the network validates or disconnects.
6079 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6080 return;
6081 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006082 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006083
Chalard Jean5fb43c72022-09-08 19:03:14 +09006084 if (!shouldPromptUnvalidated(nai)) return;
6085
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006086 // Stop automatically reconnecting to this network in the future. Automatically connecting
6087 // to a network that provides no or limited connectivity is not useful, because the user
6088 // cannot use that network except through the notification shown by this method, and the
6089 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006090 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006091
Chalard Jean254bd162022-08-25 13:04:51 +09006092 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006093 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006094 } else {
6095 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6096 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006097 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006098
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006099 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6100 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006101 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006102
lucaslin2240ef62019-03-12 13:08:03 +08006103 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6104 return;
6105 }
6106
6107 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006108 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006109 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006110 }
6111
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006112 @Override
6113 public int getMultipathPreference(Network network) {
6114 enforceAccessPermission();
6115
6116 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006117 if (nai != null && nai.networkCapabilities
6118 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006119 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6120 }
6121
Aaron Huang9a57acf2020-12-08 10:03:29 +08006122 final NetworkPolicyManager netPolicyManager =
6123 mContext.getSystemService(NetworkPolicyManager.class);
6124
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006125 final long token = Binder.clearCallingIdentity();
6126 final int networkPreference;
6127 try {
6128 networkPreference = netPolicyManager.getMultipathPreference(network);
6129 } finally {
6130 Binder.restoreCallingIdentity(token);
6131 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006132 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006133 return networkPreference;
6134 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006135 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6136 }
6137
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006138 @Override
6139 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006140 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006141 }
6142
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006143 private class InternalHandler extends Handler {
6144 public InternalHandler(Looper looper) {
6145 super(looper);
6146 }
6147
6148 @Override
6149 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006150 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006151 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006152 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006153 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006154 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006155 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006156 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006157 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006158 break;
6159 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006160 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006161 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006162 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006163 break;
6164 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006165 case EVENT_REGISTER_NETWORK_PROVIDER: {
6166 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006167 break;
6168 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006169 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6170 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006171 break;
6172 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006173 case EVENT_REGISTER_NETWORK_OFFER: {
6174 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6175 break;
6176 }
6177 case EVENT_UNREGISTER_NETWORK_OFFER: {
6178 final NetworkOfferInfo offer =
6179 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6180 if (null != offer) {
6181 handleUnregisterNetworkOffer(offer);
6182 }
6183 break;
6184 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006185 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006186 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6187 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6188 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006189 break;
6190 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006191 case EVENT_REGISTER_NETWORK_REQUEST:
6192 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006193 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006194 break;
6195 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006196 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6197 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006198 handleRegisterNetworkRequestWithIntent(msg);
6199 break;
6200 }
Erik Kline155a59a2015-11-25 12:49:38 +09006201 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6202 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6203 handleTimedOutNetworkRequest(nri);
6204 break;
6205 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006206 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6207 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6208 break;
6209 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006210 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006211 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6212 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006213 break;
6214 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006215 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006216 Network network = (Network) msg.obj;
6217 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006218 break;
6219 }
lucaslin2240ef62019-03-12 13:08:03 +08006220 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6221 Network network = (Network) msg.obj;
6222 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6223 toBool(msg.arg2));
6224 break;
6225 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006226 case EVENT_SET_AVOID_UNVALIDATED: {
6227 handleSetAvoidUnvalidated((Network) msg.obj);
6228 break;
6229 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006230 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6231 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006232 break;
6233 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006234 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6235 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006236 break;
6237 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006238 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6239 // handler thread.
6240 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006241 mKeepaliveTracker.handleStartKeepalive(msg);
6242 break;
6243 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006244 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006245 final AutomaticOnOffKeepalive ki =
6246 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6247 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006248
chiachangwang676c84e2023-02-14 09:22:05 +00006249 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006250 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006251 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006252 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006253 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6254 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006255 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6256 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006257 }
6258 }
6259
6260 // If the network no longer exists, then the keepalive should have been
6261 // cleaned up already. There is no point trying to resume keepalives.
6262 if (!networkFound) return;
6263
chiachangwang676c84e2023-02-14 09:22:05 +00006264 if (underpinnedNetworkFound) {
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006265 final NetworkCapabilities underpinnedNc =
6266 getNetworkCapabilitiesInternal(underpinnedNetwork);
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006267 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006268 underpinnedNetwork.netId, underpinnedNc.getUids());
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006269 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006270 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006271 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006272 }
6273 break;
6274 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006275 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006276 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006277 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6278 (IBinder) msg.obj);
6279 if (ki == null) {
6280 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006281 return;
6282 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006283 final int reason = msg.arg2;
6284 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006285 break;
6286 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006287 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6288 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6289 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006290 break;
6291 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006292 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6293 handlePrivateDnsSettingsChanged();
6294 break;
dalyk1720e542018-03-05 12:42:22 -05006295 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6296 handlePrivateDnsValidationUpdate(
6297 (PrivateDnsValidationUpdate) msg.obj);
6298 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006299 case EVENT_UID_BLOCKED_REASON_CHANGED:
6300 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006301 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006302 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6303 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6304 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006305 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006306 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6307 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006308 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006309 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006310 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006311 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006312 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6313 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006314 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006315 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006316 }
lucaslin1193a5d2021-01-21 02:04:15 +08006317 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006318 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006319 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006320 break;
paulhu51f77dc2021-06-07 02:34:20 +00006321 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6322 handleMobileDataPreferredUidsChanged();
6323 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006324 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6325 final long timeMs = ((Long) msg.obj).longValue();
6326 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6327 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006328 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6329 handleIngressRateLimitChanged();
6330 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006331 case EVENT_USER_DOES_NOT_WANT:
6332 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6333 if (nai == null) break;
6334 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006335 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006336 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006337 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6338 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6339 break;
chiachangwange0192a72023-02-06 13:25:01 +00006340 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6341 final long time = ((Long) msg.obj).longValue();
6342 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6343 break;
6344 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006345 case EVENT_UID_FROZEN_STATE_CHANGED:
6346 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6347 handleFrozenUids(args.mUids, args.mFrozenStates);
6348 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006349 }
6350 }
6351 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006352
Lorenzo Colittid6459092016-07-04 12:55:44 +09006353 @Override
markchien5776f962019-12-16 20:15:20 +08006354 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006355 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006356 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006357 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6358 Context.TETHERING_SERVICE);
6359 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006360 }
6361
Lorenzo Colittid6459092016-07-04 12:55:44 +09006362 @Override
markchien5776f962019-12-16 20:15:20 +08006363 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006364 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006365 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006366 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6367 Context.TETHERING_SERVICE);
6368 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006369 }
6370
Lorenzo Colittid6459092016-07-04 12:55:44 +09006371 @Override
markchien5776f962019-12-16 20:15:20 +08006372 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006373 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006374 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006375 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6376 Context.TETHERING_SERVICE);
6377 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006378 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006379
markchien5776f962019-12-16 20:15:20 +08006380
Lorenzo Colittid6459092016-07-04 12:55:44 +09006381 @Override
markchien5776f962019-12-16 20:15:20 +08006382 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006383 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006384 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006385 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6386 Context.TETHERING_SERVICE);
6387
6388 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006389 }
6390
Lorenzo Colittid6459092016-07-04 12:55:44 +09006391 @Override
markchien5776f962019-12-16 20:15:20 +08006392 @Deprecated
6393 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006394 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006395 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6396 Context.TETHERING_SERVICE);
6397
6398 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006399 }
6400
Udam Saini8f7d6a72017-06-07 12:06:28 -07006401 @Override
markchien5776f962019-12-16 20:15:20 +08006402 @Deprecated
6403 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006404 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006405 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6406 Context.TETHERING_SERVICE);
6407 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006408 }
6409
Robert Greenwalte0b00512014-07-02 09:59:16 -07006410 // Called when we lose the default network and have no replacement yet.
6411 // This will automatically be cleared after X seconds or a new default network
6412 // becomes CONNECTED, whichever happens first. The timer is started by the
6413 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006414 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006415 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006416 if (mNetTransitionWakeLock.isHeld()) {
6417 return;
6418 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006419 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006420 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6421 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006422 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006423 mWakelockLogs.log("ACQUIRE for " + forWhom);
6424 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006425 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006426 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006427 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006428 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006429
Hugo Benichi471b62a2017-03-30 23:18:10 +09006430 // Called when we gain a new default network to release the network transition wakelock in a
6431 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6432 // message is cancelled.
6433 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006434 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006435 if (!mNetTransitionWakeLock.isHeld()) {
6436 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006437 }
6438 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006439 // Cancel self timeout on wakelock hold.
6440 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6441 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6442 mHandler.sendMessageDelayed(msg, 1000);
6443 }
6444
6445 // Called when either message of ensureNetworkTransitionWakelock or
6446 // scheduleReleaseNetworkTransitionWakelock is processed.
6447 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6448 String event = eventName(eventId);
6449 synchronized (this) {
6450 if (!mNetTransitionWakeLock.isHeld()) {
6451 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006452 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006453 return;
6454 }
6455 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006456 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6457 mTotalWakelockDurationMs += lockDuration;
6458 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6459 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006460 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006461 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006462 }
6463
Robert Greenwalt986c7412010-09-08 15:24:47 -07006464 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006465 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006466 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006467 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006468 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006469 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006470 }
6471
Lorenzo Colittid6459092016-07-04 12:55:44 +09006472 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006473 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006474 enforceAccessPermission();
6475 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006476 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006477 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006478
6479 final NetworkAgentInfo nai;
6480 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006481 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006482 } else {
6483 nai = getNetworkAgentInfoForNetwork(network);
6484 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006485
6486 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006487 mHandler.obtainMessage(
6488 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006489 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006490
Hugo Benichid6b510a2017-04-06 17:22:18 +09006491 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006492 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006493 if (nai == null
6494 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006495 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006496 return;
6497 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006498 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006499 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006500 mConnectivityDiagnosticsHandler.sendMessage(
6501 mConnectivityDiagnosticsHandler.obtainMessage(
6502 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6503 new ReportedNetworkConnectivityInfo(
6504 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006505 return;
6506 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006507 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006508 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006509 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006510 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006511 // Validating a network that has not yet connected could result in a call to
6512 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006513 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006514 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006515 }
paulhu7aeba372020-12-30 00:42:19 +08006516 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6517 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006518 return;
6519 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006520
6521 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6522 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6523 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6524 // completed.
6525 mConnectivityDiagnosticsHandler.sendMessage(
6526 mConnectivityDiagnosticsHandler.obtainMessage(
6527 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6528 new ReportedNetworkConnectivityInfo(
6529 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006530 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006531 }
6532
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006533 // TODO: call into netd.
6534 private boolean queryUserAccess(int uid, Network network) {
6535 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6536 if (nai == null) return false;
6537
6538 // Any UID can use its default network.
6539 if (nai == getDefaultNetworkForUid(uid)) return true;
6540
6541 // Privileged apps can use any network.
6542 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6543 return true;
6544 }
6545
6546 // An unprivileged UID can use a VPN iff the VPN applies to it.
6547 if (nai.isVPN()) {
6548 return nai.networkCapabilities.appliesToUid(uid);
6549 }
6550
6551 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6552 // sockets, i.e., if it is the owner.
6553 final NetworkAgentInfo vpn = getVpnForUid(uid);
6554 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6555 && uid != vpn.networkCapabilities.getOwnerUid()) {
6556 return false;
6557 }
6558
6559 // The UID's permission must be at least sufficient for the network. Since the restricted
6560 // permission was already checked above, that just leaves background networks.
6561 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6562 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6563 }
6564
6565 // Unrestricted network. Anyone gets to use it.
6566 return true;
6567 }
6568
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006569 /**
6570 * Returns information about the proxy a certain network is using. If given a null network, it
6571 * it will return the proxy for the bound network for the caller app or the default proxy if
6572 * none.
6573 *
6574 * @param network the network we want to get the proxy information for.
6575 * @return Proxy information if a network has a proxy configured, or otherwise null.
6576 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006577 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006578 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006579 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006580 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006581 if (network == null) {
6582 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006583 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006584 true);
6585 if (activeNetwork == null) {
6586 return null;
6587 }
6588 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006589 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006590 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6591 // caller may not have.
6592 return getLinkPropertiesProxyInfo(network);
6593 }
6594 // No proxy info available if the calling UID does not have network access.
6595 return null;
6596 }
6597
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006598
6599 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006600 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6601 if (nai == null) return null;
6602 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006603 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6604 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006605 }
6606 }
6607
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006608 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006609 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006610 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006611 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006612 }
6613
Chalard Jean777e2e52018-06-07 18:02:37 +09006614 @Override
6615 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006616 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006617 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006618 }
6619
Aaron Huang9fe47be2021-06-08 13:11:45 +08006620 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006621 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006622 final NetworkAgentInfo nai = getDefaultNetwork();
6623 // TODO : this method should check that net == nai.network, unfortunately at this point
6624 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6625 // is only ever installed on the default network so in practice this is okay.
6626 if (null == nai) return;
6627 // PAC proxies only work on the default network. Therefore, only the default network
6628 // should have its link properties fixed up for PAC proxies.
6629 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6630 if (nai.everConnected()) {
6631 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6632 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006633 }
6634
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006635 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6636 // when any network changes proxy.
6637 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6638 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006639 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6640 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006641 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6642
Chalard Jean7d97afc2018-06-07 17:41:29 +09006643 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006644 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006645 }
6646 }
6647
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006648 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006649 final private HashMap<Uri, Integer> mUriEventMap;
6650 final private Context mContext;
6651 final private Handler mHandler;
6652
6653 SettingsObserver(Context context, Handler handler) {
6654 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006655 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006656 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006657 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006658 }
6659
Erik Kline05f2b402015-04-30 12:58:40 +09006660 void observe(Uri uri, int what) {
6661 mUriEventMap.put(uri, what);
6662 final ContentResolver resolver = mContext.getContentResolver();
6663 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006664 }
6665
6666 @Override
6667 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006668 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006669 }
6670
6671 @Override
6672 public void onChange(boolean selfChange, Uri uri) {
6673 final Integer what = mUriEventMap.get(uri);
6674 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006675 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006676 } else {
6677 loge("No matching event to send for URI=" + uri);
6678 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006679 }
6680 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006681
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006682 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006683 Log.d(TAG, s);
6684 }
6685
6686 private static void logw(String s) {
6687 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006688 }
6689
Daniel Brightf9e945b2020-06-15 16:10:01 -07006690 private static void logwtf(String s) {
6691 Log.wtf(TAG, s);
6692 }
6693
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006694 private static void logwtf(String s, Throwable t) {
6695 Log.wtf(TAG, s, t);
6696 }
6697
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006698 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006699 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006700 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006701
Hugo Benichi39621362017-02-11 17:04:43 +09006702 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006703 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006704 }
6705
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006706 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006707 * Return the information of all ongoing VPNs.
6708 *
6709 * <p>This method is used to update NetworkStatsService.
6710 *
6711 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006712 */
junyulai2050bed2021-01-23 09:46:34 +08006713 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006714 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006715 if (mLockdownEnabled) {
6716 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006717 }
junyulai2050bed2021-01-23 09:46:34 +08006718 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006719 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006720 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006721 if (info != null) {
6722 infoList.add(info);
6723 }
6724 }
junyulai2050bed2021-01-23 09:46:34 +08006725 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006726 }
6727
6728 /**
6729 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006730 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006731 */
junyulai2050bed2021-01-23 09:46:34 +08006732 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006733 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006734 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6735 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006736 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6737 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6738 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006739 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6740 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006741 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006742 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006743 }
6744 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006745
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006746 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006747
6748 List<String> interfaces = new ArrayList<>();
6749 for (Network network : underlyingNetworks) {
6750 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6751 if (underlyingNai == null) continue;
6752 LinkProperties lp = underlyingNai.linkProperties;
6753 for (String iface : lp.getAllInterfaceNames()) {
6754 if (!TextUtils.isEmpty(iface)) {
6755 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006756 }
6757 }
Benedict Wong34857f82019-06-12 17:46:15 +00006758 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006759
6760 if (interfaces.isEmpty()) return null;
6761
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006762 // Must be non-null or NetworkStatsService will crash.
6763 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6764 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006765 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006766 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006767
junyulai2050bed2021-01-23 09:46:34 +08006768 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6769 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006770 }
6771
James Mattisd31bdfa2020-12-23 16:37:26 -08006772 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006773 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6774 Network[] underlyingNetworks) {
6775 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006776 if (underlyingNetworks == null && defaultNetwork != null) {
6777 // null underlying networks means to track the default.
6778 underlyingNetworks = new Network[] { defaultNetwork };
6779 }
6780 return underlyingNetworks;
6781 }
6782
6783 // Returns true iff |network| is an underlying network of |nai|.
6784 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6785 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6786 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006787 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006788 final Network[] underlying = underlyingNetworksOrDefault(
6789 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006790 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006791 }
6792
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006793 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006794 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006795 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006796 * When underlying networks change, such networks may have to update capabilities to reflect
6797 * things like the metered bit, their transports, and so on. The capabilities are calculated
6798 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006799 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006800 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006801 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006802 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006803 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006804 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006805 }
6806 }
6807 }
6808
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006809 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6810 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6811 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6812 // a VPN is not up.
6813 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6814 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6815 for (UidRange range : blockedUidRanges) {
6816 if (range.contains(uid)) return true;
6817 }
6818 return false;
6819 }
6820
6821 @Override
6822 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006823 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006824 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6825 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6826 }
6827
6828 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6829 if (DBG) {
6830 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6831 + Arrays.toString(ranges));
6832 }
6833 // Cannot use a Set since the list of UID ranges might contain duplicates.
6834 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6835 for (int i = 0; i < ranges.length; i++) {
6836 if (requireVpn) {
6837 newVpnBlockedUidRanges.add(ranges[i]);
6838 } else {
6839 newVpnBlockedUidRanges.remove(ranges[i]);
6840 }
6841 }
6842
6843 try {
6844 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6845 } catch (RemoteException | ServiceSpecificException e) {
6846 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6847 + Arrays.toString(ranges) + "): netd command failed: " + e);
6848 }
6849
Chalard Jeandf29a852023-05-29 17:02:43 +09006850 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006851 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6852 }
6853
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006854 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6855 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006856 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6857 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006858 }
6859
6860 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6861 }
6862
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006863 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006864 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006865 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006866 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006867 }
6868
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006869 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6870 return mLockdownEnabled
6871 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6872 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006873 }
6874
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006875 private NetworkAgentInfo getLegacyLockdownNai() {
6876 if (!mLockdownEnabled) {
6877 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006878 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006879 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006880 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6881 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006882
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006883 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006884 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6885 // a local variable. There is no need to make a copy because its contents cannot change.
6886 final Network[] underlying = nai.declaredUnderlyingNetworks;
6887 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006888 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006889 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006890
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006891 // The legacy lockdown VPN always uses the default network.
6892 // If the VPN's underlying network is no longer the current default network, it means that
6893 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006894 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6895 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006896 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006897 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006898 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006899 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006900
6901 return nai;
6902 };
6903
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006904 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6905 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6906 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006907 private DetailedState getLegacyLockdownState(DetailedState origState) {
6908 if (origState != DetailedState.CONNECTED) {
6909 return origState;
6910 }
6911 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6912 ? DetailedState.CONNECTING
6913 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006914 }
6915
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006916 private void filterForLegacyLockdown(NetworkInfo ni) {
6917 if (!mLockdownEnabled || !ni.isConnected()) return;
6918 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6919 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6920 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6921 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6922 // network, this time with a state of CONNECTED.
6923 //
6924 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6925 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6926 // is not too far off the truth, since an always-on VPN, when not connected, is always
6927 // trying to reconnect.
6928 if (getLegacyLockdownNai() == null) {
6929 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6930 }
6931 }
6932
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006933 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006934 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006935 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006936 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006937 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6938 return;
6939 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006940 final long ident = Binder.clearCallingIdentity();
6941 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006942 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006943 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006944 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006945 } finally {
6946 Binder.restoreCallingIdentity(ident);
6947 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006948 }
Wink Savillecb117d32013-08-29 14:57:08 -07006949
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006950 @Override
6951 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006952 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006953 final long ident = Binder.clearCallingIdentity();
6954 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006955 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006956 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006957 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6958 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006959 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006960 } finally {
6961 Binder.restoreCallingIdentity(ident);
6962 }
6963 }
6964
James Mattis02220e22021-03-13 19:27:21 -08006965 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006966 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6967 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6968 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006969 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006970 }
6971
James Mattis02220e22021-03-13 19:27:21 -08006972 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006973 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006974 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006975 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6976 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006977 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006978 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6979 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6980 }
junyulaid91e7052020-08-28 13:44:33 +08006981 }
6982
James Mattis02220e22021-03-13 19:27:21 -08006983 private void onPackageChanged(@NonNull final String packageName) {
6984 // This is necessary in case a package is added or removed, but also when it's replaced to
6985 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6986 // as one in the preferences, then it should follow the same routing as that other package,
6987 // which means updating the rules is never to be needed in this case (whether it joins or
6988 // leaves a UID with a preference).
6989 if (isMappedInOemNetworkPreference(packageName)) {
6990 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6991 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006992
6993 // Invalidates cache entry when the package is updated.
6994 synchronized (mSelfCertifiedCapabilityCache) {
6995 mSelfCertifiedCapabilityCache.remove(packageName);
6996 }
James Mattis02220e22021-03-13 19:27:21 -08006997 }
6998
6999 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007000 @Override
7001 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007002 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007003 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007004 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007005
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007006 // User should be filled for below intents, check the existence.
7007 if (user == null) {
7008 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7009 return;
7010 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007011
Lorenzo Colitticd675292021-02-04 17:32:07 +09007012 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007013 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007014 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007015 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007016 } else {
junyulaid91e7052020-08-28 13:44:33 +08007017 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007018 }
7019 }
7020 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007021
James Mattis02220e22021-03-13 19:27:21 -08007022 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7023 @Override
7024 public void onReceive(Context context, Intent intent) {
7025 ensureRunningOnConnectivityServiceThread();
7026 switch (intent.getAction()) {
7027 case Intent.ACTION_PACKAGE_ADDED:
7028 case Intent.ACTION_PACKAGE_REMOVED:
7029 case Intent.ACTION_PACKAGE_REPLACED:
7030 onPackageChanged(intent.getData().getSchemeSpecificPart());
7031 break;
7032 default:
7033 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7034 }
7035 }
7036 };
7037
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007038 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007039 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007040
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007041 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007042 public final String name;
7043 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007044 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007045 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007046
lifraf3a3492021-03-10 13:58:14 +08007047 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7048 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007049 this.name = name;
7050 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007051 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007052 mDeathRecipient = deathRecipient;
7053
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007054 if (mDeathRecipient == null) {
7055 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007056 }
7057 }
7058
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007059 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007060 try {
7061 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7062 } catch (RemoteException e) {
7063 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007064 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007065 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007066 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007067
James Mattis4fce5d12020-11-12 15:53:42 -08007068 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7069 for (int i = 0; i < requests.size(); i++) {
7070 ensureNetworkRequestHasType(requests.get(i));
7071 }
7072 }
7073
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007074 private void ensureNetworkRequestHasType(NetworkRequest request) {
7075 if (request.type == NetworkRequest.Type.NONE) {
7076 throw new IllegalArgumentException(
7077 "All NetworkRequests in ConnectivityService must have a type");
7078 }
7079 }
7080
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007081 /**
7082 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007083 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007084 */
James Mattis258ea3c2020-11-15 15:04:40 -08007085 @VisibleForTesting
7086 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007087 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7088 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007089 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007090
James Mattisa076c532020-12-02 14:12:41 -08007091 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7092 void setSatisfier(
7093 @Nullable final NetworkAgentInfo satisfier,
7094 @Nullable final NetworkRequest activeRequest) {
7095 mSatisfier = satisfier;
7096 mActiveRequest = activeRequest;
7097 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007098
James Mattisd31bdfa2020-12-23 16:37:26 -08007099 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007100 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007101 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007102 private NetworkAgentInfo mSatisfier;
7103 NetworkAgentInfo getSatisfier() {
7104 return mSatisfier;
7105 }
7106
7107 // The request in mRequests assigned to a network agent. This is null if none of the
7108 // requests in mRequests can be satisfied. This member has the constraint of only being
7109 // accessible on the handler thread.
7110 @Nullable
7111 private NetworkRequest mActiveRequest;
7112 NetworkRequest getActiveRequest() {
7113 return mActiveRequest;
7114 }
7115
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007116 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007117 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007118 @Nullable
7119 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007120
7121 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007122 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007123 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007124 final int mPid;
7125 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007126 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007127 @Nullable
7128 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007129
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007130 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007131 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007132
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007133 // Effective UID of this request. This is different from mUid when a privileged process
7134 // files a request on behalf of another UID. This UID is used to determine blocked status,
7135 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7136 // maximum limit of registered callbacks per UID.
7137 final int mAsUid;
7138
paulhu48291862021-07-14 14:53:57 +08007139 // Preference order of this request.
7140 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007141
James Mattis3ce3d3c2021-02-09 18:18:28 -08007142 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7143 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7144 // maintained for keying off of. This is only a concern when the original nri
7145 // mNetworkRequests changes which happens currently for apps that register callbacks to
7146 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7147 // that match the per-app default nri that currently tracks the calling app's uid so that
7148 // callbacks are fired at the appropriate time. When the callbacks fire,
7149 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7150 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7151 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7152 @NonNull
7153 private final NetworkRequest mNetworkRequestForCallback;
7154 NetworkRequest getNetworkRequestForCallback() {
7155 return mNetworkRequestForCallback;
7156 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007157
James Mattisd31bdfa2020-12-23 16:37:26 -08007158 /**
7159 * Get the list of UIDs this nri applies to.
7160 */
7161 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007162 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007163 // networkCapabilities.getUids() returns a defensive copy.
7164 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007165 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7166 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007167 }
7168
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007169 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7170 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007171 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007172 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007173 }
7174
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007175 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007176 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007177 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007178 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007179 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007180 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007181 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007182 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007183 mBinder = null;
7184 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007185 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007186 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007187 mPerUidCounter = getRequestCounter(this);
7188 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007189 /**
7190 * Location sensitive data not included in pending intent. Only included in
7191 * {@link NetworkCallback}.
7192 */
7193 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007194 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007195 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007196 }
7197
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007198 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007199 @Nullable final IBinder binder,
7200 @NetworkCallback.Flag int callbackFlags,
7201 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007202 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7203 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007204 }
7205
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007206 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007207 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007208 @Nullable final IBinder binder,
7209 @NetworkCallback.Flag int callbackFlags,
7210 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007211 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007212 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007213 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007214 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007215 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007216 mBinder = binder;
7217 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007218 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007219 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007220 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007221 mPerUidCounter = getRequestCounter(this);
7222 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007223 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007224 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007225 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007226 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007227 }
7228
James Mattis3ce3d3c2021-02-09 18:18:28 -08007229 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7230 @NonNull final List<NetworkRequest> r) {
7231 super();
7232 ensureAllNetworkRequestsHaveType(r);
7233 mRequests = initializeRequests(r);
7234 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007235 final NetworkAgentInfo satisfier = nri.getSatisfier();
7236 if (null != satisfier) {
7237 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7238 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007239 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007240 // As this code creates a new NRI with a new set of requests, figure out which of
7241 // the list of requests should be the active request. It is always the first
7242 // request of the list that can be satisfied by the satisfier since the order of
7243 // requests is a priority order.
7244 // Note even in the presence of a satisfier there may not be an active request,
7245 // when the satisfier is the no-service network.
7246 NetworkRequest activeRequest = null;
7247 for (final NetworkRequest candidate : r) {
7248 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7249 activeRequest = candidate;
7250 break;
7251 }
7252 }
7253 setSatisfier(satisfier, activeRequest);
7254 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007255 mMessenger = nri.mMessenger;
7256 mBinder = nri.mBinder;
7257 mPid = nri.mPid;
7258 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007259 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007260 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007261 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007262 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007263 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007264 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007265 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007266 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007267 }
7268
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007269 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007270 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007271 }
7272
paulhue9913722021-05-26 15:19:20 +08007273 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007274 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007275 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007276 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007277 }
7278
James Mattis2516da32021-01-31 17:06:19 -08007279 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7280 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7281 // false.
7282 boolean isBeingSatisfied() {
7283 return (null != mSatisfier && null != mActiveRequest);
7284 }
7285
James Mattis3d229892020-11-16 16:46:28 -08007286 boolean isMultilayerRequest() {
7287 return mRequests.size() > 1;
7288 }
7289
James Mattis45d81842021-01-10 14:24:24 -08007290 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7291 // Creating a defensive copy to prevent the sender from modifying the list being
7292 // reflected in the return value of this method.
7293 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007294 return Collections.unmodifiableList(tempRequests);
7295 }
7296
James Mattisb1392002021-03-31 13:57:52 -07007297 void linkDeathRecipient() {
7298 if (null != mBinder) {
7299 try {
7300 mBinder.linkToDeath(this, 0);
7301 } catch (RemoteException e) {
7302 binderDied();
7303 }
7304 }
7305 }
7306
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007307 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007308 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007309 try {
7310 mBinder.unlinkToDeath(this, 0);
7311 } catch (NoSuchElementException e) {
7312 // Temporary workaround for b/194394697 pending analysis of additional logs
7313 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7314 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007315 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007316 }
7317
paulhu48291862021-07-14 14:53:57 +08007318 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7319 // Compare two preference orders.
7320 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007321 }
7322
paulhu48291862021-07-14 14:53:57 +08007323 int getPreferenceOrderForNetd() {
7324 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7325 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7326 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007327 }
paulhu48291862021-07-14 14:53:57 +08007328 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007329 }
7330
James Mattis4fce5d12020-11-12 15:53:42 -08007331 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007332 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007333 // As an immutable collection, mRequests cannot change by the time the
7334 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7335 // is acceptable. Use handleReleaseNetworkRequest and not directly
7336 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7337 // the app already unregistered the request.
7338 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7339 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007340 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007341
James Mattis4fce5d12020-11-12 15:53:42 -08007342 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007343 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007344 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7345 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007346 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007347 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007348 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007349 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007350 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007351 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007352 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007353 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007354 }
7355
Junyu Lai00d92df2022-07-05 11:01:52 +08007356 // Keep backward compatibility since the ServiceSpecificException is used by
7357 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7358 public static class RequestInfoPerUidCounter extends PerUidCounter {
7359 RequestInfoPerUidCounter(int maxCountPerUid) {
7360 super(maxCountPerUid);
7361 }
7362
7363 @Override
7364 public synchronized void incrementCountOrThrow(int uid) {
7365 try {
7366 super.incrementCountOrThrow(uid);
7367 } catch (IllegalStateException e) {
7368 throw new ServiceSpecificException(
7369 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7370 "Uid " + uid + " exceeded its allotted requests limit");
7371 }
7372 }
7373
7374 @Override
7375 public synchronized void decrementCountOrThrow(int uid) {
7376 throw new UnsupportedOperationException("Use decrementCount instead.");
7377 }
7378
7379 public synchronized void decrementCount(int uid) {
7380 try {
7381 super.decrementCountOrThrow(uid);
7382 } catch (IllegalStateException e) {
7383 logwtf("Exception when decrement per uid request count: ", e);
7384 }
7385 }
7386 }
7387
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007388 // This checks that the passed capabilities either do not request a
7389 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007390 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007391 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007392 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007393 throw new SecurityException("Insufficient permissions to request a specific SSID");
7394 }
paulhu1a407652019-03-22 16:35:06 +08007395
7396 if (nc.hasSignalStrength()
7397 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7398 throw new SecurityException(
7399 "Insufficient permissions to request a specific signal strength");
7400 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007401 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007402
junyulai2217bec2021-04-14 23:33:31 +08007403 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007404 enforceNetworkFactoryPermission();
7405 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007406 }
7407
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007408 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007409 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007410 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007411 // mNetworkRequests may contain the same value multiple times in case of
7412 // multilayer requests. It won't matter in this case because the thresholds
7413 // will then be the same and be deduplicated as they enter the `thresholds` set.
7414 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007415 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7416 for (final NetworkRequest req : nri.mRequests) {
7417 if (req.networkCapabilities.hasSignalStrength()
7418 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7419 thresholds.add(req.networkCapabilities.getSignalStrength());
7420 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007421 }
7422 }
7423 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007424 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007425 }
7426
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007427 private void updateSignalStrengthThresholds(
7428 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007429 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007430
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007431 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007432 String detail;
7433 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7434 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7435 } else {
7436 detail = reason;
7437 }
7438 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007439 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007440 }
7441
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007442 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007443 }
7444
Chalard Jeandd421992021-12-16 23:16:02 +09007445 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007446 if (nc == null) {
7447 return;
7448 }
7449 NetworkSpecifier ns = nc.getNetworkSpecifier();
7450 if (ns == null) {
7451 return;
7452 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007453 if (ns instanceof MatchAllNetworkSpecifier) {
7454 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7455 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007456 }
7457
Chalard Jeandd421992021-12-16 23:16:02 +09007458 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007459 ensureValidNetworkSpecifier(nc);
7460 if (nc.isPrivateDnsBroken()) {
7461 throw new IllegalArgumentException("Can't request broken private DNS");
7462 }
Chalard Jeande665262022-02-25 16:12:12 +09007463 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007464 throw new IllegalArgumentException("Can't request access UIDs");
7465 }
lucasline117e2e2019-10-22 18:27:33 +08007466 }
7467
Chalard Jeandd421992021-12-16 23:16:02 +09007468 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7469 ensureListenableCapabilities(nc);
7470 final String badCapability = nc.describeFirstNonRequestableCapability();
7471 if (badCapability != null) {
7472 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7473 }
7474 }
7475
Chiachang Wang3bc52762021-11-25 14:17:57 +08007476 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7477 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007478 private boolean isTargetSdkAtleast(int version, int callingUid,
7479 @NonNull String callingPackageName) {
7480 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007481 final PackageManager pm =
7482 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007483 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007484 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007485 if (callingVersion < version) return false;
7486 } catch (PackageManager.NameNotFoundException e) { }
7487 return true;
7488 }
7489
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007490 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007491 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007492 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007493 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007494 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007495 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007496 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7497 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007498 throw new SecurityException("Insufficient permissions to specify legacy type");
7499 }
markchienfac84a22020-03-18 21:16:15 +08007500 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007501 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007502 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007503 // Privileged callers can track the default network of another UID by passing in a UID.
7504 if (asUid != Process.INVALID_UID) {
7505 enforceSettingsPermission();
7506 } else {
7507 asUid = callingUid;
7508 }
junyulaiad010792021-01-11 16:53:38 +08007509 final NetworkRequest.Type reqType;
7510 try {
7511 reqType = NetworkRequest.Type.values()[reqTypeInt];
7512 } catch (ArrayIndexOutOfBoundsException e) {
7513 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7514 }
7515 switch (reqType) {
7516 case TRACK_DEFAULT:
7517 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007518 // is unused and will be replaced by ones appropriate for the UID (usually, the
7519 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007520 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007521 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007522 enforceAccessPermission();
7523 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007524 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007525 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007526 networkCapabilities = new NetworkCapabilities(defaultNc);
7527 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007528 case BACKGROUND_REQUEST:
7529 enforceNetworkStackOrSettingsPermission();
7530 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007531 case REQUEST:
7532 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7533 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007534 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007535 // TODO: this is incorrect. We mark the request as metered or not depending on
7536 // the state of the app when the request is filed, but we never change the
7537 // request if the app changes network state. http://b/29964605
7538 enforceMeteredApnPolicy(networkCapabilities);
7539 break;
junyulai1b1c8742021-03-12 20:05:08 +08007540 case LISTEN_FOR_BEST:
7541 enforceAccessPermission();
7542 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7543 break;
junyulaiad010792021-01-11 16:53:38 +08007544 default:
7545 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007546 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007547 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007548 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007549 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007550
junyulai1b1c8742021-03-12 20:05:08 +08007551 // Enforce FOREGROUND if the caller does not have permission to use background network.
7552 if (reqType == LISTEN_FOR_BEST) {
7553 restrictBackgroundRequestForCaller(networkCapabilities);
7554 }
7555
7556 // Set the UID range for this request to the single UID of the requester, unless the
7557 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007558 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7559 // are no visible methods to set the UIDs, an app could use reflection to try and get
7560 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007561 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007562 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7563 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007564
Etan Cohen85000162017-02-05 10:42:27 -08007565 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007566 throw new IllegalArgumentException("Bad timeout specified");
7567 }
Etan Cohen9786d922015-11-18 10:56:15 -08007568
James Mattis3ce3d3c2021-02-09 18:18:28 -08007569 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007570 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007571 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007572 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007573 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007574 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007575
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007576 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7577 // copied from the default request above. (This is necessary to ensure, for example, that
7578 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7579 // changes don't alter request matching.
7580 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7581 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007582 throw new IllegalStateException(
7583 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007584 + networkCapabilities + " vs. " + defaultNc);
7585 }
7586
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007587 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007588 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007589 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007590 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007591 }
7592 return networkRequest;
7593 }
7594
James Mattis3ce3d3c2021-02-09 18:18:28 -08007595 /**
7596 * Return the nri to be used when registering a network request. Specifically, this is used with
7597 * requests registered to track the default request. If there is currently a per-app default
7598 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7599 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007600 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7601 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007602 * @param nr the network request for the nri.
7603 * @param msgr the messenger for the nri.
7604 * @param binder the binder for the nri.
7605 * @param callingAttributionTag the calling attribution tag for the nri.
7606 * @return the nri to register.
7607 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007608 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007609 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007610 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007611 @Nullable String callingAttributionTag) {
7612 final List<NetworkRequest> requests;
7613 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7614 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007615 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007616 } else {
7617 requests = Collections.singletonList(nr);
7618 }
Roshan Pius951c0032020-12-22 15:10:42 -08007619 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007620 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007621 }
7622
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007623 private boolean shouldCheckCapabilitiesDeclaration(
7624 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7625 @NonNull final String callingPackageName) {
7626 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7627 // Only run the check if the change is enabled.
7628 if (!mDeps.isChangeEnabled(
7629 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7630 callingPackageName, user)) {
7631 return false;
7632 }
7633
7634 return networkCapabilities.hasCapability(
7635 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7636 || networkCapabilities.hasCapability(
7637 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7638 }
7639
7640 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7641 @NonNull final NetworkCapabilities networkCapabilities) {
7642 // This check is added to fix the linter error for "current min is 30", which is not going
7643 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007644 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007645 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7646 return;
7647 }
7648 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007649 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007650 try {
7651 synchronized (mSelfCertifiedCapabilityCache) {
7652 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7653 callerPackageName);
7654 if (applicationNetworkCapabilities == null) {
7655 final PackageManager packageManager = mContext.getPackageManager();
7656 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7657 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7658 callerPackageName
7659 );
7660 final XmlResourceParser parser = packageManager
7661 .getResourcesForApplication(callerPackageName)
7662 .getXml(networkSliceProperty.getResourceId());
7663 applicationNetworkCapabilities =
7664 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7665 mSelfCertifiedCapabilityCache.put(callerPackageName,
7666 applicationNetworkCapabilities);
7667 }
7668
7669 }
7670 } catch (PackageManager.NameNotFoundException ne) {
7671 throw new SecurityException(
7672 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7673 + " property");
7674 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7675 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007676 } finally {
7677 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007678 }
7679
7680 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7681 networkCapabilities);
7682 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007683 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007684 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007685 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7686 callingPackageName)) {
7687 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7688 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007689 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007690 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7691 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7692 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7693 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007694 }
junyulai96bd9fe2022-03-08 17:36:42 +08007695 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007696 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007697 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007698 }
7699 }
7700
fenglu3f357402015-03-20 11:29:56 -07007701 @Override
fenglub00f4882015-04-21 17:12:05 -07007702 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007703 enforceAccessPermission();
7704 NetworkAgentInfo nai = null;
7705 if (network == null) {
7706 return false;
7707 }
7708 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007709 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007710 }
7711 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007712 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007713 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007714 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007715 Integer uidReqs = mBandwidthRequests.get(uid);
7716 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007717 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007718 }
7719 mBandwidthRequests.put(uid, ++uidReqs);
7720 }
fenglu3f357402015-03-20 11:29:56 -07007721 return true;
7722 }
7723 return false;
7724 }
7725
Felipe Leme0a5ae422016-06-20 16:36:29 -07007726 private boolean isSystem(int uid) {
7727 return uid < Process.FIRST_APPLICATION_UID;
7728 }
fenglu3f357402015-03-20 11:29:56 -07007729
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007730 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007731 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007732 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007733 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007734 return;
7735 }
Hugo Benichi39621362017-02-11 17:04:43 +09007736 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7737 // Policy already enforced.
7738 return;
7739 }
paulhuaf50d7d2020-12-24 19:47:34 +08007740 final long ident = Binder.clearCallingIdentity();
7741 try {
7742 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7743 // If UID is restricted, don't allow them to bring up metered APNs.
7744 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7745 }
7746 } finally {
7747 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007748 }
7749 }
7750
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007751 @Override
7752 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007753 PendingIntent operation, @NonNull String callingPackageName,
7754 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007755 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007756 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007757 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007758 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007759 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007760 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007761 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007762 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007763 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007764 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7765 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007766
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007767 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007768 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007769 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7770 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007771 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007772 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7773 nri));
7774 return networkRequest;
7775 }
7776
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007777 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7778 mHandler.sendMessageDelayed(
7779 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007780 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007781 }
7782
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007783 @Override
7784 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007785 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007786 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007787 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007788 }
7789
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007790 // In order to implement the compatibility measure for pre-M apps that call
7791 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7792 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7793 // This ensures it has permission to do so.
7794 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7795 if (nc == null) {
7796 return false;
7797 }
7798 int[] transportTypes = nc.getTransportTypes();
7799 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7800 return false;
7801 }
7802 try {
7803 mContext.enforceCallingOrSelfPermission(
7804 android.Manifest.permission.ACCESS_WIFI_STATE,
7805 "ConnectivityService");
7806 } catch (SecurityException e) {
7807 return false;
7808 }
7809 return true;
7810 }
7811
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007812 @Override
7813 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007814 Messenger messenger, IBinder binder,
7815 @NetworkCallback.Flag int callbackFlags,
7816 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007817 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007818 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7819 enforceAccessPermission();
7820 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007821
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007822 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007823 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007824 Binder.getCallingPid(), callingUid, callingPackageName);
7825 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007826 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7827 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7828 // onLost and onAvailable callbacks when networks move in and out of the background.
7829 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7830 // can't request networks.
7831 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007832 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007833
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007834 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007835 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007836 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007837 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007838 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007839 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007840
7841 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7842 return networkRequest;
7843 }
7844
7845 @Override
7846 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007847 PendingIntent operation, @NonNull String callingPackageName,
7848 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007849 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007850 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007851 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7852 enforceAccessPermission();
7853 }
Chalard Jeandd421992021-12-16 23:16:02 +09007854 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007855 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007856 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007857 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007858 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007859
7860 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007861 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007862 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7863 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007864 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007865
WeiZhang1cc3f172021-06-03 19:02:04 -05007866 mHandler.sendMessage(mHandler.obtainMessage(
7867 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007868 }
7869
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007870 /** Returns the next Network provider ID. */
7871 public final int nextNetworkProviderId() {
7872 return mNextNetworkProviderId.getAndIncrement();
7873 }
7874
Erik Kline0c04b742016-07-07 16:50:58 +09007875 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007876 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007877 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007878 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007879 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007880 }
7881
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007882 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7883 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007884 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7885 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7886 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007887 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007888 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007889 return;
7890 }
7891
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007892 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7893 mNetworkProviderInfos.put(npi.messenger, npi);
7894 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007895 }
7896
7897 @Override
7898 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007899 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007900 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007901 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007902 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007903 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7904 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007905 }
7906
7907 @Override
7908 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007909 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007910 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007911 }
7912
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007913 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007914 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007915 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7916 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007917 Objects.requireNonNull(score);
7918 Objects.requireNonNull(caps);
7919 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007920 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007921 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007922 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7923 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007924 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7925 }
7926
Chalard Jeanbb902a52021-08-18 01:35:19 +09007927 private void updateOfferScore(final NetworkOffer offer) {
7928 final boolean yieldToBadWiFi =
7929 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7930 final NetworkOffer newOffer = new NetworkOffer(
7931 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7932 offer.caps, offer.callback, offer.providerId);
7933 if (offer.equals(newOffer)) return;
7934 handleRegisterNetworkOffer(newOffer);
7935 }
7936
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007937 @Override
7938 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007939 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007940 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7941 }
7942
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007943 private void handleUnregisterNetworkProvider(Messenger messenger) {
7944 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7945 if (npi == null) {
7946 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007947 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007948 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007949 // Unregister all the offers from this provider
7950 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7951 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007952 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007953 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7954 toRemove.add(noi);
7955 }
7956 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007957 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007958 handleUnregisterNetworkOffer(noi);
7959 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007960 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007961 }
7962
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007963 @Override
James Mattisf7027322020-12-13 16:28:14 -08007964 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007965 if (request.hasTransport(TRANSPORT_TEST)) {
7966 enforceNetworkFactoryOrTestNetworksPermission();
7967 } else {
7968 enforceNetworkFactoryPermission();
7969 }
James Mattisf7027322020-12-13 16:28:14 -08007970 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7971 if (nri != null) {
7972 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7973 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7974 mHandler.post(() -> handleReleaseNetworkRequest(
7975 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7976 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007977 }
7978
Paul Jensen1f567382015-02-13 14:18:39 -05007979 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7980 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007981 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007982 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007983 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007984 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007985 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007986
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007987 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007988 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007989 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007990
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007991 // UID ranges for users that are currently blocked by VPNs.
7992 // This array is accessed and iterated on multiple threads without holding locks, so its
7993 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7994 // (on the handler thread).
7995 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7996
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007997 // Must only be accessed on the handler thread
7998 @NonNull
7999 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8000
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008001 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008002 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008003
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008004 // Current OEM network preferences. This object must only be written to on the handler thread.
8005 // Since it is immutable and always non-null, other threads may read it if they only care
8006 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008007 @NonNull
8008 private OemNetworkPreferences mOemNetworkPreferences =
8009 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008010 // Current per-profile network preferences. This object follows the same threading rules as
8011 // the OEM network preferences above.
8012 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008013 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8014 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008015
lucaslin3ba7cc22022-12-19 02:35:33 +00008016 // Current VPN network preferences. This object follows the same threading rules as the OEM
8017 // network preferences above.
8018 @NonNull
8019 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8020 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8021
paulhu51f77dc2021-06-07 02:34:20 +00008022 // A set of UIDs that should use mobile data preferentially if available. This object follows
8023 // the same threading rules as the OEM network preferences above.
8024 @NonNull
8025 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8026
James Mattiscb1e0362021-04-06 17:07:42 -07008027 // OemNetworkPreferences activity String log entries.
8028 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8029 @NonNull
8030 private final LocalLog mOemNetworkPreferencesLogs =
8031 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8032
James Mattis02220e22021-03-13 19:27:21 -08008033 /**
8034 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8035 * @param packageName the package name to check existence of a mapping for.
8036 * @return true if a mapping exists, false otherwise
8037 */
8038 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8039 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8040 }
8041
James Mattise3ef1912020-12-20 11:09:58 -08008042 // The always-on request for an Internet-capable network that apps without a specific default
8043 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008044 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008045 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008046 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008047 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008048 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008049 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008050 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008051
James Mattisd31bdfa2020-12-23 16:37:26 -08008052 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8053 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8054 }
8055
8056 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008057 * Return the default network request currently tracking the given uid.
8058 * @param uid the uid to check.
8059 * @return the NetworkRequestInfo tracking the given uid.
8060 */
8061 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008062 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008063 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008064 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008065 // Checking the first request is sufficient as only multilayer requests will have more
8066 // than one request and for multilayer, all requests will track the same uids.
8067 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008068 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008069 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008070 highestPriorityNri = nri;
8071 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008072 }
8073 }
paulhuaa0743d2021-05-26 21:56:03 +08008074 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008075 }
8076
8077 /**
8078 * Get a copy of the network requests of the default request that is currently tracking the
8079 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008080 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8081 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008082 * @param requestorUid the uid to check the default for.
8083 * @param requestorPackageName the requestor's package name.
8084 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8085 */
8086 @NonNull
8087 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008088 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008089 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008090 getDefaultRequestTrackingUid(asUid).mRequests,
8091 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008092 }
8093
8094 /**
8095 * Copy the given nri's NetworkRequest collection.
8096 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008097 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8098 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008099 * @param requestorUid the uid to set on the copied collection.
8100 * @param requestorPackageName the package name to set on the copied collection.
8101 * @return the copied NetworkRequest collection.
8102 */
8103 @NonNull
8104 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008105 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8106 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008107 final List<NetworkRequest> requests = new ArrayList<>();
8108 for (final NetworkRequest nr : requestsToCopy) {
8109 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008110 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008111 nr.legacyType, nextNetworkRequestId(), nr.type));
8112 }
8113 return requests;
8114 }
8115
8116 @NonNull
8117 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008118 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8119 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008120 // These capabilities are for a TRACK_DEFAULT callback, so:
8121 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8122 // mDefaultRequest and a per-UID default request.
8123 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008124 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008125 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008126 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8127 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008128 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008129 restrictRequestUidsForCallerAndSetRequestorInfo(
8130 netCap, requestorUid, requestorPackageName);
8131 return netCap;
8132 }
8133
8134 /**
8135 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8136 * @param nr the network request to check for equality against.
8137 * @return the nri if one exists, null otherwise.
8138 */
8139 @Nullable
8140 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8141 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8142 if (nri.getNetworkRequestForCallback().equals(nr)) {
8143 return nri;
8144 }
8145 }
8146 return null;
8147 }
8148
8149 /**
8150 * Check if an nri is currently being managed by per-app default networking.
8151 * @param nri the nri to check.
8152 * @return true if this nri is currently being managed by per-app default networking.
8153 */
8154 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8155 // nri.mRequests.get(0) is only different from the original request filed in
8156 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8157 // functionality therefore if these two don't match, it means this particular nri is
8158 // currently being managed by a per-app default.
8159 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8160 }
8161
8162 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008163 * Determine if an nri is a managed default request that disallows default networking.
8164 * @param nri the request to evaluate
8165 * @return true if device-default networking is disallowed
8166 */
8167 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8168 // Check if this nri is a managed default that supports the default network at its
8169 // lowest priority request.
8170 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8171 final NetworkCapabilities lowestPriorityNetCap =
8172 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8173 return isPerAppDefaultRequest(nri)
8174 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8175 lowestPriorityNetCap));
8176 }
8177
Erik Kline05f2b402015-04-30 12:58:40 +09008178 // Request used to optionally keep mobile data active even when higher
8179 // priority networks like Wi-Fi are active.
8180 private final NetworkRequest mDefaultMobileDataRequest;
8181
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008182 // Request used to optionally keep wifi data active even when higher
8183 // priority networks like ethernet are active.
8184 private final NetworkRequest mDefaultWifiRequest;
8185
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008186 // Request used to optionally keep vehicle internal network always active
8187 private final NetworkRequest mDefaultVehicleRequest;
8188
James Mattisd31bdfa2020-12-23 16:37:26 -08008189 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8190 // network with no service. This NAI should never be matched against, nor should any public API
8191 // ever return the associated network. For this reason, this NAI is not in the list of available
8192 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8193 // default requests that don't support using the device default network which will ultimately
8194 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8195 @VisibleForTesting
8196 final NetworkAgentInfo mNoServiceNetwork;
8197
Chalard Jean5b409c72021-02-04 13:12:59 +09008198 // The NetworkAgentInfo currently satisfying the default request, if any.
8199 private NetworkAgentInfo getDefaultNetwork() {
8200 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008201 }
8202
James Mattis2516da32021-01-31 17:06:19 -08008203 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008204 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008205 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8206 // Currently, all network requests will have the same uids therefore checking the first
8207 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008208 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008209 if (null == uids) {
8210 continue;
8211 }
8212 for (final UidRange range : uids) {
8213 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008214 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008215 highestPriorityNri = nri;
8216 }
James Mattis2516da32021-01-31 17:06:19 -08008217 }
8218 }
8219 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008220 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008221 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008222 }
8223
Varun Ananddf569952019-02-06 10:13:38 -08008224 @Nullable
8225 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8226 return nai != null ? nai.network : null;
8227 }
8228
8229 private void ensureRunningOnConnectivityServiceThread() {
8230 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8231 throw new IllegalStateException(
8232 "Not running on ConnectivityService thread: "
8233 + Thread.currentThread().getName());
8234 }
8235 }
8236
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008237 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008238 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8239 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008240 }
8241
Chalard Jean29d06db2018-05-02 21:14:54 +09008242 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008243 * Returns whether local agents are supported on this device.
8244 *
8245 * Local agents are supported from U on TVs, and from V on all devices.
8246 */
8247 @VisibleForTesting
8248 public boolean areLocalAgentsSupported() {
8249 final PackageManager pm = mContext.getPackageManager();
8250 // Local agents are supported starting on U on TVs and on V on everything else.
8251 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8252 }
8253
8254 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008255 * Register a new agent with ConnectivityService to handle a network.
8256 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008257 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008258 * @param networkInfo the initial info associated with this network. It can be updated later :
8259 * see {@link #updateNetworkInfo}.
8260 * @param linkProperties the initial link properties of this network. They can be updated
8261 * later : see {@link #updateLinkProperties}.
8262 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008263 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008264 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008265 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008266 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008267 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008268 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008269 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008270 public Network registerNetworkAgent(INetworkAgent na,
8271 NetworkInfo networkInfo,
8272 LinkProperties linkProperties,
8273 NetworkCapabilities networkCapabilities,
8274 @NonNull NetworkScore initialScore,
8275 @Nullable LocalNetworkConfig localNetworkConfig,
8276 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008277 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008278 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8279 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8280 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008281 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008282 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008283 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008284 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008285 } else {
8286 enforceNetworkFactoryPermission();
8287 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008288 final boolean hasLocalCap =
8289 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8290 if (hasLocalCap && !areLocalAgentsSupported()) {
8291 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8292 throw new IllegalArgumentException("Local agents are not supported in this version");
8293 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008294 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8295 if (hasLocalCap != hasLocalNetworkConfig) {
8296 throw new IllegalArgumentException(null != localNetworkConfig
8297 ? "Only local network agents can have a LocalNetworkConfig"
8298 : "Local network agents must have a LocalNetworkConfig"
8299 );
8300 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008301
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008302 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008303 final long token = Binder.clearCallingIdentity();
8304 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008305 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008306 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8307 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008308 } finally {
8309 Binder.restoreCallingIdentity(token);
8310 }
8311 }
8312
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008313 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008314 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008315 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8316 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008317 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008318
Chalard Jeandbc46952022-02-02 00:14:18 +09008319 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8320 // and mutate them at any time.
8321 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8322 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8323 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008324 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008325
Chalard Jean366c5252022-01-25 18:27:53 +09008326 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008327 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008328 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8329 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008330 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008331 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008332 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8333 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8334 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008335
Chalard Jeandbc46952022-02-02 00:14:18 +09008336 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008337 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008338 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008339 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008340 mDeps.getNetworkStack().makeNetworkMonitor(
8341 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008342 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8343 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008344 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008345 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008346 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008347 }
8348
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008349 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008350 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008351 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008352 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008353 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008354 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8355 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8356 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008357
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008358 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008359
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008360 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008361 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008362 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008363 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008364
8365 try {
8366 networkMonitor.start();
8367 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008368 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008369 }
Chalard Jean366c5252022-01-25 18:27:53 +09008370
Chalard Jean1e4c2182023-10-06 18:45:53 +09008371 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008372 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008373 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008374 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008375 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008376 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008377 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008378 }
8379
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008380 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8381 @NonNull public final NetworkOffer offer;
8382
8383 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8384 this.offer = offer;
8385 }
8386
8387 @Override
8388 public void binderDied() {
8389 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8390 }
8391 }
8392
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008393 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8394 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8395 if (npi.providerId == providerId) return true;
8396 }
8397 return false;
8398 }
8399
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008400 /**
8401 * Register or update a network offer.
8402 * @param newOffer The new offer. If the callback member is the same as an existing
8403 * offer, it is an update of that offer.
8404 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008405 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008406 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8407 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008408 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008409 // This may actually happen if a provider updates its score or registers and then
8410 // immediately unregisters. The offer would still be in the handler queue, but the
8411 // provider would have been removed.
8412 if (DBG) log("Received offer from an unregistered provider");
8413 return;
8414 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008415 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8416 if (null != existingOffer) {
8417 handleUnregisterNetworkOffer(existingOffer);
8418 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008419 if (DBG) {
8420 // handleUnregisterNetworkOffer has already logged the old offer
8421 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8422 }
8423 } else {
8424 if (DBG) {
8425 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8426 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008427 }
8428 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8429 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008430 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008431 } catch (RemoteException e) {
8432 noi.binderDied();
8433 return;
8434 }
8435 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008436 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008437 }
8438
8439 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8440 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008441 if (DBG) {
8442 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8443 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008444
8445 // If the provider removes the offer and dies immediately afterwards this
8446 // function may be called twice in a row, but the array will no longer contain
8447 // the offer.
8448 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008449 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008450 }
8451
8452 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8453 @NonNull final INetworkOfferCallback callback) {
8454 ensureRunningOnConnectivityServiceThread();
8455 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008456 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008457 }
8458 return null;
8459 }
8460
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008461 /**
8462 * Called when receiving LinkProperties directly from a NetworkAgent.
8463 * Stores into |nai| any data coming from the agent that might also be written to the network's
8464 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8465 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008466 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008467 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008468 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8469 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008470 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008471 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008472 }
8473
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008474 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008475 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008476 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008477
Lorenzo Colittid523d142020-04-01 20:16:30 +09008478 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8479 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8480 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008481 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008482
Suprabh Shukla1e312032023-01-24 03:36:37 -08008483 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008484
8485 // update filtering rules, need to happen after the interface update so netd knows about the
8486 // new interface (the interface name -> index map becomes initialized)
8487 updateVpnFiltering(newLp, oldLp, networkAgent);
8488
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008489 updateMtu(newLp, oldLp);
8490 // TODO - figure out what to do for clat
8491// for (LinkProperties lp : newLp.getStackedLinks()) {
8492// updateMtu(lp, null);
8493// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008494 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008495 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008496 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8497 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008498
Erik Klineb9888902016-04-05 13:30:49 +09008499 updateRoutes(newLp, oldLp, netId);
8500 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008501 // Make sure LinkProperties represents the latest private DNS status.
8502 // This does not need to be done before updateDnses because the
8503 // LinkProperties are not the source of the private DNS configuration.
8504 // updateDnses will fetch the private DNS configuration from DnsManager.
8505 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008506
Chalard Jean5b409c72021-02-04 13:12:59 +09008507 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008508 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008509 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008510 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008511 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008512
8513 updateWakeOnLan(newLp);
8514
Hai Shalome58bdc62021-01-11 18:45:34 -08008515 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8516 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8517 // does, it needs to be merged here.
8518 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8519 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008520
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008521 // TODO - move this check to cover the whole function
8522 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008523 synchronized (networkAgent) {
8524 networkAgent.linkProperties = newLp;
8525 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008526 // Start or stop DNS64 detection and 464xlat according to network state.
8527 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008528 // Notify NSS when relevant events happened. Currently, NSS only cares about
8529 // interface changed to update clat interfaces accounting.
8530 final boolean interfacesChanged = oldLp == null
8531 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8532 if (interfacesChanged) {
8533 notifyIfacesChangedForNetworkStats();
8534 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008535 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8536 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008537 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008538 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008539
8540 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008541 }
8542
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008543 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8544 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8545 }
8546
Hai Shalome58bdc62021-01-11 18:45:34 -08008547 /**
8548 * @param naData captive portal data from NetworkAgent
8549 * @param apiData captive portal data from capport API
8550 */
8551 @Nullable
8552 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8553 CaptivePortalData apiData) {
8554 if (naData == null || apiData == null) {
8555 return naData == null ? apiData : naData;
8556 }
8557 final CaptivePortalData.Builder captivePortalBuilder =
8558 new CaptivePortalData.Builder(naData);
8559
8560 if (apiData.isCaptive()) {
8561 captivePortalBuilder.setCaptive(true);
8562 }
8563 if (apiData.isSessionExtendable()) {
8564 captivePortalBuilder.setSessionExtendable(true);
8565 }
8566 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8567 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8568 // otherwise data would be inconsistent. Prefer the capport API info if present,
8569 // as it can generally be refreshed more often.
8570 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8571 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8572 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8573 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8574 // No source has time / bytes remaining information: surface the newest refresh time
8575 // for other fields
8576 captivePortalBuilder.setRefreshTime(
8577 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8578 }
8579
Hai Shalom7c6ab402021-02-04 19:34:06 -08008580 // Prioritize the user portal URL from the network agent if the source is authenticated.
8581 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8582 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8583 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8584 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008585 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008586 // Prioritize the venue information URL from the network agent if the source is
8587 // authenticated.
8588 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8589 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8590 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8591 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008592 }
8593 return captivePortalBuilder.build();
8594 }
8595
Suprabh Shukla53e16392023-04-26 18:47:36 -07008596 @VisibleForTesting
8597 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008598 // This needs to be kept in sync and backwards compatible with the decoding logic in
8599 // NetdEventListenerService, which is non-mainline code.
8600 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8601 }
8602
Suprabh Shukla75642282023-04-25 23:15:43 -07008603 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8604 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8605 return true;
8606 }
8607 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8608 return true;
8609 }
8610 return false;
8611 }
8612
Suprabh Shukla1e312032023-01-24 03:36:37 -08008613 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008614 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008615 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008616 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008617 return;
8618 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008619
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008620 // Mask/mark of zero will not detect anything interesting.
8621 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008622 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008623 return;
8624 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008625
Suprabh Shukla1e312032023-01-24 03:36:37 -08008626 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008627 try {
8628 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008629 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008630 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008631 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008632 }
8633 } catch (Exception e) {
8634 loge("Exception modifying wakeup packet monitoring: " + e);
8635 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008636 }
8637
Junyu Lai970963e2022-10-25 15:46:47 +08008638 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008639 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008640 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008641 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008642 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008643 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008644 for (final String iface : interfaceDiff.added) {
8645 try {
8646 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008647 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008648 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008649 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008650 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008651 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008652 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008653 }
Paul Jensenbff73492014-04-28 10:33:11 -04008654 }
8655 }
Chalard Jean9589e722019-11-19 19:03:53 +09008656 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008657 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008658 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008659 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008660 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008661 } catch (Exception e) {
8662 loge("Exception removing interface: " + e);
8663 }
8664 }
8665 }
8666
Paul Jensene0fd4a82014-08-06 15:51:33 -04008667 /**
8668 * Have netd update routes from oldLp to newLp.
8669 * @return true if routes changed between oldLp and newLp
8670 */
Junyu Lai970963e2022-10-25 15:46:47 +08008671 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8672 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008673 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008674 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8675 new CompareOrUpdateResult<>(
8676 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008677 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008678 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008679
8680 // add routes before removing old in case it helps with continuous connectivity
8681
Chalard Jean9dd11612018-06-04 16:52:49 +09008682 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008683 for (RouteInfo route : routeDiff.added) {
8684 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008685 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008686 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008687 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008688 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008689 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008690 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008691 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008692 }
8693 }
8694 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008695 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008696 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008697 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008698 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008699 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008700 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008701 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008702 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008703 }
8704 }
8705
8706 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008707 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008708 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008709 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008710 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008711 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008712 }
8713 }
Tyler Weare4314862019-12-05 14:55:30 -08008714
8715 for (RouteInfo route : routeDiff.updated) {
8716 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8717 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008718 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008719 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008720 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008721 }
8722 }
8723 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8724 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008725 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008726
Junyu Lai970963e2022-10-25 15:46:47 +08008727 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8728 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008729 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8730 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008731 }
Erik Klineb9888902016-04-05 13:30:49 +09008732
Erik Kline31b4a9e2018-01-11 21:07:29 +09008733 if (DBG) {
8734 final Collection<InetAddress> dnses = newLp.getDnsServers();
8735 log("Setting DNS servers for network " + netId + " to " + dnses);
8736 }
Erik Klineb9888902016-04-05 13:30:49 +09008737 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008738 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008739 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008740 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008741 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008742 }
Erik Kline54e35c02017-04-07 15:29:29 +09008743 }
8744
Junyu Lai970963e2022-10-25 15:46:47 +08008745 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8746 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008747 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8748 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008749 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8750 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008751
8752 if (!wasFiltering && !needsFiltering) {
8753 // Nothing to do.
8754 return;
8755 }
8756
8757 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8758 // Nothing changed.
8759 return;
8760 }
8761
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008762 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008763 if (ranges == null || ranges.isEmpty()) {
8764 return;
8765 }
8766
Qingxi Libb8da982020-01-17 17:54:27 -08008767 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008768 // TODO: this create a window of opportunity for apps to receive traffic between the time
8769 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008770 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008771 // old rules are being removed.
8772 if (wasFiltering) {
8773 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8774 }
8775 if (needsFiltering) {
8776 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8777 }
8778 }
8779
Valentin Iftime9fa35092019-09-24 13:32:13 +02008780 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008781 if (mWolSupportedInterfaces == null) {
8782 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008783 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008784 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008785 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8786 }
8787
Luke Huangb913c812018-08-24 20:33:16 +08008788 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008789 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008790 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008791 }
8792 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008793 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008794 }
Luke Huangb913c812018-08-24 20:33:16 +08008795 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008796 }
8797
Chalard Jean62edfd82019-12-02 18:39:29 +09008798 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8799 @NonNull final NetworkCapabilities newNc) {
8800 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8801 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008802 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008803 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008804 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008805 } catch (RemoteException | ServiceSpecificException e) {
8806 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008807 }
8808 }
8809 }
8810
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008811 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008812 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008813 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008814 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008815 underlyingNetworks = underlyingNetworksOrDefault(
8816 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008817 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008818 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8819 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008820 // metered if any underlying is metered, or originally declared metered by the agent.
8821 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008822 boolean roaming = false; // roaming if any underlying is roaming
8823 boolean congested = false; // congested if any underlying is congested
8824 boolean suspended = true; // suspended if all underlying are suspended
8825
8826 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008827 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008828 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008829 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008830 for (Network underlyingNetwork : underlyingNetworks) {
8831 final NetworkAgentInfo underlying =
8832 getNetworkAgentInfoForNetwork(underlyingNetwork);
8833 if (underlying == null) continue;
8834
8835 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8836 hadUnderlyingNetworks = true;
8837 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008838 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008839 }
8840
8841 // Merge capabilities of this underlying network. For bandwidth, assume the
8842 // worst case.
8843 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8844 underlyingCaps.getLinkDownstreamBandwidthKbps());
8845 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8846 underlyingCaps.getLinkUpstreamBandwidthKbps());
8847 // If this underlying network is metered, the VPN is metered (it may cost money
8848 // to send packets on this network).
8849 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8850 // If this underlying network is roaming, the VPN is roaming (the billing structure
8851 // is different than the usual, local one).
8852 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8853 // If this underlying network is congested, the VPN is congested (the current
8854 // condition of the network affects the performance of this network).
8855 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8856 // If this network is not suspended, the VPN is not suspended (the VPN
8857 // is able to transfer some data).
8858 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008859 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008860 }
8861 }
8862 if (!hadUnderlyingNetworks) {
8863 // No idea what the underlying networks are; assume reasonable defaults
8864 metered = true;
8865 roaming = false;
8866 congested = false;
8867 suspended = false;
8868 }
8869
Chalard Jean1d420b32022-10-12 16:39:37 +09008870 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008871 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8872 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8873 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8874 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8875 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8876 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008877 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008878 }
8879
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008880 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008881 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8882 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8883 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008884 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008885 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008886 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008887 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008888 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8889 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008890 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008891 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008892 if (nai.everConnected()
8893 && !nai.isVPN()
8894 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008895 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008896 // does not cause any request (that is not a listen) currently matching that agent to
8897 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008898 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008899 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008900 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008901 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008902 }
8903
Paul Jensen53f08952015-06-16 14:27:36 -04008904 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008905 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008906 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008907 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008908 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008909 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008910 }
Chalard Jean254bd162022-08-25 13:04:51 +09008911 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008912 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008913 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008914 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008915 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008916 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008917 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008918 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008919 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008920 }
Chalard Jean254bd162022-08-25 13:04:51 +09008921 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008922 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8923 } else {
8924 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8925 }
lucasline117e2e2019-10-22 18:27:33 +08008926 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008927
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008928 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008929 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8930 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008931 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008932 }
8933
Lorenzo Colittibd079452021-07-02 11:47:57 +09008934 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008935 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008936 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008937 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008938 }
8939
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008940 return newNc;
8941 }
8942
Lorenzo Colitti44840702021-01-11 22:27:57 +09008943 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8944 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8945 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8946 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8947 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8948 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8949 if (prevSuspended != suspended) {
8950 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8951 // onResumed have been removed.
8952 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8953 : ConnectivityManager.CALLBACK_RESUMED);
8954 }
8955 if (prevSuspended != suspended || prevRoaming != roaming) {
8956 // updateNetworkInfo will mix in the suspended info from the capabilities and
8957 // take appropriate action for the network having possibly changed state.
8958 updateNetworkInfo(nai, nai.networkInfo);
8959 }
8960 }
8961
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008962 /**
8963 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8964 *
8965 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8966 * capabilities we manage and store in {@code nai}, such as validated status and captive
8967 * portal status)
8968 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8969 * potentially triggers rematches.
8970 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8971 * change.)
8972 *
8973 * @param oldScore score of the network before any of the changes that prompted us
8974 * to call this function.
8975 * @param nai the network having its capabilities updated.
8976 * @param nc the new network capabilities.
8977 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008978 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008979 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008980 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008981 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008982 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8983 if (null != differences) {
8984 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8985 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008986 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008987 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008988
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008989 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008990 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008991 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008992
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008993 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008994 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8995 // the change we're processing can't affect any requests, it can only affect the listens
8996 // on this network. We might have been called by rematchNetworkAndRequests when a
8997 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008998 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008999 } else {
9000 // If the requestable capabilities have changed or the score changed, we can't have been
9001 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009002 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009003 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009004 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009005 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009006
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009007 final boolean oldMetered = prevNc.isMetered();
9008 final boolean newMetered = newNc.isMetered();
9009 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009010
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009011 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009012 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9013 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009014 }
junyulaif2c67e42018-08-07 19:50:45 +08009015
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009016 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9017 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009018
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009019 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009020 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009021 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009022 }
9023
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009024 // This network might have been underlying another network. Propagate its capabilities.
9025 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009026
Ken Chen5a35cf92023-10-07 07:54:22 +08009027 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009028 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009029 }
lucaslin53e8a262021-06-08 01:43:59 +08009030
9031 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009032 }
9033
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009034 /** Convenience method to update the capabilities for a given network. */
9035 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009036 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009037 }
9038
Chalard Jean1e4c2182023-10-06 18:45:53 +09009039 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009040 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009041 @Nullable final LocalNetworkConfig oldConfig,
9042 @NonNull final LocalNetworkConfig newConfig) {
9043 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009044 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9045 return;
9046 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009047
Chalard Jean4fe23392023-10-17 23:02:27 +09009048 if (VDBG) {
9049 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9050 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009051 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
9052 // TODO : apply the diff for multicast routing.
9053 configBuilder.setUpstreamMulticastRoutingConfig(
9054 newConfig.getUpstreamMulticastRoutingConfig());
9055 configBuilder.setDownstreamMulticastRoutingConfig(
9056 newConfig.getDownstreamMulticastRoutingConfig());
9057
9058 final NetworkRequest oldRequest =
9059 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9060 final NetworkCapabilities oldCaps =
9061 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9062 final NetworkRequestInfo oldNri =
9063 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9064 final NetworkAgentInfo oldSatisfier =
9065 null == oldNri ? null : oldNri.getSatisfier();
9066 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9067 final NetworkCapabilities newCaps =
9068 (null == newRequest) ? null : newRequest.networkCapabilities;
9069 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9070 if (null != oldRequest && requestUpdated) {
9071 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9072 if (null == newRequest && null != oldSatisfier) {
9073 // If there is an old satisfier, but no new request, then remove the old upstream.
9074 removeLocalNetworkUpstream(nai, oldSatisfier);
9075 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009076 // When there is a new request, the rematch sees the new request and sends the
9077 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9078 // But here there is no new request, so the rematch won't see anything. Send
9079 // callbacks to apps now to tell them about the loss of upstream.
9080 notifyNetworkCallbacks(nai,
9081 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009082 return;
9083 }
9084 }
9085 if (null != newRequest && requestUpdated) {
9086 // File the new request if :
9087 // - it has changed (requestUpdated), or
9088 // - it's the first time this local info (null == oldConfig)
9089 // is updated and the request has not been filed yet.
9090 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9091 // upstream (the best) but never request it to be brought up.
9092 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9093 nextNetworkRequestId(), LISTEN_FOR_BEST);
9094 configBuilder.setUpstreamSelector(nr);
9095 final NetworkRequestInfo nri = new NetworkRequestInfo(
9096 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9097 0 /* callbackFlags */, null /* attributionTag */);
9098 if (null != oldSatisfier) {
9099 // Set the old satisfier in the new NRI so that the rematch will see any changes
9100 nri.setSatisfier(oldSatisfier, nr);
9101 }
9102 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009103 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9104 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9105 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009106 handleRegisterNetworkRequest(nri);
9107 } else {
9108 configBuilder.setUpstreamSelector(oldRequest);
9109 nai.localNetworkConfig = configBuilder.build();
9110 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009111 }
9112
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009113 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009114 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009115 *
9116 * Ingress interface filtering enforces that all apps under the given network can only receive
9117 * packets from the network's interface (and loopback). This is important for VPNs because
9118 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9119 * non-VPN interfaces.
9120 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009121 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009122 * 1. the network is an app VPN (not legacy VPN)
9123 * 2. the VPN does not allow bypass
9124 * 3. the VPN is fully-routed
9125 * 4. the VPN interface is non-null
9126 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009127 * @see INetd#firewallAddUidInterfaceRules
9128 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009129 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009130 @Nullable
9131 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009132 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009133 if (nc == null || lp == null) return null;
9134 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009135 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009136 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009137 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009138 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009139 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009140 && !lp.hasExcludeRoute()) {
9141 return lp.getInterfaceName();
9142 }
9143 return null;
9144 }
9145
9146 /**
9147 * Returns whether we need to set interface filtering rule or not
9148 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009149 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009150 String isolationIface) {
9151 // Allow rules are always needed if VPN isolation is enabled.
9152 if (isolationIface != null) return true;
9153
9154 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9155 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9156 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009157 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009158 }
9159
Chiachang Wang28afaff2020-12-10 22:24:47 +08009160 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9161 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9162 int index = 0;
9163 for (UidRange range : ranges) {
9164 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9165 index++;
9166 }
9167 return stableRanges;
9168 }
9169
Chalard Jeane6c95272022-01-25 21:04:21 +09009170 private static UidRangeParcel[] intsToUidRangeStableParcels(
9171 final @NonNull ArraySet<Integer> uids) {
9172 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9173 int index = 0;
9174 for (int uid : uids) {
9175 stableRanges[index] = new UidRangeParcel(uid, uid);
9176 index++;
9177 }
9178 return stableRanges;
9179 }
9180
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009181 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9182 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9183 for (int i = 0; i < ranges.length; i++) {
9184 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9185 }
9186 return stableRanges;
9187 }
9188
Motomu Utsumi93a22182023-03-16 17:04:21 +09009189 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009190 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009191 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9192 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009193 if (mDeps.isAtLeastU()) {
9194 final Set<Integer> exemptUidSet = new ArraySet<>();
9195 for (final int uid: exemptUids) {
9196 exemptUidSet.add(uid);
9197 }
9198 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9199 } else {
9200 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9201 }
Ken Chen5e65a852020-12-24 12:59:10 +08009202 } catch (Exception e) {
9203 loge("Exception in socket destroy: ", e);
9204 }
9205 }
9206 }
9207
paulhuaa0743d2021-05-26 21:56:03 +08009208 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009209 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009210 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9211 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9212 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009213 exemptUids[0] = VPN_UID;
9214 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009215 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9216
Motomu Utsumi6345e462023-03-13 13:24:50 +09009217 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009218 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009219 try {
9220 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009221 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009222 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009223 } else {
paulhu0e79d952021-06-09 16:11:35 +08009224 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009225 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009226 }
9227 } catch (Exception e) {
9228 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9229 " on netId " + nai.network.netId + ". " + e);
9230 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009231 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009232 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009233 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009234
lucaslin53e8a262021-06-08 01:43:59 +08009235 private boolean isProxySetOnAnyDefaultNetwork() {
9236 ensureRunningOnConnectivityServiceThread();
9237 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9238 final NetworkAgentInfo nai = nri.getSatisfier();
9239 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9240 return true;
9241 }
9242 }
9243 return false;
9244 }
9245
9246 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9247 NetworkCapabilities newNc) {
9248 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9249 // the proxy might be changed since the default network satisfied by the apps might also
9250 // changed.
9251 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9252 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009253 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9254 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009255 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009256 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9257 mProxyTracker.sendProxyBroadcast();
9258 }
9259 }
9260
Chalard Jeane6c95272022-01-25 21:04:21 +09009261 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9262 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009263 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9264 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009265 if (null == prevRanges) prevRanges = new ArraySet<>();
9266 if (null == newRanges) newRanges = new ArraySet<>();
9267 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9268
9269 prevRanges.removeAll(newRanges);
9270 newRanges.removeAll(prevRangesCopy);
9271
9272 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009273 // When updating the VPN uid routing rules, add the new range first then remove the old
9274 // range. If old range were removed first, there would be a window between the old
9275 // range being removed and the new range being added, during which UIDs contained
9276 // in both ranges are not subject to any VPN routing rules. Adding new range before
9277 // removing old range works because, unlike the filtering rules below, it's possible to
9278 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009279 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9280 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9281 // [1-5] & [1-2],[4-5] == [3]
9282 // Then we can do:
9283 // maybeCloseSockets([3])
9284 // mNetd.networkAddUidRanges([1-2],[4-5])
9285 // mNetd.networkRemoveUidRanges([1-5])
9286 // maybeCloseSockets([3])
9287 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9288 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009289 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009290 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009291 }
9292 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009293 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009294 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009295 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9296 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009297 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9298 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009299 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009300 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009301 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9302 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9303 // were added first and then newRanges got removed later, there would be only one uid
9304 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9305 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9306 // Note that this is in contrast with the (more robust) update of VPN routing rules
9307 // above, where the addition of new ranges happens before the removal of old ranges.
9308 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9309 // to be removed will never overlap with the new range to be added.
9310 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009311 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9312 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009313 }
9314 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009315 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009316 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009317 } catch (Exception e) {
9318 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009319 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009320 }
9321 }
9322
Chalard Jeande665262022-02-25 16:12:12 +09009323 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009324 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9325 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009326 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9327 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009328 if (prevEmpty && newEmpty) return;
9329
9330 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009331 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009332 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009333 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009334
9335 if (prevUids.equals(newUids)) return;
9336
9337 // This implementation is very simple and vastly faster for sets of Integers than
9338 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9339 // a key computed from the value and has storage for that.
9340 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9341 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9342 toRemove.removeAll(newUids);
9343 toAdd.removeAll(prevUids);
9344
9345 try {
9346 if (!toAdd.isEmpty()) {
9347 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9348 nai.network.netId,
9349 intsToUidRangeStableParcels(toAdd),
9350 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9351 }
9352 if (!toRemove.isEmpty()) {
9353 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9354 nai.network.netId,
9355 intsToUidRangeStableParcels(toRemove),
9356 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9357 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009358 } catch (ServiceSpecificException e) {
9359 // Has the interface disappeared since the network was built ?
9360 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009361 } catch (RemoteException e) {
9362 // Netd died. This usually causes a runtime restart anyway.
9363 }
9364 }
9365
Junyu Lai2ed7d412022-10-07 16:52:21 +08009366 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9367 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009368 ensureRunningOnConnectivityServiceThread();
9369
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009370 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009371 // Ignore updates for disconnected networks
9372 return;
9373 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009374 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009375 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009376 + "; created=" + nai.getCreatedTime()
9377 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009378 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009379 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9380 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009381 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009382 }
9383
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009384 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9385 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009386 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009387 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009388 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009389 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9390 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9391 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009392 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9393 // need to be sent as a separate extra.
9394 final NetworkRequest req = nri.isMultilayerRequest()
9395 ? nri.getActiveRequest()
9396 // Non-multilayer listen requests do not have an active request
9397 : nri.mRequests.get(0);
9398 if (req == null) {
9399 Log.wtf(TAG, "No request in NRI " + nri);
9400 }
9401 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009402 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009403 sendIntent(nri.mPendingIntent, intent);
9404 }
9405 // else not handled
9406 }
9407
Michael Groover73f69482023-01-27 11:01:25 -06009408 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9409 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009410 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9411 mPendingIntentWakeLock.acquire();
9412 try {
9413 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009414 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009415 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009416 // Explicitly disallow the receiver from starting activities, to prevent apps from
9417 // utilizing the PendingIntent as a backdoor to do this.
9418 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9419 }
9420 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9421 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009422 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009423 } catch (PendingIntent.CanceledException e) {
9424 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9425 mPendingIntentWakeLock.release();
9426 releasePendingNetworkRequest(pendingIntent);
9427 }
9428 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9429 }
9430
9431 @Override
9432 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9433 String resultData, Bundle resultExtras) {
9434 if (DBG) log("Finished sending " + pendingIntent);
9435 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009436 // Release with a delay so the receiving client has an opportunity to put in its
9437 // own request.
9438 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009439 }
9440
Chalard Jean22350c92023-10-07 19:21:45 +09009441 @Nullable
9442 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9443 if (!nai.isLocalNetwork()) return null;
9444 final Network upstream;
9445 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9446 if (null == selector) {
9447 upstream = null;
9448 } else {
9449 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9450 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9451 upstream = (null == satisfier) ? null : satisfier.network;
9452 }
9453 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9454 }
9455
Chalard Jean46bfbf02022-02-02 00:56:25 +09009456 // networkAgent is only allowed to be null if notificationType is
9457 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9458 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009459 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009460 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009461 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009462 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009463 // Default request has no msgr. Also prevents callbacks from being invoked for
9464 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9465 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9466 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009467 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009468 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009469 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009470 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009471 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009472 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009473 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009474 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9475 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009476 }
Roshan Pius951c0032020-12-22 15:10:42 -08009477 final boolean includeLocationSensitiveInfo =
9478 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009479 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009480 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009481 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009482 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009483 networkCapabilitiesRestrictedForCallerPermissions(
9484 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9485 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009486 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009487 nri.mCallingAttributionTag);
9488 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009489 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9490 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009491 // The local network info is often null, so can't use the static putParcelable
9492 // method here.
9493 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9494 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009495 // For this notification, arg1 contains the blocked status.
9496 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009497 break;
9498 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009499 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009500 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009501 break;
9502 }
9503 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009504 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009505 final NetworkCapabilities netCap =
9506 networkCapabilitiesRestrictedForCallerPermissions(
9507 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9508 putParcelable(
9509 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009510 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009511 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009512 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009513 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009514 break;
9515 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009516 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009517 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9518 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009519 break;
9520 }
junyulaif2c67e42018-08-07 19:50:45 +08009521 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009522 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009523 msg.arg1 = arg1;
9524 break;
9525 }
Chalard Jean22350c92023-10-07 19:21:45 +09009526 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9527 if (!networkAgent.isLocalNetwork()) {
9528 Log.wtf(TAG, "Callback for local info for a non-local network");
9529 return;
9530 }
9531 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9532 break;
9533 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009534 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009535 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009536 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009537 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009538 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009539 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009540 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009541 }
James Mattis45d81842021-01-10 14:24:24 -08009542 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009543 } catch (RemoteException e) {
9544 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009545 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009546 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009547 }
9548
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009549 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9550 bundle.putParcelable(t.getClass().getSimpleName(), t);
9551 }
9552
Chalard Jean0702f982021-09-16 21:50:07 +09009553 /**
9554 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9555 *
9556 * When a request should be assigned to a new network, it is normally lingered to give
9557 * time for apps to gracefully migrate their connections. When both networks are on the same
9558 * radio, but that radio can't do time-sharing efficiently, this may end up being
9559 * counter-productive because any traffic on the old network may drastically reduce the
9560 * performance of the new network.
9561 * The stack supports a configuration to let modem vendors state that their radio can't
9562 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9563 * from one cell network to another can't be done gracefully.
9564 *
9565 * @param oldNai the old network serving the request
9566 * @param newNai the new network serving the request
9567 * @return whether the switch can be graceful
9568 */
9569 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9570 @NonNull final NetworkAgentInfo newSatisfier) {
9571 if (mCellularRadioTimesharingCapable) return true;
9572 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9573 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9574 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9575 }
9576
Paul Jensenaf94b982014-09-30 15:37:41 -04009577 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009578 if (nai.numRequestNetworkRequests() != 0) {
9579 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9580 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009581 // Ignore listening and track default requests.
9582 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009583 loge("Dead network still had at least " + nr);
9584 break;
9585 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009586 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009587 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009588 }
9589
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009590 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9591 if (oldNetwork == null) {
9592 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9593 return;
9594 }
Chalard Jean49707572019-12-10 21:07:02 +09009595 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009596
9597 // If we get here it means that the last linger timeout for this network expired. So there
9598 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009599 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009600
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009601 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009602 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009603 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009604 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009605 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009606 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009607 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009608 }
9609
James Mattise3ef1912020-12-20 11:09:58 -08009610 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9611 boolean isDefaultChanged = false;
9612 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9613 final NetworkReassignment.RequestReassignment reassignment =
9614 changes.getReassignment(defaultRequestInfo);
9615 if (null == reassignment) {
9616 continue;
9617 }
9618 // reassignment only contains those instances where the satisfying network changed.
9619 isDefaultChanged = true;
9620 // Notify system services of the new default.
9621 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9622 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009623
James Mattise3ef1912020-12-20 11:09:58 -08009624 if (isDefaultChanged) {
9625 // Hold a wakelock for a short time to help apps in migrating to a new default.
9626 scheduleReleaseNetworkTransitionWakelock();
9627 }
9628 }
9629
Aaron Huang9fe47be2021-06-08 13:11:45 +08009630 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9631 if (null == oldDefaultNetwork) return;
9632 // The network stopped being the default. If it was using a PAC proxy, then the
9633 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9634 // to the local proxy server, which would forward them over the newly default network.
9635 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9636 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9637 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9638 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9639 }
9640
James Mattise3ef1912020-12-20 11:09:58 -08009641 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9642 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9643 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9644 if (DBG) {
9645 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9646 }
Chalard Jean8e382112019-12-03 20:45:30 +09009647
James Mattisd31bdfa2020-12-23 16:37:26 -08009648 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9649 if (newDefaultNetwork != null) {
9650 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009651 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009652
James Mattisd31bdfa2020-12-23 16:37:26 -08009653 // Set an app level managed default and return since further processing only applies to the
9654 // default network.
9655 if (mDefaultRequest != nri) {
9656 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9657 return;
9658 }
9659
9660 makeDefaultNetwork(newDefaultNetwork);
9661
James Mattise3ef1912020-12-20 11:09:58 -08009662 if (oldDefaultNetwork != null) {
9663 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9664 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09009665 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009666 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009667 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009668 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009669 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009670 updateTcpBufferSizes(null != newDefaultNetwork
9671 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009672 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009673 }
9674
James Mattisd31bdfa2020-12-23 16:37:26 -08009675 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9676 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9677 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9678 try {
9679 if (VDBG) {
9680 log("Setting default network for " + nri
9681 + " using UIDs " + nri.getUids()
9682 + " with old network " + (oldDefaultNetwork != null
9683 ? oldDefaultNetwork.network().getNetId() : "null")
9684 + " and new network " + (newDefaultNetwork != null
9685 ? newDefaultNetwork.network().getNetId() : "null"));
9686 }
9687 if (nri.getUids().isEmpty()) {
9688 throw new IllegalStateException("makeDefaultForApps called without specifying"
9689 + " any applications to set as the default." + nri);
9690 }
9691 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009692 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009693 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009694 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009695 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009696 }
9697 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009698 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009699 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009700 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009701 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009702 }
9703 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009704 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009705 }
9706 }
9707
Junyu Lai35665cc2022-12-19 17:37:48 +08009708 /**
9709 * Collect restricted uid ranges for the given network and UserHandle, these uids
9710 * are not restricted for matched enterprise networks but being restricted for non-matched
9711 * enterprise networks and non-enterprise networks.
9712 */
9713 @NonNull
9714 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9715 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9716 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9717 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9718 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9719
9720 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9721 // The NC is built from a `ProfileNetworkPreference` which has only one
9722 // enterprise ID, so it's guaranteed to have exactly one.
9723 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9724 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9725 continue;
9726 }
9727 }
9728
9729 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9730 pref.capabilities.getUidRanges())) {
9731 throw new IllegalArgumentException(
9732 "Overlapping uid range in preference: " + pref);
9733 }
9734 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9735 }
9736 return restrictedUidRanges;
9737 }
9738
9739 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009740 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009741 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009742
Junyu Lai35665cc2022-12-19 17:37:48 +08009743 ensureRunningOnConnectivityServiceThread();
9744 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9745 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9746 .getUserHandles(true /* excludeDying */);
9747 if (users.isEmpty()) {
9748 throw new IllegalStateException("No user is available");
9749 }
9750
9751 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9752 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9753 for (final UserHandle user : users) {
9754 final ArraySet<UidRange> restrictedUidRanges =
9755 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9756 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9757 UidRange.createForUser(user), restrictedUidRanges));
9758 }
9759
9760 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9761 configs.add(new NativeUidRangeConfig(
9762 nai.network.netId, rangesParcel, 0 /* subPriority */));
9763 }
9764
9765 // The netd API replaces the previous configs with the current configs.
9766 // Thus, for network disconnection or preference removal, no need to
9767 // unset previous config. Instead, collecting all currently needed
9768 // configs and issue to netd.
9769 try {
9770 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9771 } catch (ServiceSpecificException e) {
9772 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009773 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009774 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009775 // Netd died. This will cause a runtime restart anyway.
9776 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009777 }
9778 }
9779
James Mattisd31bdfa2020-12-23 16:37:26 -08009780 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9781 try {
9782 if (null != newDefaultNetwork) {
9783 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9784 } else {
9785 mNetd.networkClearDefault();
9786 }
9787 } catch (RemoteException | ServiceSpecificException e) {
9788 loge("Exception setting default network :" + e);
9789 }
9790 }
9791
Chalard Jean05cbe972019-12-09 11:50:38 +09009792 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009793 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009794 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009795 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009796 processNewlySatisfiedListenRequests(nai);
9797 }
9798
9799 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009800 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9801 if (nri.isMultilayerRequest()) {
9802 continue;
9803 }
9804 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009805 if (!nr.isListen()) continue;
9806 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009807 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009808 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9809 }
9810 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009811 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009812
Chalard Jeancd397a22019-11-22 22:33:33 +09009813 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009814 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9815 if (nri.isMultilayerRequest()) {
9816 continue;
9817 }
9818 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009819 if (!nr.isListen()) continue;
9820 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9821 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009822 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009823 }
9824 }
9825 }
9826
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009827 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009828 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009829 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009830 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009831 @Nullable public final NetworkRequest mOldNetworkRequest;
9832 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009833 @Nullable public final NetworkAgentInfo mOldNetwork;
9834 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009835 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009836 @Nullable final NetworkRequest oldNetworkRequest,
9837 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009838 @Nullable final NetworkAgentInfo oldNetwork,
9839 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009840 mNetworkRequestInfo = networkRequestInfo;
9841 mOldNetworkRequest = oldNetworkRequest;
9842 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009843 mOldNetwork = oldNetwork;
9844 mNewNetwork = newNetwork;
9845 }
Chalard Jean49707572019-12-10 21:07:02 +09009846
9847 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009848 final NetworkRequest requestToShow = null != mNewNetworkRequest
9849 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9850 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009851 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9852 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009853 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009854 }
9855
Chalard Jean46a62372019-12-10 21:25:24 +09009856 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009857
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009858 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009859 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009860 }
9861
9862 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009863 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009864 // The code is never supposed to add two reassignments of the same request. Make
9865 // sure this stays true, but without imposing this expensive check on all
9866 // reassignments on all user devices.
9867 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009868 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009869 throw new IllegalStateException("Trying to reassign ["
9870 + reassignment + "] but already have ["
9871 + existing + "]");
9872 }
9873 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009874 }
Chalard Jean46a62372019-12-10 21:25:24 +09009875 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009876 }
9877
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009878 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009879 // the passed request.
9880 @Nullable
9881 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009882 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009883 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009884 }
9885 return null;
9886 }
Chalard Jean49707572019-12-10 21:07:02 +09009887
9888 public String toString() {
9889 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9890 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009891 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009892 for (final RequestReassignment rr : getRequestReassignments()) {
9893 sj.add(rr.toString());
9894 }
9895 return sj.toString();
9896 }
9897
9898 public String debugString() {
9899 final StringBuilder sb = new StringBuilder();
9900 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009901 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009902 for (final RequestReassignment rr : getRequestReassignments()) {
9903 sb.append("\n ").append(rr);
9904 }
9905 return sb.append("\n").toString();
9906 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009907 }
9908
Chalard Jean24344d72019-12-04 13:32:31 +09009909 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009910 @Nullable final NetworkRequest previousRequest,
9911 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009912 @Nullable final NetworkAgentInfo previousSatisfier,
9913 @Nullable final NetworkAgentInfo newSatisfier,
9914 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009915 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009916 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009917 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009918 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009919 log(" accepting network in place of " + previousSatisfier.toShortString()
9920 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009921 }
James Mattisa076c532020-12-02 14:12:41 -08009922 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009923 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009924 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009925 // If this network switch can't be supported gracefully, the request is not
9926 // lingered. This allows letting go of the network sooner to reclaim some
9927 // performance on the new network, since the radio can't do both at the same
9928 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009929 //
9930 // Also don't linger the request if the old network has been destroyed.
9931 // A destroyed network does not provide actual network connectivity, so
9932 // lingering it is not useful. In particular this ensures that a destroyed
9933 // network is outscored by its replacement,
9934 // then it is torn down immediately instead of being lingered, and any apps that
9935 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009936 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9937 }
Chalard Jean24344d72019-12-04 13:32:31 +09009938 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009939 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009940 }
junyulai0ac374f2020-12-14 18:41:52 +08009941
9942 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9943 // and immediately satisfies a request then remove the timer. This will happen for
9944 // all networks except in the case of an underlying network for a VCN.
9945 if (newSatisfier.isNascent()) {
9946 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009947 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009948 }
9949
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009950 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009951 newSatisfier.unlingerRequest(newRequest.requestId);
9952 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009953 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009954 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009955 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009956 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009957 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009958 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009959 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009960 }
James Mattisa076c532020-12-02 14:12:41 -08009961 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009962 }
James Mattisa076c532020-12-02 14:12:41 -08009963 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009964 }
9965
James Mattisa076c532020-12-02 14:12:41 -08009966 /**
9967 * This function is triggered when something can affect what network should satisfy what
9968 * request, and it computes the network reassignment from the passed collection of requests to
9969 * network match to the one that the system should now have. That data is encoded in an
9970 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9971 * satisfier.
9972 *
9973 * After the reassignment is computed, it is applied to the state objects.
9974 *
9975 * @param networkRequests the nri objects to evaluate for possible network reassignment
9976 * @return NetworkReassignment listing of proposed network assignment changes
9977 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009978 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009979 private NetworkReassignment computeNetworkReassignment(
9980 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009981 final NetworkReassignment changes = new NetworkReassignment();
9982
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009983 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009984 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009985 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009986 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009987 }
Chalard Jean857a1712019-12-10 21:08:07 +09009988
James Mattisa076c532020-12-02 14:12:41 -08009989 for (final NetworkRequestInfo nri : networkRequests) {
9990 // Non-multilayer listen requests can be ignored.
9991 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9992 continue;
9993 }
9994 NetworkAgentInfo bestNetwork = null;
9995 NetworkRequest bestRequest = null;
9996 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009997 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009998 // Stop evaluating as the highest possible priority request is satisfied.
9999 if (null != bestNetwork) {
10000 bestRequest = req;
10001 break;
10002 }
10003 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010004 if (null == bestNetwork && isDefaultBlocked(nri)) {
10005 // Remove default networking if disallowed for managed default requests.
10006 bestNetwork = mNoServiceNetwork;
10007 }
10008 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010009 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010010 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010011 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010012 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010013 }
10014 return changes;
10015 }
10016
James Mattisa076c532020-12-02 14:12:41 -080010017 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10018 return new HashSet<>(mNetworkRequests.values());
10019 }
10020
Paul Jensenc88b39b2015-06-16 14:27:36 -040010021 /**
James Mattisa076c532020-12-02 14:12:41 -080010022 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010023 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010024 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010025 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010026 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10027 }
10028
10029 /**
10030 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10031 * being disconnected.
10032 */
10033 private void rematchNetworksAndRequests(
10034 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10035 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010036 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010037 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010038 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010039 final long computed = SystemClock.elapsedRealtime();
10040 applyNetworkReassignment(changes, start);
10041 final long applied = SystemClock.elapsedRealtime();
10042 issueNetworkNeeds();
10043 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010044 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010045 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10046 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010047 log(changes.debugString());
10048 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010049 // Shorter form, only one line of log
10050 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10051 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010052 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010053 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010054
Chalard Jean1e4c2182023-10-06 18:45:53 +090010055 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10056 @Nullable final NetworkAgentInfo nai2) {
10057 if (null == nai1) return null == nai2;
10058 if (null == nai2) return false;
10059 return nai1.linkProperties.getInterfaceName()
10060 .equals(nai2.linkProperties.getInterfaceName());
10061 }
10062
Chalard Jeand7f762d2019-12-10 19:01:29 +090010063 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010064 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010065 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010066
10067 // Since most of the time there are only 0 or 1 background networks, it would probably
10068 // be more efficient to just use an ArrayList here. TODO : measure performance
10069 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10070 for (final NetworkAgentInfo nai : nais) {
10071 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10072 }
10073
Chalard Jeand7f762d2019-12-10 19:01:29 +090010074 // First, update the lists of satisfied requests in the network agents. This is necessary
10075 // because some code later depends on this state to be correct, most prominently computing
10076 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010077 for (final NetworkReassignment.RequestReassignment event :
10078 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010079 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10080 event.mOldNetworkRequest, event.mNewNetworkRequest,
10081 event.mOldNetwork, event.mNewNetwork,
10082 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010083 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010084
James Mattise3ef1912020-12-20 11:09:58 -080010085 // Process default network changes if applicable.
10086 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010087
Chalard Jean68eab722023-11-16 17:00:04 +090010088 // Update forwarding rules for the upstreams of local networks. Do this before sending
10089 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10090 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10091 // onAvailable so clients know what network the change is about. Store such changes in
10092 // an array that's only allocated if necessary (because it's almost never necessary).
10093 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10094 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10095 if (!nai.isLocalNetwork()) continue;
10096 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10097 if (null == nr) continue; // No upstream for this local network
10098 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10099 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10100 if (null == change) continue; // No change in upstreams for this network
10101 final String fromIface = nai.linkProperties.getInterfaceName();
10102 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10103 || change.mOldNetwork.isDestroyed()) {
10104 // There can be a change with the same interface name if the new network is the
10105 // replacement for the old network that was unregisteredAfterReplacement.
10106 try {
10107 if (null != change.mOldNetwork) {
10108 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10109 change.mOldNetwork.linkProperties.getInterfaceName());
10110 }
10111 // If the new upstream is already destroyed, there is no point in setting up
10112 // a forward (in fact, it might forward to the interface for some new network !)
10113 // Later when the upstream disconnects CS will try to remove the forward, which
10114 // is ignored with a benign log by RoutingCoordinatorService.
10115 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10116 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10117 change.mNewNetwork.linkProperties.getInterfaceName());
10118 }
10119 } catch (final RemoteException e) {
10120 loge("Can't update forwarding rules", e);
10121 }
10122 }
10123 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10124 localInfoChangedAgents.add(nai);
10125 }
10126
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010127 // Notify requested networks are available after the default net is switched, but
10128 // before LegacyTypeTracker sends legacy broadcasts
10129 for (final NetworkReassignment.RequestReassignment event :
10130 changes.getRequestReassignments()) {
10131 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010132 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010133 } else {
James Mattisa076c532020-12-02 14:12:41 -080010134 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010135 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010136 }
10137 }
10138
junyulai0ac374f2020-12-14 18:41:52 +080010139 // Update the inactivity state before processing listen callbacks, because the background
10140 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010141 // just yet though, because they have to be sent after the listens are processed to keep
10142 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010143 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010144 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010145 // Rematching may have altered the inactivity state of some networks, so update all
10146 // inactivity timers. updateInactivityState reads the state from the network agent
10147 // and does nothing if the state has not changed : the source of truth is controlled
10148 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10149 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010150 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010151 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010152 }
10153 }
10154
Chalard Jeanb10ab412019-12-11 14:12:30 +090010155 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010156 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010157 // Process listen requests and update capabilities if the background state has
10158 // changed for this network. For consistency with previous behavior, send onLost
10159 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010160 processNewlyLostListenRequests(nai);
10161 if (oldBackground != nai.isBackgroundNetwork()) {
10162 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010163 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010164 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010165 }
10166
junyulai0ac374f2020-12-14 18:41:52 +080010167 for (final NetworkAgentInfo nai : inactiveNetworks) {
10168 // For nascent networks, if connecting with no foreground request, skip broadcasting
10169 // LOSING for backward compatibility. This is typical when mobile data connected while
10170 // wifi connected with mobile data always-on enabled.
10171 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010172 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010173 }
10174
Chalard Jean68eab722023-11-16 17:00:04 +090010175 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10176 if (null != localInfoChangedAgents) {
10177 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10178 notifyNetworkCallbacks(nai,
10179 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010180 }
10181 }
10182
James Mattise3ef1912020-12-20 11:09:58 -080010183 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010184
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010185 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010186 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010187 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010188 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010189 // This network has active linger timers and no requests, but is not
10190 // lingering. Linger it.
10191 //
10192 // One way (the only way?) this can happen if this network is unvalidated
10193 // and became unneeded due to another network improving its score to the
10194 // point where this network will no longer be able to satisfy any requests
10195 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010196 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010197 notifyNetworkLosing(nai, now);
10198 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010199 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010200 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010201 teardownUnneededNetwork(nai);
10202 }
10203 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010204 }
10205 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010206
Chalard Jean62edfd82019-12-02 18:39:29 +090010207 /**
10208 * Apply a change in background state resulting from rematching networks with requests.
10209 *
10210 * During rematch, a network may change background states by starting to satisfy or stopping
10211 * to satisfy a foreground request. Listens don't count for this. When a network changes
10212 * background states, its capabilities need to be updated and callbacks fired for the
10213 * capability change.
10214 *
10215 * @param nai The network that changed background states
10216 */
10217 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10218 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10219 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10220 updateNetworkPermissions(nai, newNc);
10221 nai.getAndSetNetworkCapabilities(newNc);
10222 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10223 }
10224
Chalard Jeanf0344532019-11-19 19:23:38 +090010225 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010226 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010227 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010228 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10229 changes.getReassignment(mDefaultRequest);
10230 final NetworkAgentInfo oldDefaultNetwork =
10231 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10232 final NetworkAgentInfo newDefaultNetwork =
10233 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010234
Chalard Jean5b409c72021-02-04 13:12:59 +090010235 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010236 // Maintain the illusion : since the legacy API only understands one network at a time,
10237 // if the default network changed, apps should see a disconnected broadcast for the
10238 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010239 if (oldDefaultNetwork != null) {
10240 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10241 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010242 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010243 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010244 // The new default network can be newly null if and only if the old default
10245 // network doesn't satisfy the default request any more because it lost a
10246 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010247 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010248 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010249 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010250 }
10251 }
10252
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010253 // Now that all the callbacks have been sent, send the legacy network broadcasts
10254 // as needed. This is necessary so that legacy requests correctly bind dns
10255 // requests to this network. The legacy users are listening for this broadcast
10256 // and will generally do a dns request so they can ensureRouteToHost and if
10257 // they do that before the callbacks happen they'll use the default network.
10258 //
10259 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10260 // callbacks, but if apps can receive the broadcast before the callback, they still might
10261 // have an inconsistent view of networking.
10262 //
10263 // This *does* introduce a race where if the user uses the new api
10264 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10265 // they may get old info. Reverse this after the old startUsing api is removed.
10266 // This is on top of the multiple intent sequencing referenced in the todo above.
10267 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010268 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010269 addNetworkToLegacyTypeTracker(nai);
10270 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010271 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010272 }
10273
Chalard Jean0354d8c2021-01-12 10:58:56 +090010274 private void issueNetworkNeeds() {
10275 ensureRunningOnConnectivityServiceThread();
10276 for (final NetworkOfferInfo noi : mNetworkOffers) {
10277 issueNetworkNeeds(noi);
10278 }
10279 }
10280
10281 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10282 ensureRunningOnConnectivityServiceThread();
10283 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10284 informOffer(nri, noi.offer, mNetworkRanker);
10285 }
10286 }
10287
10288 /**
10289 * Inform a NetworkOffer about any new situation of a request.
10290 *
10291 * This function handles updates to offers. A number of events may happen that require
10292 * updating the registrant for this offer about the situation :
10293 * • The offer itself was updated. This may lead the offer to no longer being able
10294 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10295 * or conversely being strengthened enough to beat the satisfier (and therefore
10296 * start being needed)
10297 * • The network satisfying a request changed (including cases where the request
10298 * starts or stops being satisfied). The new network may be a stronger or weaker
10299 * match than the old one, possibly affecting whether the offer is needed.
10300 * • The network satisfying a request updated their score. This may lead the offer
10301 * to no longer be able to beat it if the current satisfier got better, or
10302 * conversely start being a good choice if the current satisfier got weaker.
10303 *
10304 * @param nri The request
10305 * @param offer The offer. This may be an updated offer.
10306 */
10307 private static void informOffer(@NonNull NetworkRequestInfo nri,
10308 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10309 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10310 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010311
10312 // Multi-layer requests have a currently active request, the one being satisfied.
10313 // Since the system will try to bring up a better network than is currently satisfying
10314 // the request, NetworkProviders need to be told the offers matching the requests *above*
10315 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10316 // not needed, and the offer is needed for the active request iff the offer can beat
10317 // the satisfier.
10318 // For non-multilayer requests, the logic above gracefully degenerates to only the
10319 // last case.
10320 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10321 // providers that the offer is needed for this request, until the active request is found.
10322 // In a second phase, deal with the currently active request. In a third phase, inform
10323 // the providers that offer is unneeded for the remaining requests.
10324
10325 // First phase : inform providers of all requests above the active request.
10326 int i;
10327 for (i = 0; nri.mRequests.size() > i; ++i) {
10328 final NetworkRequest request = nri.mRequests.get(i);
10329 if (activeRequest == request) break; // Found the active request : go to phase 2
10330 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10331 // Since this request is higher-priority than the one currently satisfied, if the
10332 // offer can satisfy it, the provider should try and bring up the network for sure ;
10333 // no need to even ask the ranker – an offer that can satisfy is always better than
10334 // no network. Hence tell the provider so unless it already knew.
10335 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10336 offer.onNetworkNeeded(request);
10337 }
10338 }
10339
10340 // Second phase : deal with the active request (if any)
10341 if (null != activeRequest && activeRequest.isRequest()) {
10342 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010343 // If an offer can satisfy the request, it is considered needed if it is currently
10344 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010345 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010346 && satisfier.factorySerialNumber == offer.providerId
10347 && activeRequest.canBeSatisfiedBy(offer.caps);
10348 final boolean newNeeded = currentlyServing
10349 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010350 if (newNeeded != oldNeeded) {
10351 if (newNeeded) {
10352 offer.onNetworkNeeded(activeRequest);
10353 } else {
10354 // The offer used to be able to beat the satisfier. Now it can't.
10355 offer.onNetworkUnneeded(activeRequest);
10356 }
10357 }
10358 }
10359
10360 // Third phase : inform the providers that the offer isn't needed for any request
10361 // below the active one.
10362 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10363 final NetworkRequest request = nri.mRequests.get(i);
10364 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10365 // Since this request is lower-priority than the one currently satisfied, if the
10366 // offer can satisfy it, the provider should not try and bring up the network.
10367 // Hence tell the provider so unless it already knew.
10368 if (offer.neededFor(request)) {
10369 offer.onNetworkUnneeded(request);
10370 }
10371 }
10372 }
10373
Chalard Jean61c79252019-11-07 23:07:32 +090010374 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10375 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10376 NetworkRequest nr = nai.requestAt(i);
10377 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10378 // legacy type tracker filters out repeat adds
10379 mLegacyTypeTracker.add(nr.legacyType, nai);
10380 }
10381 }
10382
10383 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010384 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010385 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10386 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10387 if (nai.isVPN()) {
10388 mLegacyTypeTracker.add(TYPE_VPN, nai);
10389 }
10390 }
10391
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010392 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010393 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010394 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010395 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010396 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010397 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010398
Chalard Jean254bd162022-08-25 13:04:51 +090010399 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010400 // Don't repeat publish.
10401 if (newInetCondition == mDefaultInetConditionPublished) return;
10402
10403 mDefaultInetConditionPublished = newInetCondition;
10404 sendInetConditionBroadcast(nai.networkInfo);
10405 }
10406
Chalard Jeand61375d2020-01-14 22:46:36 +090010407 @NonNull
10408 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10409 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010410 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010411 final boolean suspended =
10412 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10413 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10414 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10415 // state. This is because the network could have been suspended before connecting,
10416 // or it could be disconnecting while being suspended, and in both these cases
10417 // the state should not be overridden. Note that the only detailed state that
10418 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10419 // worry about multiple different substates of CONNECTED.
10420 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10421 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010422 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10423 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10424 // network agent is created, then goes to suspended, then goes out of suspended without
10425 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010426 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010427 ? NetworkInfo.DetailedState.CONNECTED
10428 : NetworkInfo.DetailedState.CONNECTING,
10429 info.getReason(),
10430 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010431 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010432 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010433 return newInfo;
10434 }
10435
10436 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10437 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10438
Erik Kline99f301b2017-02-15 19:59:17 +090010439 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010440 NetworkInfo oldInfo = null;
10441 synchronized (networkAgent) {
10442 oldInfo = networkAgent.networkInfo;
10443 networkAgent.networkInfo = newInfo;
10444 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010445
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010446 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010447 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10448 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010449 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010450
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010451 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010452 // A network that has just connected has zero requests and is thus a foreground network.
10453 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10454
Luke Huangfdd11f82019-04-09 18:41:49 +080010455 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010456
10457 networkAgent.setCreated();
10458
10459 // If the network is created immediately on register, then apply the LinkProperties now.
10460 // Otherwise, this is done further down when the network goes into connected state.
10461 // Applying the LinkProperties means that the network is ready to carry traffic -
10462 // interfaces and routing rules have been added, DNS servers programmed, etc.
10463 // For VPNs, this must be done before the capabilities are updated, because as soon as
10464 // that happens, UIDs are routed to the network.
10465 if (shouldCreateNetworksImmediately()) {
10466 applyInitialLinkProperties(networkAgent);
10467 }
10468
10469 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10470 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010471 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010472 // Initialize the network's capabilities to their starting values according to the
10473 // underlying networks. This ensures that the capabilities are correct before
10474 // anything happens to the network.
10475 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010476 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010477 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010478 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010479 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010480 }
10481
Chalard Jean254bd162022-08-25 13:04:51 +090010482 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10483 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010484
lucaslin45e639b2019-04-03 17:09:28 +080010485 // NetworkCapabilities need to be set before sending the private DNS config to
10486 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010487 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10488
Erik Kline9a62f012018-03-21 07:18:33 -070010489 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010490 if (!shouldCreateNetworksImmediately()) {
10491 applyInitialLinkProperties(networkAgent);
10492 } else {
10493 // The network was created when the agent registered, and the LinkProperties are
10494 // already up-to-date. However, updateLinkProperties also makes some changes only
10495 // when the network connects. Apply those changes here. On T and below these are
10496 // handled by the applyInitialLinkProperties call just above.
10497 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10498 // If something depends on both LinkProperties and connected state, it should be in
10499 // this method as well.
10500 networkAgent.clatd.update();
10501 updateProxy(networkAgent.linkProperties, null);
10502 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010503
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010504 // If a rate limit has been configured and is applicable to this network (network
10505 // provides internet connectivity), apply it. The tc police filter cannot be attached
10506 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010507 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010508 // Note: in case of a system server crash, the NetworkController constructor in netd
10509 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10510 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10511 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10512 mIngressRateLimit);
10513 }
10514
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010515 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10516 // command must be sent after updating LinkProperties to maximize chances of
10517 // NetworkMonitor seeing the correct LinkProperties when starting.
10518 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010519 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010520 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010521 }
Chalard Jeand4900722022-02-06 12:25:38 +090010522 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10523 params.networkAgentConfig = networkAgent.networkAgentConfig;
10524 params.networkCapabilities = networkAgent.networkCapabilities;
10525 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10526 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010527 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10528 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10529 // call that would cause a Log.wtf to be emitted from the system_server process, and
10530 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10531 // process to check the interface version, just use an SDK check. NetworkStack will
10532 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010533 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010534 networkAgent.networkMonitor().notifyNetworkConnected(params);
10535 } else {
10536 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10537 params.networkCapabilities);
10538 }
Chalard Jean0f141332023-06-05 19:26:17 +090010539 final long evaluationDelay;
10540 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10541 // If the network is anything other than pure wifi, use the default timeout.
10542 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10543 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10544 // If the network is explicitly selected, use the default timeout because it's
10545 // shorter and the user is likely staring at the screen expecting it to validate
10546 // right away.
10547 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10548 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10549 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10550 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10551 } else {
10552 // It's wifi, automatically connected, and bad wifi is preferred : use the
10553 // longer timeout to avoid the device switching to captive portals with bad
10554 // signal or very slow response.
10555 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10556 }
10557 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010558
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010559 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10560 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10561 // capabilities, so it only needs to be done once on initial connect, not every time the
10562 // network's capabilities change. Note that we do this before rematching the network,
10563 // so we could decide to tear it down immediately afterwards. That's fine though - on
10564 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10565 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010566 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010567
junyulai0ac374f2020-12-14 18:41:52 +080010568 // Before first rematching networks, put an inactivity timer without any request, this
10569 // allows {@code updateInactivityState} to update the state accordingly and prevent
10570 // tearing down for any {@code unneeded} evaluation in this period.
10571 // Note that the timer will not be rescheduled since the expiry time is
10572 // fixed after connection regardless of the network satisfying other requests or not.
10573 // But it will be removed as soon as the network satisfies a request for the first time.
10574 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10575 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010576 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010577
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010578 if (mTrackMultiNetworkActivities) {
10579 // Start tracking activity of this network.
10580 // This must be called before rematchAllNetworksAndRequests since the network
10581 // should be tracked when the network becomes the default network.
10582 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
10583 // can be triggered later if this network becomes the default network.
10584 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
10585 }
10586
Paul Jensen05e85ee2014-09-11 11:00:39 -040010587 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010588 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010589
10590 // This has to happen after matching the requests, because callbacks are just requests.
10591 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010592 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010593 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010594 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010595 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010596 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010597 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010598 if (networkAgent.isVPN()) {
10599 // As the active or bound network changes for apps, broadcast the default proxy, as
10600 // apps may need to update their proxy data. This is called after disconnecting from
10601 // VPN to make sure we do not broadcast the old proxy data.
10602 // TODO(b/122649188): send the broadcast only to VPN users.
10603 mProxyTracker.sendProxyBroadcast();
10604 }
Chalard Jean254bd162022-08-25 13:04:51 +090010605 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10606 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010607 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010608 }
10609 }
10610
Chalard Jean28018572020-12-21 18:36:52 +090010611 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010612 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10613 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010614 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010615 }
10616
Erik Kline99f301b2017-02-15 19:59:17 +090010617 // Notify only this one new request of the current state. Transfer all the
10618 // current state by calling NetworkCapabilities and LinkProperties callbacks
10619 // so that callers can be guaranteed to have as close to atomicity in state
10620 // transfer as can be supported by this current API.
10621 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010622 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010623 if (nri.mPendingIntent != null) {
10624 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10625 // Attempt no subsequent state pushes where intents are involved.
10626 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010627 }
Erik Kline99f301b2017-02-15 19:59:17 +090010628
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010629 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010630 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010631 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10632 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10633 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010634 }
10635
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010636 // Notify the requests on this NAI that the network is now lingered.
10637 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010638 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010639 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10640 }
10641
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010642 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10643 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10644 return vpnBlocked
10645 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10646 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10647 }
10648
10649 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10650 if (blockedReasons == BLOCKED_REASON_NONE) {
10651 mUidBlockedReasons.delete(uid);
10652 } else {
10653 mUidBlockedReasons.put(uid, blockedReasons);
10654 }
10655 }
10656
junyulaif2c67e42018-08-07 19:50:45 +080010657 /**
10658 * Notify of the blocked state apps with a registered callback matching a given NAI.
10659 *
10660 * Unlike other callbacks, blocked status is different between each individual uid. So for
10661 * any given nai, all requests need to be considered according to the uid who filed it.
10662 *
10663 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010664 * @param oldMetered True if the previous network capabilities were metered.
10665 * @param newMetered True if the current network capabilities are metered.
10666 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10667 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010668 */
10669 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010670 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10671 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010672
10673 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10674 NetworkRequest nr = nai.requestAt(i);
10675 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010676
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010677 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10678 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10679 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010680 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010681 : oldVpnBlocked;
10682
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010683 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10684 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10685 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010686 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010687 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010688 }
10689 }
10690 }
10691
10692 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010693 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010694 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010695 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010696 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010697 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010698 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010699 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010700 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010701
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010702 final int oldBlockedState = getBlockedState(
10703 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10704 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10705 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010706 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010707 }
junyulaif2c67e42018-08-07 19:50:45 +080010708 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10709 NetworkRequest nr = nai.requestAt(i);
10710 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010711 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010712 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10713 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010714 }
10715 }
10716 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010717 }
10718
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010719 @VisibleForTesting
10720 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010721 // The NetworkInfo we actually send out has no bearing on the real
10722 // state of affairs. For example, if the default connection is mobile,
10723 // and a request for HIPRI has just gone away, we need to pretend that
10724 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10725 // the state to DISCONNECTED, even though the network is of type MOBILE
10726 // and is still connected.
10727 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10728 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010729 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010730 if (state != DetailedState.DISCONNECTED) {
10731 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010732 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010733 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010734 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010735 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10736 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10737 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10738 if (info.isFailover()) {
10739 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10740 nai.networkInfo.setFailover(false);
10741 }
10742 if (info.getReason() != null) {
10743 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10744 }
10745 if (info.getExtraInfo() != null) {
10746 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10747 }
10748 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010749 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010750 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010751 if (newDefaultAgent != null) {
10752 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10753 newDefaultAgent.networkInfo);
10754 } else {
10755 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10756 }
10757 }
10758 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10759 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010760 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010761 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010762 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010763 }
10764 }
10765 }
10766
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010767 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010768 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010769 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010770 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010771 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010772 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10773 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010774 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10775 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010776 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010777 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010778 } else {
10779 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10780 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010781 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010782 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010783
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010784 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10785 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10786 }
10787
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010788 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010789 * Returns the list of all interfaces that could be used by network traffic that does not
10790 * explicitly specify a network. This includes the default network, but also all VPNs that are
10791 * currently connected.
10792 *
10793 * Must be called on the handler thread.
10794 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010795 @NonNull
10796 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010797 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010798 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010799 final Set<Integer> activeNetIds = new ArraySet<>();
10800 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10801 if (nri.isBeingSatisfied()) {
10802 activeNetIds.add(nri.getSatisfier().network().netId);
10803 }
10804 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010805 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010806 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010807 defaultNetworks.add(nai.network);
10808 }
10809 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010810 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010811 }
10812
10813 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010814 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10815 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010816 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010817 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010818 ensureRunningOnConnectivityServiceThread();
10819 String activeIface = null;
10820 LinkProperties activeLinkProperties = getActiveLinkProperties();
10821 if (activeLinkProperties != null) {
10822 activeIface = activeLinkProperties.getInterfaceName();
10823 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010824
junyulai2050bed2021-01-23 09:46:34 +080010825 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010826 try {
junyulaide41fc22021-01-22 22:46:01 +080010827 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010828 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010829 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10830 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010831 } catch (Exception ignored) {
10832 }
10833 }
10834
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010835 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010836 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010837 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010838 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010839 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010840
10841 if (!TextUtils.isEmpty(settingUrl)) {
10842 return settingUrl;
10843 }
10844
10845 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010846 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010847 if (!TextUtils.isEmpty(settingUrl)) {
10848 return settingUrl;
10849 }
10850
10851 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010852 }
10853
10854 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010855 public void startNattKeepalive(Network network, int intervalSeconds,
10856 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010857 enforceKeepalivePermission();
10858 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010859 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010860 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10861 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010862 // false and set the underpinned network to null because there is no way and no
10863 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10864 // deprecated method.
10865 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010866 }
10867
10868 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010869 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010870 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010871 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010872 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010873 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010874 mKeepaliveTracker.startNattKeepalive(
10875 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010876 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10877 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010878 } finally {
10879 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10880 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010881 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10882 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010883 }
10884 }
junyulaid05a1922019-01-15 11:32:44 +080010885 }
10886
10887 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010888 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010889 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010890 try {
10891 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010892 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010893 mKeepaliveTracker.startTcpKeepalive(
10894 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10895 } finally {
10896 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10897 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010898 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10899 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010900 }
10901 }
junyulai0835a1e2019-01-08 20:04:33 +080010902 }
10903
10904 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010905 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010906 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010907 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10908 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010909 }
10910
10911 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010912 public int[] getSupportedKeepalives() {
10913 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10914 // Backwards compatibility with CTS 13
10915 android.Manifest.permission.QUERY_ALL_PACKAGES);
10916
10917 return BinderUtils.withCleanCallingIdentity(() ->
10918 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10919 }
10920
10921 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010922 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010923 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010924
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010925 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010926 final long token = Binder.clearCallingIdentity();
10927 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010928 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10929 UserHandle.getUserHandleForUid(uid))) {
10930 return;
10931 }
10932
Heemin Seogdb8489d2019-06-12 09:21:44 -070010933 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10934 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010935
10936 // Turn airplane mode off
10937 setAirplaneMode(false);
10938
10939 // restore private DNS settings to default mode (opportunistic)
10940 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10941 UserHandle.getUserHandleForUid(uid))) {
10942 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10943 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10944 }
10945
10946 Settings.Global.putString(mContext.getContentResolver(),
10947 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010948 } finally {
10949 Binder.restoreCallingIdentity(token);
10950 }
Stuart Scottd5463642015-04-02 18:00:02 -070010951 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010952
Ricky Wai7097cc92018-01-23 04:09:45 +000010953 @Override
10954 public byte[] getNetworkWatchlistConfigHash() {
10955 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10956 if (nwm == null) {
10957 loge("Unable to get NetworkWatchlistManager");
10958 return null;
10959 }
10960 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10961 return nwm.getWatchlistConfigHash();
10962 }
10963
Hugo Benichibe0c7652016-05-31 16:28:06 +090010964 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010965 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010966 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010967 }
Hugo Benichif4210292017-04-21 15:07:12 +090010968
10969 private static boolean toBool(int encodedBoolean) {
10970 return encodedBoolean != 0; // Only 0 means false.
10971 }
10972
10973 private static int encodeBool(boolean b) {
10974 return b ? 1 : 0;
10975 }
mswest4632928412018-03-12 10:34:34 -070010976
10977 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010978 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10979 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10980 @NonNull String[] args) {
10981 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10982 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010983 }
10984
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010985 private Boolean parseBooleanArgument(final String arg) {
10986 if ("true".equals(arg)) {
10987 return true;
10988 } else if ("false".equals(arg)) {
10989 return false;
10990 } else {
10991 return null;
10992 }
10993 }
10994
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010995 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010996 @Override
10997 public int onCommand(String cmd) {
10998 if (cmd == null) {
10999 return handleDefaultCommands(cmd);
11000 }
11001 final PrintWriter pw = getOutPrintWriter();
11002 try {
11003 switch (cmd) {
11004 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011005 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11006 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011007 final String action = getNextArg();
11008 if ("enable".equals(action)) {
11009 setAirplaneMode(true);
11010 return 0;
11011 } else if ("disable".equals(action)) {
11012 setAirplaneMode(false);
11013 return 0;
11014 } else if (action == null) {
11015 final ContentResolver cr = mContext.getContentResolver();
11016 final int enabled = Settings.Global.getInt(cr,
11017 Settings.Global.AIRPLANE_MODE_ON);
11018 pw.println(enabled == 0 ? "disabled" : "enabled");
11019 return 0;
11020 } else {
11021 onHelp();
11022 return -1;
11023 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011024 case "set-chain3-enabled": {
11025 final Boolean enabled = parseBooleanArgument(getNextArg());
11026 if (null == enabled) {
11027 onHelp();
11028 return -1;
11029 }
11030 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11031 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11032 enabled);
11033 return 0;
11034 }
11035 case "get-chain3-enabled": {
11036 final boolean chainEnabled = getFirewallChainEnabled(
11037 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11038 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11039 return 0;
11040 }
11041 case "set-package-networking-enabled": {
11042 final Boolean enabled = parseBooleanArgument(getNextArg());
11043 final String packageName = getNextArg();
11044 if (null == enabled || null == packageName) {
11045 onHelp();
11046 return -1;
11047 }
11048 // Throws NameNotFound if the package doesn't exist.
11049 final int appId = setPackageFirewallRule(
11050 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11051 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11052 final String msg = (enabled ? "Enabled" : "Disabled")
11053 + " networking for " + packageName + ", appId " + appId;
11054 Log.i(TAG, msg);
11055 pw.println(msg);
11056 return 0;
11057 }
11058 case "get-package-networking-enabled": {
11059 final String packageName = getNextArg();
11060 final int rule = getPackageFirewallRule(
11061 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11062 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11063 pw.println(packageName + ":" + "allow");
11064 } else if (FIREWALL_RULE_DENY == rule) {
11065 pw.println(packageName + ":" + "deny");
11066 } else {
11067 throw new IllegalStateException("Unknown rule " + rule + " for package "
11068 + packageName);
11069 }
11070 return 0;
11071 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011072 case "reevaluate":
11073 // Usage : adb shell cmd connectivity reevaluate <netId>
11074 // If netId is omitted, then reevaluate the default network
11075 final String netId = getNextArg();
11076 final NetworkAgentInfo nai;
11077 if (null == netId) {
11078 // Note that the command is running on the wrong thread to call this,
11079 // so this could in principle return stale data. But it can't crash.
11080 nai = getDefaultNetwork();
11081 } else {
11082 // If netId can't be parsed, this throws NumberFormatException, which
11083 // is passed back to adb who prints it.
11084 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11085 }
11086 if (null == nai) {
11087 pw.println("Unknown network (net ID not found or no default network)");
11088 return 0;
11089 }
11090 Log.d(TAG, "Reevaluating network " + nai.network);
11091 reportNetworkConnectivity(nai.network, !nai.isValidated());
11092 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011093 case "bpf-get-cgroup-program-id": {
11094 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11095 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11096 // for more detail.
11097 // If type can't be parsed, this throws NumberFormatException, which
11098 // is passed back to adb who prints it.
11099 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011100 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011101 pw.println(ret);
11102 return 0;
11103 }
mswest4632928412018-03-12 10:34:34 -070011104 default:
11105 return handleDefaultCommands(cmd);
11106 }
11107 } catch (Exception e) {
11108 pw.println(e);
11109 }
11110 return -1;
11111 }
11112
11113 @Override
11114 public void onHelp() {
11115 PrintWriter pw = getOutPrintWriter();
11116 pw.println("Connectivity service commands:");
11117 pw.println(" help");
11118 pw.println(" Print this help text.");
11119 pw.println(" airplane-mode [enable|disable]");
11120 pw.println(" Turn airplane mode on or off.");
11121 pw.println(" airplane-mode");
11122 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011123 pw.println(" set-chain3-enabled [true|false]");
11124 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11125 pw.println(" get-chain3-enabled");
11126 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11127 pw.println(" set-package-networking-enabled [true|false] [package name]");
11128 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11129 + " no effect if the chain is disabled.");
11130 pw.println(" get-package-networking-enabled [package name]");
11131 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011132 }
11133 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011134
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011135 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011136 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11137 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11138 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011139 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011140 }
11141
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011142 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11143 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011144 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11145 final TransportInfo newInfo = nc.getTransportInfo();
11146 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11147 return;
11148 }
11149 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011150 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011151 }
11152 }
11153
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011154 /**
11155 * @param connectionInfo the connection to resolve.
11156 * @return {@code uid} if the connection is found and the app has permission to observe it
11157 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11158 * connection is not found.
11159 */
11160 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011161 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11162 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11163 }
11164
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011165 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011166 connectionInfo.local, connectionInfo.remote);
11167
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011168 if (uid == INVALID_UID) return uid; // Not found.
11169
11170 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11171 // VPN, if any, that applies to the UID that owns the connection.
11172 if (checkNetworkStackPermission()) return uid;
11173
11174 final NetworkAgentInfo vpn = getVpnForUid(uid);
11175 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011176 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011177 return INVALID_UID;
11178 }
11179
11180 return uid;
11181 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011182
Benedict Wong493e04b2018-11-09 14:45:34 -080011183 /**
11184 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11185 *
11186 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11187 */
11188 @Override
11189 public IBinder startOrGetTestNetworkService() {
11190 synchronized (mTNSLock) {
11191 TestNetworkService.enforceTestNetworkPermissions(mContext);
11192
11193 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011194 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011195 }
11196
11197 return mTNS;
11198 }
11199 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011200
Cody Kesting73708bf2019-12-18 10:57:50 -080011201 /**
11202 * Handler used for managing all Connectivity Diagnostics related functions.
11203 *
11204 * @see android.net.ConnectivityDiagnosticsManager
11205 *
11206 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11207 */
11208 @VisibleForTesting
11209 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011210 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11211
Cody Kesting73708bf2019-12-18 10:57:50 -080011212 /**
11213 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11214 * android.net.ConnectivityDiagnosticsManager}.
11215 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11216 * NetworkRequestInfo to be registered
11217 */
11218 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11219
11220 /**
11221 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11222 * android.net.ConnectivityDiagnosticsManager}.
11223 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11224 * arg1 = the uid of the caller
11225 */
11226 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11227
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011228 /**
11229 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011230 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011231 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11232 * NetworkMonitor.
11233 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011234 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011235 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011236
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011237 /**
11238 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11239 * been detected on the network.
11240 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11241 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11242 * arg2 = NetID.
11243 * data = PersistableBundle of extras passed from NetworkMonitor.
11244 */
11245 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11246
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011247 /**
11248 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11249 * the platform. This event will invoke {@link
11250 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11251 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011252 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011253 */
11254 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11255
Cody Kesting73708bf2019-12-18 10:57:50 -080011256 private ConnectivityDiagnosticsHandler(Looper looper) {
11257 super(looper);
11258 }
11259
11260 @Override
11261 public void handleMessage(Message msg) {
11262 switch (msg.what) {
11263 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11264 handleRegisterConnectivityDiagnosticsCallback(
11265 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11266 break;
11267 }
11268 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11269 handleUnregisterConnectivityDiagnosticsCallback(
11270 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11271 break;
11272 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011273 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011274 final ConnectivityReportEvent reportEvent =
11275 (ConnectivityReportEvent) msg.obj;
11276
Aaron Huang959d3642021-01-21 15:47:41 +080011277 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011278 break;
11279 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011280 case EVENT_DATA_STALL_SUSPECTED: {
11281 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011282 final Pair<Long, PersistableBundle> arg =
11283 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011284 if (nai == null) break;
11285
Aaron Huang959d3642021-01-21 15:47:41 +080011286 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011287 break;
11288 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011289 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011290 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011291 break;
11292 }
11293 default: {
11294 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11295 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011296 }
11297 }
11298 }
11299
11300 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11301 @VisibleForTesting
11302 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11303 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11304 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011305 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011306
11307 @VisibleForTesting
11308 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011309 @NonNull IConnectivityDiagnosticsCallback cb,
11310 @NonNull NetworkRequestInfo nri,
11311 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011312 mCb = cb;
11313 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011314 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011315 }
11316
11317 @Override
11318 public void binderDied() {
11319 log("ConnectivityDiagnosticsCallback IBinder died.");
11320 unregisterConnectivityDiagnosticsCallback(mCb);
11321 }
11322 }
11323
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011324 /**
11325 * Class used for sending information from {@link
11326 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11327 */
11328 private static class NetworkTestedResults {
11329 private final int mNetId;
11330 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011331 @Nullable private final String mRedirectUrl;
11332
11333 private NetworkTestedResults(
11334 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11335 mNetId = netId;
11336 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011337 mRedirectUrl = redirectUrl;
11338 }
11339 }
11340
11341 /**
11342 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11343 * ConnectivityDiagnosticsHandler}.
11344 */
11345 private static class ConnectivityReportEvent {
11346 private final long mTimestampMillis;
11347 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011348 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011349
Aaron Huang959d3642021-01-21 15:47:41 +080011350 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11351 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011352 mTimestampMillis = timestampMillis;
11353 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011354 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011355 }
11356 }
11357
Cody Kestingf1120be2020-08-03 18:01:40 -070011358 /**
11359 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11360 * ConnectivityDiagnosticsHandler}.
11361 */
11362 private static class ReportedNetworkConnectivityInfo {
11363 public final boolean hasConnectivity;
11364 public final boolean isNetworkRevalidating;
11365 public final int reporterUid;
11366 @NonNull public final NetworkAgentInfo nai;
11367
11368 private ReportedNetworkConnectivityInfo(
11369 boolean hasConnectivity,
11370 boolean isNetworkRevalidating,
11371 int reporterUid,
11372 @NonNull NetworkAgentInfo nai) {
11373 this.hasConnectivity = hasConnectivity;
11374 this.isNetworkRevalidating = isNetworkRevalidating;
11375 this.reporterUid = reporterUid;
11376 this.nai = nai;
11377 }
11378 }
11379
Cody Kesting73708bf2019-12-18 10:57:50 -080011380 private void handleRegisterConnectivityDiagnosticsCallback(
11381 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11382 ensureRunningOnConnectivityServiceThread();
11383
11384 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011385 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011386 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11387
James Mattis64b8b0f2020-11-24 17:40:49 -080011388 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11389 // confusing for these networks to change when an NRI is satisfied in another layer.
11390 if (nri.isMultilayerRequest()) {
11391 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11392 + "network requests.");
11393 }
11394
Cody Kesting73708bf2019-12-18 10:57:50 -080011395 // This means that the client registered the same callback multiple times. Do
11396 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011397 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011398 if (VDBG) log("Diagnostics callback is already registered");
11399
11400 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11401 // incremented when the NetworkRequestInfo is created as part of
11402 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011403 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011404 return;
11405 }
11406
Cody Kesting31f1ff62020-03-05 10:46:02 -080011407 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011408
11409 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011410 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011411 } catch (RemoteException e) {
11412 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011413 return;
11414 }
11415
11416 // Once registered, provide ConnectivityReports for matching Networks
11417 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11418 synchronized (mNetworkForNetId) {
11419 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11420 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011421 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11422 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011423 matchingNetworks.add(nai);
11424 }
11425 }
11426 }
11427 for (final NetworkAgentInfo nai : matchingNetworks) {
11428 final ConnectivityReport report = nai.getConnectivityReport();
11429 if (report == null) {
11430 continue;
11431 }
11432 if (!checkConnectivityDiagnosticsPermissions(
11433 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11434 continue;
11435 }
11436
11437 try {
11438 cb.onConnectivityReportAvailable(report);
11439 } catch (RemoteException e) {
11440 // Exception while sending the ConnectivityReport. Move on to the next network.
11441 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011442 }
11443 }
11444
11445 private void handleUnregisterConnectivityDiagnosticsCallback(
11446 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11447 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011448 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011449
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011450 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11451 mConnectivityDiagnosticsCallbacks.remove(iCb);
11452 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011453 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11454 return;
11455 }
11456
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011457 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011458
Cody Kesting70fa2b22020-12-02 12:16:56 -080011459 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11460 // (if the Binder died)
11461 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11462 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011463 return;
11464 }
11465
Cody Kesting46cb1672020-03-04 13:35:20 -080011466 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11467 // incremented when the NetworkRequestInfo is created as part of
11468 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011469 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011470
Cody Kesting31f1ff62020-03-05 10:46:02 -080011471 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011472 }
11473
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011474 private void handleNetworkTestedWithExtras(
11475 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11476 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011477 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011478 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011479 final ConnectivityReport report =
11480 new ConnectivityReport(
11481 reportEvent.mNai.network,
11482 reportEvent.mTimestampMillis,
11483 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011484 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011485 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011486 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011487
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011488 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011489 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011490 for (final IConnectivityDiagnosticsCallback cb : results) {
11491 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011492 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011493 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011494 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011495 }
11496 }
11497 }
11498
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011499 private void handleDataStallSuspected(
11500 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11501 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011502 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011503 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011504 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011505 new DataStallReport(
11506 nai.network,
11507 timestampMillis,
11508 detectionMethod,
11509 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011510 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011511 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011512 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011513 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011514 for (final IConnectivityDiagnosticsCallback cb : results) {
11515 try {
11516 cb.onDataStallSuspected(report);
11517 } catch (RemoteException ex) {
11518 loge("Error invoking onDataStallSuspected", ex);
11519 }
11520 }
11521 }
11522
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011523 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011524 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11525 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11526 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11527
11528 // If the Network is being re-validated as a result of this call to
11529 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11530 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011531 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011532 getMatchingPermissionedCallbacks(
11533 nai,
11534 reportedNetworkConnectivityInfo.isNetworkRevalidating
11535 ? Process.INVALID_UID
11536 : reportedNetworkConnectivityInfo.reporterUid);
11537
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011538 for (final IConnectivityDiagnosticsCallback cb : results) {
11539 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011540 cb.onNetworkConnectivityReported(
11541 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011542 } catch (RemoteException ex) {
11543 loge("Error invoking onNetworkConnectivityReported", ex);
11544 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011545
11546 // If the Network isn't re-validating, also provide the cached report. If there is no
11547 // cached report, the Network is still being validated and a report will be sent once
11548 // validation is complete. Note that networks which never undergo validation will still
11549 // have a cached ConnectivityReport with RESULT_SKIPPED.
11550 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11551 try {
11552 cb.onConnectivityReportAvailable(cachedReport);
11553 } catch (RemoteException ex) {
11554 loge("Error invoking onConnectivityReportAvailable", ex);
11555 }
11556 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011557 }
11558 }
11559
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011560 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011561 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11562 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011563 sanitized.setUids(null);
11564 sanitized.setAdministratorUids(new int[0]);
11565 sanitized.setOwnerUid(Process.INVALID_UID);
11566 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011567 }
11568
Cody Kestingf1120be2020-08-03 18:01:40 -070011569 /**
11570 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11571 *
11572 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11573 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011574 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011575 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011576 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011577 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011578 mConnectivityDiagnosticsCallbacks.entrySet()) {
11579 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11580 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011581
James Mattis64b8b0f2020-11-24 17:40:49 -080011582 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011583 if (!nai.satisfies(nri.mRequests.get(0))) {
11584 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011585 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011586
11587 // UID for this callback must either be:
11588 // - INVALID_UID (which sends callbacks to all UIDs), or
11589 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11590 // notified as a result)
11591 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11592 continue;
11593 }
11594
11595 if (!checkConnectivityDiagnosticsPermissions(
11596 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11597 continue;
11598 }
11599
11600 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011601 }
11602 return results;
11603 }
11604
Cody Kesting7474f672021-05-11 14:22:40 -070011605 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11606 @NonNull NetworkAgentInfo nai) {
11607 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11608 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11609 }
11610
Cody Kesting160ef392021-05-05 13:17:22 -070011611 private boolean hasLocationPermission(String packageName, int uid) {
11612 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11613 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11614 // call in a try-catch.
11615 try {
11616 if (!mLocationPermissionChecker.checkLocationPermission(
11617 packageName, null /* featureId */, uid, null /* message */)) {
11618 return false;
11619 }
11620 } catch (SecurityException e) {
11621 return false;
11622 }
11623
11624 return true;
11625 }
11626
11627 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11628 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011629 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011630 && virtual.networkCapabilities.getOwnerUid() == uid
11631 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11632 return true;
11633 }
11634 }
11635
11636 return false;
11637 }
11638
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011639 @VisibleForTesting
11640 boolean checkConnectivityDiagnosticsPermissions(
11641 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11642 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11643 return true;
11644 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011645 if (mAllowSysUiConnectivityReports
11646 && checkSystemBarServicePermission(callbackPid, callbackUid)) {
11647 return true;
11648 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011649
Cody Kesting160ef392021-05-05 13:17:22 -070011650 // Administrator UIDs also contains the Owner UID
11651 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11652 if (!CollectionUtils.contains(administratorUids, callbackUid)
11653 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011654 return false;
11655 }
11656
Cody Kesting7474f672021-05-11 14:22:40 -070011657 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11658 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011659 }
11660
Cody Kestingd199a9d2019-12-17 12:55:28 -080011661 @Override
11662 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011663 @NonNull IConnectivityDiagnosticsCallback callback,
11664 @NonNull NetworkRequest request,
11665 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011666 Objects.requireNonNull(callback, "callback must not be null");
11667 Objects.requireNonNull(request, "request must not be null");
11668 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11669
Cody Kesting73708bf2019-12-18 10:57:50 -080011670 if (request.legacyType != TYPE_NONE) {
11671 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11672 + " Please use NetworkCapabilities instead.");
11673 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011674 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011675 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011676
11677 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11678 // and administrator uids to be safe.
11679 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011680 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011681
11682 final NetworkRequest requestWithId =
11683 new NetworkRequest(
11684 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11685
11686 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11687 //
11688 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11689 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11690 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011691 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011692 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011693 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011694
11695 mConnectivityDiagnosticsHandler.sendMessage(
11696 mConnectivityDiagnosticsHandler.obtainMessage(
11697 ConnectivityDiagnosticsHandler
11698 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11699 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011700 }
11701
11702 @Override
11703 public void unregisterConnectivityDiagnosticsCallback(
11704 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011705 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011706 mConnectivityDiagnosticsHandler.sendMessage(
11707 mConnectivityDiagnosticsHandler.obtainMessage(
11708 ConnectivityDiagnosticsHandler
11709 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011710 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011711 0,
11712 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011713 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011714
Yan Yanfe96dde2022-12-05 23:00:01 +000011715 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11716 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11717 if (underlyingNetworks == null) return false;
11718
11719 for (Network network : underlyingNetworks) {
11720 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11721 return true;
11722 }
11723 }
11724 return false;
11725 }
11726
Cody Kestingf53a0752020-04-15 12:33:28 -070011727 @Override
11728 public void simulateDataStall(int detectionMethod, long timestampMillis,
11729 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011730 Objects.requireNonNull(network, "network must not be null");
11731 Objects.requireNonNull(extras, "extras must not be null");
11732
paulhu3ffffe72021-09-16 10:15:22 +080011733 enforceAnyPermissionOf(mContext,
11734 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011735 android.Manifest.permission.NETWORK_STACK);
11736 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011737 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11738 throw new SecurityException(
11739 "Data Stall simulation is only possible for test networks or networks built on"
11740 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011741 }
11742
11743 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011744 if (nai == null
11745 || (nai.creatorUid != mDeps.getCallingUid()
11746 && nai.creatorUid != Process.SYSTEM_UID)) {
11747 throw new SecurityException(
11748 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011749 }
11750
Cody Kesting652e3ec2020-05-21 12:08:21 -070011751 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11752 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11753 // Data Stall information as a DataStallReportParcelable and passing to
11754 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11755 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011756 final DataStallReportParcelable p = new DataStallReportParcelable();
11757 p.timestampMillis = timestampMillis;
11758 p.detectionMethod = detectionMethod;
11759
11760 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11761 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11762 }
11763 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11764 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11765 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11766 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11767 }
11768
Serik Beketayevec8ad212020-12-07 22:43:07 -080011769 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011770 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011771
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011772 /**
11773 * Class to hold the information for network activity change event from idle timers
11774 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11775 */
11776 private static final class NetworkActivityParams {
11777 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011778 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
11779 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011780 public final int label;
11781 public final long timestampNs;
11782 // Uid represents the uid that was responsible for waking the radio.
11783 // -1 for no uid and uid is -1 if isActive is false.
11784 public final int uid;
11785
11786 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11787 this.isActive = isActive;
11788 this.label = label;
11789 this.timestampNs = timestampNs;
11790 this.uid = uid;
11791 }
11792 }
11793
lucaslin66f44212021-02-23 01:12:55 +080011794 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11795 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011796 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011797 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011798 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11799 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011800 }
lucaslin37a16d92021-01-21 19:48:09 +080011801
11802 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011803 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011804 mHandler.post(() -> {
11805 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011806 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011807 }
11808 });
lucaslin37a16d92021-01-21 19:48:09 +080011809 }
11810
11811 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011812 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011813 mHandler.post(() -> {
11814 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011815 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011816 }
11817 });
lucaslin66f44212021-02-23 01:12:55 +080011818 }
11819 }
11820
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011821 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080011822 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11823
11824 /**
11825 * Class used for updating network activity tracking with netd and notify network activity
11826 * changes.
11827 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011828 @VisibleForTesting
11829 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011830 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011831 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011832 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011833 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011834 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11835 new RemoteCallbackList<>();
11836 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011837 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011838 // If there is no default network, default network is considered active to keep the existing
11839 // behavior. Initial value is used until first connect to the default network.
11840 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011841 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011842 // Key is netId. Value is configured idle timer information.
11843 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011844 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011845 // Store netIds of Wi-Fi networks whose idletimers report that they are active
11846 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
11847 // Store netIds of cellular networks whose idletimers report that they are active
11848 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011849
Chalard Jean46bfbf02022-02-02 00:56:25 +090011850 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011851 public final int timeout;
11852 public final int transportType;
11853
11854 IdleTimerParams(int timeout, int transport) {
11855 this.timeout = timeout;
11856 this.transportType = transport;
11857 }
11858 }
11859
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011860 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011861 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011862 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011863 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011864 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011865 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011866 }
11867
11868 private void ensureRunningOnConnectivityServiceThread() {
11869 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11870 throw new IllegalStateException("Not running on ConnectivityService thread: "
11871 + Thread.currentThread().getName());
11872 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011873 }
11874
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011875 /**
11876 * Update network activity and call BatteryStats to update radio power state if the
11877 * mobile or Wi-Fi activity is changed.
11878 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
11879 * mobile network is active since BatteryStatsService only maintains a single power state
11880 * for the mobile network.
11881 * The Wi-Fi network is also the same.
11882 *
11883 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
11884 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
11885 * transports.
11886 */
11887 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
11888 final boolean isActive, final int uid) {
11889 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
11890 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
11891 + transportType);
11892 return;
11893 }
11894 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
11895 ? mActiveWifiNetworks : mActiveCellularNetworks;
11896
11897 final boolean wasEmpty = activeNetworks.isEmpty();
11898 if (isActive) {
11899 activeNetworks.add(netId);
11900 } else {
11901 activeNetworks.remove(netId);
11902 }
11903
11904 if (wasEmpty != activeNetworks.isEmpty()) {
11905 updateRadioPowerState(isActive, transportType, uid);
11906 }
11907 }
11908
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011909 private void handleDefaultNetworkActivity(final int transportType,
11910 final boolean isActive, final long timestampNs) {
11911 mIsDefaultNetworkActive = isActive;
11912 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
11913 isActive, timestampNs);
11914 if (isActive) {
11915 reportNetworkActive();
11916 }
11917 }
11918
11919 private void handleReportNetworkActivityWithNetIdLabel(
11920 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011921 final int netId = activityParams.label;
11922 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011923 if (idleTimerParams == null) {
11924 // This network activity change is not tracked anymore
11925 // This can happen if netd callback post activity change event message but idle
11926 // timer is removed before processing this message.
11927 return;
11928 }
11929 // TODO: if a network changes transports, storing the transport type in the
11930 // IdleTimerParams is not correct. Consider getting it from the network's
11931 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011932 final int transportType = idleTimerParams.transportType;
11933 maybeUpdateRadioPowerState(netId, transportType,
11934 activityParams.isActive, activityParams.uid);
11935
11936 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
11937 // This activity change is not for the default network.
11938 return;
11939 }
11940
11941 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011942 activityParams.timestampNs);
11943 }
11944
11945 private void handleReportNetworkActivityWithTransportTypeLabel(
11946 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011947 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011948 // This activity change is not for the current default network.
11949 // This can happen if netd callback post activity change event message but
11950 // the default network is lost before processing this message.
11951 return;
11952 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011953 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
11954 activityParams.timestampNs);
11955 }
11956
11957 /**
11958 * Handle network activity change
11959 */
11960 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
11961 ensureRunningOnConnectivityServiceThread();
11962 if (mTrackMultiNetworkActivities) {
11963 handleReportNetworkActivityWithNetIdLabel(activityParams);
11964 } else {
11965 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080011966 }
11967 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011968
lucaslin1193a5d2021-01-21 02:04:15 +080011969 private void reportNetworkActive() {
11970 final int length = mNetworkActivityListeners.beginBroadcast();
11971 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11972 try {
11973 for (int i = 0; i < length; i++) {
11974 try {
11975 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11976 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011977 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011978 }
11979 }
11980 } finally {
11981 mNetworkActivityListeners.finishBroadcast();
11982 }
11983 }
11984
lucaslin1a8b4c62021-01-21 02:02:55 +080011985 // This is deprecated and only to support legacy use cases.
11986 private int transportTypeToLegacyType(int type) {
11987 switch (type) {
11988 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011989 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011990 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011991 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011992 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011993 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011994 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011995 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011996 default:
11997 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11998 }
11999 return ConnectivityManager.TYPE_NONE;
12000 }
12001
12002 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12003 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12004 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12005 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12006 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12007 final long ident = Binder.clearCallingIdentity();
12008 try {
12009 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12010 RECEIVE_DATA_ACTIVITY_CHANGE,
12011 null /* resultReceiver */,
12012 null /* scheduler */,
12013 0 /* initialCode */,
12014 null /* initialData */,
12015 null /* initialExtra */);
12016 } finally {
12017 Binder.restoreCallingIdentity(ident);
12018 }
12019 }
12020
12021 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012022 * Get idle timer label
12023 */
12024 @VisibleForTesting
12025 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12026 final int netId, final int transportType) {
12027 return trackMultiNetworkActivities ? netId : transportType;
12028 }
12029
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012030 private boolean maybeCreateIdleTimer(
12031 String iface, int netId, int timeout, int transportType) {
12032 if (timeout <= 0 || iface == null) return false;
12033 try {
12034 final String label = Integer.toString(getIdleTimerLabel(
12035 mTrackMultiNetworkActivities, netId, transportType));
12036 mNetd.idletimerAddInterface(iface, timeout, label);
12037 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12038 return true;
12039 } catch (Exception e) {
12040 loge("Exception in createIdleTimer", e);
12041 return false;
12042 }
12043 }
12044
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012045 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012046 * Setup data activity tracking for the given network.
12047 *
12048 * Every {@code setupDataActivityTracking} should be paired with a
12049 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012050 *
12051 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012052 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012053 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012054 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012055 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012056 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012057
12058 final int timeout;
12059 final int type;
12060
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012061 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12062 // Do not track VPN network.
12063 return false;
12064 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012065 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12066 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012067 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012068 10);
12069 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12070 } else if (networkAgent.networkCapabilities.hasTransport(
12071 NetworkCapabilities.TRANSPORT_WIFI)) {
12072 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012073 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012074 15);
12075 type = NetworkCapabilities.TRANSPORT_WIFI;
12076 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012077 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012078 }
12079
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012080 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12081 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12082 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12083 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12084 // state only about a network that has an idletimer.
12085 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012086 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012087 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012088 }
12089
12090 /**
12091 * Remove data activity tracking when network disconnects.
12092 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012093 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12094 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012095 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012096 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012097 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12098
lucaslinb961efc2021-01-21 02:03:17 +080012099 if (iface == null) return;
12100
12101 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012102 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12103 // Do not track VPN network.
12104 return;
12105 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012106 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12107 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12108 type = NetworkCapabilities.TRANSPORT_WIFI;
12109 } else {
12110 return; // do not track any other networks
12111 }
12112
12113 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012114 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012115 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012116 if (params == null) {
12117 // IdleTimer is not added if the configured timeout is 0 or negative value
12118 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012119 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012120 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012121 final String label = Integer.toString(getIdleTimerLabel(
12122 mTrackMultiNetworkActivities, netId, params.transportType));
12123 // The call fails silently if no idle timer setup for this interface
12124 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012125 } catch (Exception e) {
12126 // You shall not crash!
12127 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012128 }
12129 }
12130
Motomu Utsumi6225d572023-05-29 15:08:57 +090012131 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12132 boolean hasIdleTimer) {
12133 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012134 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012135 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012136 // If only the default network is tracked, callbacks are called only when the
12137 // network has the idle timer.
12138 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012139 reportNetworkActive();
12140 }
12141 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012142 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012143 // If there is no default network, default network is considered active to keep the
12144 // existing behavior.
12145 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090012146 }
12147 }
12148
lucaslin1a8b4c62021-01-21 02:02:55 +080012149 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012150 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012151 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012152 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012153 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012154 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012155 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12156 // first connected and remove when the network is disconnected.
12157 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12158 // becomes the default network and remove when the network becomes no longer the default
12159 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012160 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012161 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012162 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012163 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012164 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012165 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012166 removeDataActivityTracking(oldNetwork);
12167 }
12168 }
lucaslinb961efc2021-01-21 02:03:17 +080012169
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012170 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012171 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12172 switch (transportType) {
12173 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012174 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012175 break;
12176 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012177 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012178 break;
12179 default:
12180 logw("Untracked transport type:" + transportType);
12181 }
12182 }
lucaslin1193a5d2021-01-21 02:04:15 +080012183
12184 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012185 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012186 }
12187
12188 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12189 mNetworkActivityListeners.register(l);
12190 }
12191
12192 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12193 mNetworkActivityListeners.unregister(l);
12194 }
lucaslin012f7a12021-01-21 02:04:35 +080012195
12196 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012197 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012198 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012199 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012200 pw.println("Idle timers:");
12201 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012202 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12203 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12204 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012205 pw.print(" timeout="); pw.print(params.timeout);
12206 pw.print(" type="); pw.println(params.transportType);
12207 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012208 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12209 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012210 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012211 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12212 // be accessed from handler thread, except dump(). As dump() is never called in
12213 // normal usage, it would be needlessly expensive to lock the collection only for
12214 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012215 // So catching the exception and logging.
12216 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012217 }
12218 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012219 }
James Mattis47db0582021-01-01 14:13:35 -080012220
Daniel Brightf9e945b2020-06-15 16:10:01 -070012221 /**
12222 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12223 *
12224 * @param socketInfo the socket information
12225 * @param callback the callback to register
12226 */
12227 @Override
12228 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12229 @NonNull final IQosCallback callback) {
12230 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12231 if (nai == null || nai.networkCapabilities == null) {
12232 try {
12233 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12234 } catch (final RemoteException ex) {
12235 loge("registerQosCallbackInternal: RemoteException", ex);
12236 }
12237 return;
12238 }
12239 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12240 }
12241
12242 /**
12243 * Register a {@link IQosCallback} with base {@link QosFilter}.
12244 *
12245 * @param filter the filter to register
12246 * @param callback the callback to register
12247 * @param nai the agent information related to the filter's network
12248 */
12249 @VisibleForTesting
12250 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12251 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012252 Objects.requireNonNull(filter, "filter must be non-null");
12253 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012254
12255 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012256 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12257 // on this network is unregistered when the app loses permission or b) no QoS
12258 // callbacks are sent for restricted networks unless the app currently has permission
12259 // to access restricted networks.
12260 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012261 }
12262 mQosCallbackTracker.registerCallback(callback, filter, nai);
12263 }
12264
12265 /**
12266 * Unregisters the given callback.
12267 *
12268 * @param callback the callback to unregister
12269 */
12270 @Override
12271 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012272 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012273 mQosCallbackTracker.unregisterCallback(callback);
12274 }
James Mattis47db0582021-01-01 14:13:35 -080012275
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012276 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12277 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12278 // Enterprise device can be fully managed like device owner and such use case
12279 // also should be supported. Calling app check for work profile and fully managed device
12280 // is already done in DevicePolicyManager.
12281 // This check is an extra caution to be sure device is fully managed or not.
12282 final UserManager um = mContext.getSystemService(UserManager.class);
12283 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12284 if (um.isManagedProfile(profile.getIdentifier())) {
12285 return true;
12286 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012287 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012288 return false;
12289 }
12290
James Mattis45d81842021-01-10 14:24:24 -080012291 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012292 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012293 *
12294 * See the documentation for the individual preferences for a description of the supported
12295 * behaviors.
12296 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012297 * @param profile If the device owner is set, any profile is allowed.
12298 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012299 * @param preferences the list of profile network preferences for the
12300 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012301 * @param listener an optional listener to listen for completion of the operation.
12302 */
12303 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012304 public void setProfileNetworkPreferences(
12305 @NonNull final UserHandle profile,
12306 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012307 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012308 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012309 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012310
12311 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012312 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12313 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12314 .build();
12315 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012316 }
12317
paulhu3ffffe72021-09-16 10:15:22 +080012318 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012319 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012320 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012321 }
12322 if (profile.getIdentifier() < 0) {
12323 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12324 + "UserHandle.CURRENT not supported)");
12325 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012326 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12327 throw new IllegalArgumentException("Profile must be a managed profile "
12328 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012329 }
paulhuaa0743d2021-05-26 21:56:03 +080012330
Chalard Jean0606fc82022-12-14 20:34:43 +090012331 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012332 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012333 for (final ProfileNetworkPreference preference : preferences) {
12334 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012335 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012336 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012337 switch (preference.getPreference()) {
12338 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12339 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012340 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012341 if (preference.getPreferenceEnterpriseId() != 0) {
12342 throw new IllegalArgumentException(
12343 "Invalid enterprise identifier in setProfileNetworkPreferences");
12344 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012345 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012346 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12347 blockingNonEnterprise = true;
12348 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012349 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12350 allowFallback = false;
12351 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012352 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012353 // This code is needed even though there is a check later on,
12354 // because isRangeAlreadyInPreferenceList assumes that every preference
12355 // has a UID list.
12356 if (hasDefaultPreference) {
12357 throw new IllegalArgumentException(
12358 "Default profile preference should not be set along with other "
12359 + "preference");
12360 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012361 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12362 throw new IllegalArgumentException(
12363 "Invalid enterprise identifier in setProfileNetworkPreferences");
12364 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012365 final Set<UidRange> uidRangeSet =
12366 getUidListToBeAppliedForNetworkPreference(profile, preference);
12367 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12368 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12369 } else {
12370 throw new IllegalArgumentException(
12371 "Overlapping uid range in setProfileNetworkPreferences");
12372 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012373 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012374 nc.addEnterpriseId(
12375 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012376 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12377 break;
12378 default:
12379 throw new IllegalArgumentException(
12380 "Invalid preference in setProfileNetworkPreferences");
12381 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012382 preferenceList.add(new ProfileNetworkPreferenceInfo(
12383 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012384 if (hasDefaultPreference && preferenceList.size() > 1) {
12385 throw new IllegalArgumentException(
12386 "Default profile preference should not be set along with other preference");
12387 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012388 }
12389 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012390 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012391 }
12392
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012393 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12394 @NonNull final UserHandle profile,
12395 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12396 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012397 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12398 profileNetworkPreference.getIncludedUids());
12399
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012400 if (uidRangeSet.size() > 0) {
12401 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12402 throw new IllegalArgumentException(
12403 "Allow uid range is outside the uid range of profile.");
12404 }
12405 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012406 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012407 profileNetworkPreference.getExcludedUids());
12408 if (disallowUidRangeSet.size() > 0) {
12409 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12410 throw new IllegalArgumentException(
12411 "disallow uid range is outside the uid range of profile.");
12412 }
12413 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12414 disallowUidRangeSet);
12415 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012416 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012417 uidRangeSet.add(profileUids);
12418 }
12419 }
12420 return uidRangeSet;
12421 }
12422
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012423 private boolean isEnterpriseIdentifierValid(
12424 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012425 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012426 return true;
12427 }
12428 return false;
12429 }
12430
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012431 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012432 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012433 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012434 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012435 // The NRI for a user should contain the request for capabilities.
12436 // If fallback to default network is needed then NRI should include
12437 // the request for the default network. Create an image of it to
12438 // have the correct UIDs in it (also a request can only be part of one NRI, because
12439 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012440 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12441 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012442 if (pref.allowFallback) {
12443 nrs.add(createDefaultInternetRequestForTransport(
12444 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12445 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012446 if (VDBG) {
12447 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12448 pref.capabilities.getUids()));
12449 }
12450
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012451 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012452 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012453 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012454 result.add(nri);
12455 }
12456 return result;
12457 }
12458
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012459 /**
12460 * Compare if the given UID range sets have the same UIDs.
12461 *
12462 */
12463 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012464 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012465 @NonNull Set<UidRange> uidRangeSet) {
12466 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12467 return false;
12468 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012469 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012470 if (UidRangeUtils.doesRangeSetOverlap(
12471 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12472 return true;
12473 }
12474 }
12475 return false;
12476 }
12477
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012478 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012479 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012480 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012481 /*
12482 * handleSetProfileNetworkPreference is always called for single user.
12483 * preferenceList only contains preferences for different uids within the same user
12484 * (enforced by getUidListToBeAppliedForNetworkPreference).
12485 * Clear all the existing preferences for the user before applying new preferences.
12486 *
12487 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012488 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12489 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012490 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12491 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012492
paulhu74128522021-09-28 02:29:03 +000012493 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12494 addPerAppDefaultNetworkRequests(
12495 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012496 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012497
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012498 // Finally, rematch.
12499 rematchAllNetworksAndRequests();
12500
12501 if (null != listener) {
12502 try {
12503 listener.onComplete();
12504 } catch (RemoteException e) {
12505 loge("Listener for setProfileNetworkPreference has died");
12506 }
12507 }
12508 }
12509
paulhu51f77dc2021-06-07 02:34:20 +000012510 @VisibleForTesting
12511 @NonNull
12512 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12513 @NonNull final Set<Integer> uids) {
12514 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12515 if (uids.size() == 0) {
12516 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12517 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12518 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12519 return nris;
12520 }
12521
12522 final List<NetworkRequest> requests = new ArrayList<>();
12523 // The NRI should be comprised of two layers:
12524 // - The request for the mobile network preferred.
12525 // - The request for the default network, for fallback.
12526 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012527 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012528 requests.add(createDefaultInternetRequestForTransport(
12529 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12530 final Set<UidRange> ranges = new ArraySet<>();
12531 for (final int uid : uids) {
12532 ranges.add(new UidRange(uid, uid));
12533 }
12534 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012535 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012536 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012537 return nris;
12538 }
12539
12540 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012541 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012542 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12543 addPerAppDefaultNetworkRequests(
12544 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012545 // Finally, rematch.
12546 rematchAllNetworksAndRequests();
12547 }
12548
Patrick Rohr2857ac42022-01-21 14:58:16 +010012549 private void handleIngressRateLimitChanged() {
12550 final long oldIngressRateLimit = mIngressRateLimit;
12551 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12552 mContext);
12553 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12554 if (canNetworkBeRateLimited(networkAgent)) {
12555 // If rate limit has previously been enabled, remove the old limit first.
12556 if (oldIngressRateLimit >= 0) {
12557 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12558 }
12559 if (mIngressRateLimit >= 0) {
12560 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12561 mIngressRateLimit);
12562 }
12563 }
12564 }
12565 }
12566
12567 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012568 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012569 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012570
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012571 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12572 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12573 // internet connectivity can be rate limited.
12574 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12575 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012576 return false;
12577 }
12578
12579 final String iface = networkAgent.linkProperties.getInterfaceName();
12580 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012581 // This may happen in tests, but if there is no interface then there is nothing that
12582 // can be rate limited.
12583 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012584 return false;
12585 }
12586 return true;
12587 }
12588
James Mattis45d81842021-01-10 14:24:24 -080012589 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012590 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12591 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012592 }
12593
12594 /**
12595 * Used by automotive devices to set the network preferences used to direct traffic at an
12596 * application level as per the given OemNetworkPreferences. An example use-case would be an
12597 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12598 * vehicle via a particular network.
12599 *
12600 * Calling this will overwrite the existing preference.
12601 *
James Mattisda32cfe2021-01-26 16:23:52 -080012602 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012603 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012604 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012605 */
James Mattis47db0582021-01-01 14:13:35 -080012606 @Override
James Mattis45d81842021-01-10 14:24:24 -080012607 public void setOemNetworkPreference(
12608 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012609 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012610
James Mattisfa270db2021-05-31 17:11:10 -070012611 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12612 // Only bypass the permission/device checks if this is a valid test request.
12613 if (isValidTestOemNetworkPreference(preference)) {
12614 enforceManageTestNetworksPermission();
12615 } else {
12616 enforceAutomotiveDevice();
12617 enforceOemNetworkPreferencesPermission();
12618 validateOemNetworkPreferences(preference);
12619 }
James Mattis45d81842021-01-10 14:24:24 -080012620
James Mattis45d81842021-01-10 14:24:24 -080012621 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12622 new Pair<>(preference, listener)));
12623 }
12624
James Mattisfa270db2021-05-31 17:11:10 -070012625 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012626 * Sets the specified UIDs to get/receive the VPN as the only default network.
12627 *
12628 * Calling this will overwrite the existing network preference for this session, and the
12629 * specified UIDs won't get any default network when no VPN is connected.
12630 *
12631 * @param session The VPN session which manages the passed UIDs.
12632 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12633 * setting for this session if the array is empty. Null is not allowed, the
12634 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12635 * @hide
12636 */
12637 @Override
12638 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12639 Objects.requireNonNull(ranges);
12640 enforceNetworkStackOrSettingsPermission();
12641 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12642 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12643 throw new IllegalArgumentException(
12644 "setVpnNetworkPreference: Passed UID ranges overlap");
12645 }
12646
12647 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12648 new VpnNetworkPreferenceInfo(session,
12649 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12650 }
12651
12652 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12653 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12654
12655 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12656 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12657
12658 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12659 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12660 // Finally, rematch.
12661 rematchAllNetworksAndRequests();
12662 }
12663
12664 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12665 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12666 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12667 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12668 final List<NetworkRequest> requests = new ArrayList<>();
12669 // Request VPN only, so other networks won't be the fallback options when VPN is not
12670 // connected temporarily.
12671 requests.add(createVpnRequest());
12672 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12673 setNetworkRequestUids(requests, uidRanges);
12674 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12675 }
12676 return nris;
12677 }
12678
12679 /**
James Mattisfa270db2021-05-31 17:11:10 -070012680 * Check the validity of an OEM network preference to be used for testing purposes.
12681 * @param preference the preference to validate
12682 * @return true if this is a valid OEM network preference test request.
12683 */
12684 private boolean isValidTestOemNetworkPreference(
12685 @NonNull final OemNetworkPreferences preference) {
12686 // Allow for clearing of an existing OemNetworkPreference used for testing.
12687 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12688 // changes after this check is complete. This is an unlikely scenario as calling of this API
12689 // is controlled by the OEM therefore the added complexity is not worth adding given those
12690 // circumstances. That said, it is an edge case to be aware of hence this comment.
12691 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12692 && isTestOemNetworkPreference(mOemNetworkPreferences);
12693 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12694 }
12695
12696 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12697 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12698 return prefMap.size() == 1
12699 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12700 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12701 }
12702
James Mattis45d81842021-01-10 14:24:24 -080012703 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12704 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12705 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012706 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12707 throw new IllegalArgumentException(
12708 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12709 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012710 }
12711 }
12712 }
12713
12714 private void handleSetOemNetworkPreference(
12715 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012716 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012717 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12718 if (DBG) {
12719 log("set OEM network preferences :" + preference.toString());
12720 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012721
James Mattiscb1e0362021-04-06 17:07:42 -070012722 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012723 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12724 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12725 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012726 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012727
12728 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012729 try {
12730 listener.onComplete();
12731 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012732 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012733 }
James Mattis45d81842021-01-10 14:24:24 -080012734 }
12735 }
12736
paulhu74128522021-09-28 02:29:03 +000012737 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012738 // Skip the requests which are set by other network preference. Because the uid range rules
12739 // should stay in netd.
12740 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012741 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012742 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012743 }
12744
James Mattis3ce3d3c2021-02-09 18:18:28 -080012745 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12746 ensureRunningOnConnectivityServiceThread();
12747 mDefaultNetworkRequests.addAll(nris);
12748 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12749 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012750 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012751 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12752 nrisToRegister.addAll(
12753 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12754 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012755 }
12756
12757 /**
12758 * All current requests that are tracking the default network need to be assessed as to whether
12759 * or not the current set of per-application default requests will be changing their default
12760 * network. If so, those requests will need to be updated so that they will send callbacks for
12761 * default network changes at the appropriate time. Additionally, those requests tracking the
12762 * default that were previously updated by this flow will need to be reassessed.
12763 * @return the nris which will need to be updated.
12764 */
12765 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12766 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12767 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12768 // same nri in the map's values for each of its NetworkRequest objects.
12769 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012770 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012771 // Include this nri if it is currently being tracked.
12772 if (isPerAppTrackedNri(nri)) {
12773 defaultCallbackRequests.add(nri);
12774 continue;
12775 }
12776 // We only track callbacks for requests tracking the default.
12777 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12778 continue;
12779 }
12780 // Include this nri if it will be tracked by the new per-app default requests.
12781 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012782 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012783 if (isNriGoingToBeTracked) {
12784 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012785 }
12786 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012787 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012788 }
12789
James Mattis3ce3d3c2021-02-09 18:18:28 -080012790 /**
12791 * Create nris for those network requests that are currently tracking the default network that
12792 * are being controlled by a per-application default.
12793 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12794 * foundation when creating the nri. Important items include the calling uid's original
12795 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12796 * requests are assumed to have already been validated as needing to be updated.
12797 * @return the Set of nris to use when registering network requests.
12798 */
12799 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12800 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12801 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12802 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12803 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012804 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012805
Chalard Jean9473c982021-07-29 20:03:04 +090012806 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012807 if (trackingNri == mDefaultRequest) {
12808 callbackRequestsToRegister.add(new NetworkRequestInfo(
12809 callbackRequest,
12810 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12811 continue;
12812 }
12813
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012814 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012815 callbackRequestsToRegister.add(new NetworkRequestInfo(
12816 callbackRequest,
12817 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012818 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012819 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012820 }
12821 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012822 }
12823
Chalard Jean17215832021-03-01 14:06:28 +090012824 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12825 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012826 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012827 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012828 }
12829 }
12830
James Mattis45d81842021-01-10 14:24:24 -080012831 /**
12832 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12833 */
12834 @VisibleForTesting
12835 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012836 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012837 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012838 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012839 final SparseArray<Set<Integer>> uids =
12840 createUidsFromOemNetworkPreferences(preference);
12841 for (int i = 0; i < uids.size(); i++) {
12842 final int key = uids.keyAt(i);
12843 final Set<Integer> value = uids.valueAt(i);
12844 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12845 // No need to add an nri without any requests.
12846 if (0 == nri.mRequests.size()) {
12847 continue;
12848 }
12849 nris.add(nri);
12850 }
12851
12852 return nris;
12853 }
12854
12855 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12856 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012857 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012858 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012859 final List<UserHandle> users =
12860 mContext.getSystemService(UserManager.class).getUserHandles(true);
12861 if (null == users || users.size() == 0) {
12862 if (VDBG || DDBG) {
12863 log("No users currently available for setting the OEM network preference.");
12864 }
James Mattisb6b6a432021-06-01 22:30:36 -070012865 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012866 }
James Mattis45d81842021-01-10 14:24:24 -080012867 for (final Map.Entry<String, Integer> entry :
12868 preference.getNetworkPreferences().entrySet()) {
12869 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012870 // Add the rules for all users as this policy is device wide.
12871 for (final UserHandle user : users) {
12872 try {
12873 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12874 if (!prefToUids.contains(pref)) {
12875 prefToUids.put(pref, new ArraySet<>());
12876 }
12877 prefToUids.get(pref).add(uid);
12878 } catch (PackageManager.NameNotFoundException e) {
12879 // Although this may seem like an error scenario, it is ok that uninstalled
12880 // packages are sent on a network preference as the system will watch for
12881 // package installations associated with this network preference and update
12882 // accordingly. This is done to minimize race conditions on app install.
12883 continue;
James Mattis45d81842021-01-10 14:24:24 -080012884 }
James Mattis45d81842021-01-10 14:24:24 -080012885 }
12886 }
James Mattisb6b6a432021-06-01 22:30:36 -070012887 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012888 }
12889
12890 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12891 @OemNetworkPreferences.OemNetworkPreference final int preference,
12892 @NonNull final Set<Integer> uids) {
12893 final List<NetworkRequest> requests = new ArrayList<>();
12894 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12895 switch (preference) {
12896 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12897 requests.add(createUnmeteredNetworkRequest());
12898 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012899 requests.add(createDefaultInternetRequestForTransport(
12900 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012901 break;
12902 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12903 requests.add(createUnmeteredNetworkRequest());
12904 requests.add(createOemPaidNetworkRequest());
12905 break;
12906 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12907 requests.add(createOemPaidNetworkRequest());
12908 break;
12909 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12910 requests.add(createOemPrivateNetworkRequest());
12911 break;
James Mattisfa270db2021-05-31 17:11:10 -070012912 case OEM_NETWORK_PREFERENCE_TEST:
12913 requests.add(createUnmeteredNetworkRequest());
12914 requests.add(createTestNetworkRequest());
12915 requests.add(createDefaultRequest());
12916 break;
12917 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12918 requests.add(createTestNetworkRequest());
12919 break;
James Mattis45d81842021-01-10 14:24:24 -080012920 default:
12921 // This should never happen.
12922 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12923 + " called with invalid preference of " + preference);
12924 }
12925
James Mattisfa270db2021-05-31 17:11:10 -070012926 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012927 for (final int uid : uids) {
12928 ranges.add(new UidRange(uid, uid));
12929 }
12930 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012931 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012932 }
12933
12934 private NetworkRequest createUnmeteredNetworkRequest() {
12935 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12936 .addCapability(NET_CAPABILITY_NOT_METERED)
12937 .addCapability(NET_CAPABILITY_VALIDATED);
12938 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12939 }
12940
12941 private NetworkRequest createOemPaidNetworkRequest() {
12942 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12943 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12944 .addCapability(NET_CAPABILITY_OEM_PAID)
12945 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12946 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12947 }
12948
12949 private NetworkRequest createOemPrivateNetworkRequest() {
12950 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12951 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12952 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12953 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12954 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12955 }
12956
12957 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012958 final NetworkCapabilities netcap = new NetworkCapabilities();
12959 netcap.addCapability(NET_CAPABILITY_INTERNET);
12960 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12961 return netcap;
12962 }
12963
12964 private NetworkRequest createTestNetworkRequest() {
12965 final NetworkCapabilities netcap = new NetworkCapabilities();
12966 netcap.clearAll();
12967 netcap.addTransportType(TRANSPORT_TEST);
12968 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012969 }
James Mattis47db0582021-01-01 14:13:35 -080012970 }
markchien738ad912021-12-09 18:15:45 +080012971
Ken Chen24330172023-10-20 13:02:14 +080012972 @TargetApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080012973 @Override
Junyu Laidf210362023-10-24 02:47:50 +000012974 public void setDataSaverEnabled(final boolean enable) {
12975 enforceNetworkStackOrSettingsPermission();
12976 try {
12977 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
12978 if (!ret) {
12979 throw new IllegalStateException("Error when changing iptables: " + enable);
12980 }
12981 } catch (RemoteException e) {
12982 // Lack of permission or binder errors.
12983 throw new IllegalStateException(e);
12984 }
Ken Chen24330172023-10-20 13:02:14 +080012985
12986 try {
12987 mBpfNetMaps.setDataSaverEnabled(enable);
12988 } catch (ServiceSpecificException | UnsupportedOperationException e) {
12989 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
12990 }
Junyu Laidf210362023-10-24 02:47:50 +000012991 }
12992
12993 @Override
markchien738ad912021-12-09 18:15:45 +080012994 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12995 enforceNetworkStackOrSettingsPermission();
12996
12997 try {
12998 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012999 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013000 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013001 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013002 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013003 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013004 throw new IllegalStateException(e);
13005 }
13006 }
13007
13008 @Override
13009 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13010 enforceNetworkStackOrSettingsPermission();
13011
13012 try {
13013 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013014 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013015 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013016 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013017 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013018 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013019 throw new IllegalStateException(e);
13020 }
13021 }
markchiene1561fa2021-12-09 22:00:56 +080013022
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013023 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13024 throws PackageManager.NameNotFoundException {
13025 final PackageManager pm = mContext.getPackageManager();
13026 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13027 if (appId < Process.FIRST_APPLICATION_UID) {
13028 throw new RuntimeException("Can't set package firewall rule for system app "
13029 + packageName + " with appId " + appId);
13030 }
13031 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13032 final int uid = uh.getUid(appId);
13033 setUidFirewallRule(chain, uid, rule);
13034 }
13035 return appId;
13036 }
13037
markchiene1561fa2021-12-09 22:00:56 +080013038 @Override
markchien3c04e662022-03-22 16:29:56 +080013039 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013040 enforceNetworkStackOrSettingsPermission();
13041
markchien3c04e662022-03-22 16:29:56 +080013042 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13043 int firewallRule = getFirewallRuleType(chain, rule);
13044
13045 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13046 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13047 }
13048
markchiene1561fa2021-12-09 22:00:56 +080013049 try {
markchien3c04e662022-03-22 16:29:56 +080013050 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013051 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013052 throw new IllegalStateException(e);
13053 }
13054 }
markchien98a6f952022-01-13 23:43:53 +080013055
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013056 private int getPackageFirewallRule(final int chain, final String packageName)
13057 throws PackageManager.NameNotFoundException {
13058 final PackageManager pm = mContext.getPackageManager();
13059 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13060 return getUidFirewallRule(chain, appId);
13061 }
13062
Motomu Utsumi900b8062023-01-19 16:16:49 +090013063 @Override
13064 public int getUidFirewallRule(final int chain, final int uid) {
13065 enforceNetworkStackOrSettingsPermission();
13066 return mBpfNetMaps.getUidRule(chain, uid);
13067 }
13068
markchien3c04e662022-03-22 16:29:56 +080013069 private int getFirewallRuleType(int chain, int rule) {
13070 final int defaultRule;
13071 switch (chain) {
13072 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013073 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13074 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013075 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013076 defaultRule = FIREWALL_RULE_ALLOW;
13077 break;
13078 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13079 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13080 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13081 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013082 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013083 defaultRule = FIREWALL_RULE_DENY;
13084 break;
13085 default:
13086 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13087 }
13088 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13089
13090 return rule;
13091 }
13092
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013093 private void closeSocketsForFirewallChainLocked(final int chain)
13094 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013095 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013096 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13097 // So, close all non-system socket owned by uids that are not explicitly allowed
13098 Set<Range<Integer>> ranges = new ArraySet<>();
13099 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13100 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13101 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13102 } else {
13103 // Denylist means the firewall allows all by default, uids must be explicitly denied
13104 // So, close socket owned by uids that are explicitly denied
13105 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13106 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13107 }
13108 }
13109
markchien98a6f952022-01-13 23:43:53 +080013110 @Override
13111 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13112 enforceNetworkStackOrSettingsPermission();
13113
13114 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013115 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013116 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013117 throw new IllegalStateException(e);
13118 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013119
Chalard Jeandf29a852023-05-29 17:02:43 +090013120 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013121 try {
13122 closeSocketsForFirewallChainLocked(chain);
13123 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13124 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13125 }
13126 }
markchien98a6f952022-01-13 23:43:53 +080013127 }
13128
markchien00a0bed2022-01-13 23:46:13 +080013129 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013130 public boolean getFirewallChainEnabled(final int chain) {
13131 enforceNetworkStackOrSettingsPermission();
13132
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013133 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013134 }
13135
13136 @Override
markchien00a0bed2022-01-13 23:46:13 +080013137 public void replaceFirewallChain(final int chain, final int[] uids) {
13138 enforceNetworkStackOrSettingsPermission();
13139
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013140 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013141 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013142
13143 @Override
13144 public IBinder getCompanionDeviceManagerProxyService() {
13145 enforceNetworkStackPermission(mContext);
13146 return mCdmps;
13147 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013148
13149 @Override
13150 public IBinder getRoutingCoordinatorService() {
13151 enforceNetworkStackPermission(mContext);
13152 return mRoutingCoordinatorService;
13153 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013154}