blob: 0ec0f13154e5e653b7daba90fb1bee75040ed8d1 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Mark Fasheh7c999d82023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
Chalard Jeane0aaca52023-10-17 13:23:07 +090022import static android.content.pm.PackageManager.FEATURE_LEANBACK;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090023import static android.content.pm.PackageManager.FEATURE_WATCH;
24import static android.content.pm.PackageManager.FEATURE_WIFI;
25import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090026import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090027import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
29import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
34import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Junyu Lai38c75032023-12-04 07:52:19 +000035import static android.net.ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090036import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
37import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000038import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang9fe47be2021-06-08 13:11:45 +080039import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070040import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080041import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
42import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
43import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090044import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090045import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090046import static android.net.ConnectivityManager.TYPE_MOBILE;
47import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
49import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
50import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
51import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
52import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
53import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
54import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
55import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070056import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090057import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070058import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090059import static android.net.ConnectivityManager.TYPE_WIFI;
60import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070061import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070062import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080063import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070066import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080067import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040068import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
75import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090077import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090079import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080080import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
81import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080082import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090083import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090084import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080085import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
86import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080087import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
88import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
89import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090090import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090091import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060092import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070093import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080094import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090095import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070096import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
97import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070098import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080099import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100100import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700101import static android.system.OsConstants.IPPROTO_TCP;
102import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900103
Junyu Lai155760b2023-10-05 14:51:00 +0800104import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
105import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
106import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
107import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
108import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Xiao Ma60142372022-07-16 17:30:20 +0900109import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800110import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800111import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
112import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
113import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900114import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900115
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800116import static java.util.Map.Entry;
117
Chalard Jean5b639762020-03-09 21:25:37 +0900118import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000119import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800120import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600121import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800122import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000123import android.app.ActivityManager;
124import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800125import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800126import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700127import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700128import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900129import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800130import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700131import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800132import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800133import android.content.ContentResolver;
134import android.content.Context;
135import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700136import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800137import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900138import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700139import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800140import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900141import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900142import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700143import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800144import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800145import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800146import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900147import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800148import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900149import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800150import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900151import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800152import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700153import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900154import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800155import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800157import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800158import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800159import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900160import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900161import android.net.INetworkMonitor;
162import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900163import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900164import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700165import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800166import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900167import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900168import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900169import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800170import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900171import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900172import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100173import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800174import android.net.NativeNetworkConfig;
175import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800176import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700177import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700178import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900179import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700180import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800181import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700182import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900183import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900184import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000185import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900186import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700187import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900188import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700189import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900190import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700191import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800192import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900193import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700194import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000195import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800196import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900197import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800198import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400199import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700200import android.net.QosCallbackException;
201import android.net.QosFilter;
202import android.net.QosSocketFilter;
203import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700204import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800205import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800206import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900207import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400208import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800209import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800210import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400211import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800212import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900213import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900214import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900215import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900216import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800217import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900218import android.net.networkstack.ModuleNetworkStackClient;
219import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900220import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800221import android.net.resolv.aidl.DnsHealthEventParcel;
222import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
223import android.net.resolv.aidl.Nat64PrefixEventParcel;
224import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900225import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900226import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800227import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800228import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800229import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700230import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000231import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700233import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700234import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800235import android.os.Looper;
236import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700237import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700238import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900239import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800240import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700241import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700242import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800243import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700244import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900245import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900246import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700247import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700248import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400249import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800250import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900251import android.stats.connectivity.MeteredState;
252import android.stats.connectivity.RequestType;
253import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900254import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700255import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700256import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700257import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800258import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900259import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000260import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600261import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900262import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900263import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700264import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700265import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900266import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800267
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800268import androidx.annotation.RequiresApi;
269
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900270import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400271import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400272import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700273import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900274import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900275import com.android.metrics.ConnectionDurationForTransports;
276import com.android.metrics.ConnectionDurationPerTransports;
277import com.android.metrics.ConnectivitySampleMetricsHelper;
278import com.android.metrics.ConnectivityStateSample;
279import com.android.metrics.NetworkCountForTransports;
280import com.android.metrics.NetworkCountPerTransports;
281import com.android.metrics.NetworkDescription;
282import com.android.metrics.NetworkList;
283import com.android.metrics.NetworkRequestCount;
284import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800285import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900286import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800287import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000288import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900289import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800290import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900291import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900292import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100293import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900294import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
295import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900296import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800297import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800298import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100299import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000300import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800301import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
302import com.android.networkstack.apishim.ConstantsShim;
303import com.android.networkstack.apishim.common.BroadcastOptionsShim;
304import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900305import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900306import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000307import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900308import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800309import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800310import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900311import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900312import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900313import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500314import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700315import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900316import com.android.server.connectivity.FullScore;
Junyu Laif8dba342023-10-12 17:01:03 +0800317import com.android.server.connectivity.HandlerUtils;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900318import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900319import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000320import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100321import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700322import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900323import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700324import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600325import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900326import com.android.server.connectivity.NetworkNotificationManager;
327import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900328import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900329import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900330import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700331import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900332import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900333import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700334import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900335import com.android.server.connectivity.RoutingCoordinatorService;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800336import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000337import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800338import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600339
Josh Gao461a1222020-06-16 15:58:11 -0700340import libcore.io.IoUtils;
341
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900342import org.xmlpull.v1.XmlPullParserException;
343
The Android Open Source Project28527d22009-03-03 19:31:44 -0800344import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100345import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900346import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800347import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900348import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700349import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700350import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900351import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900352import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700353import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700354import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700355import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700356import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800357import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900358import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800359import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700360import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700361import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700362import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700363import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900364import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700365import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900366import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600367import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900368import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600369import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900370import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900371import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800372
373/**
374 * @hide
375 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800376public class ConnectivityService extends IConnectivityManager.Stub
377 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900378 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800379
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900380 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900381 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900382 private static final String NETWORK_ARG = "networks";
383 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800384 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900385
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900386 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900387 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
388 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800389
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900390 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700391
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100392 /**
393 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
394 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800395 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100396 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
397 * (preferably via runtime resource overlays).
398 */
399 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
400 "http://connectivitycheck.gstatic.com/generate_204";
401
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700402 // TODO: create better separation between radio types and network types
403
Robert Greenwalt2034b912009-08-12 16:08:25 -0700404 // how long to wait before switching back to a radio's default network
405 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
406 // system property that can override the above value
407 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
408 "android.telephony.apn-restore";
409
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900410 // How long to wait before putting up a "This network doesn't have an Internet connection,
411 // connect anyway?" dialog after the user selects a network that doesn't validate.
412 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
413
Chalard Jean5fb43c72022-09-08 19:03:14 +0900414 // How long to wait before considering that a network is bad in the absence of any form
415 // of connectivity (valid, partial, captive portal). If none has been detected after this
416 // delay, the stack considers this network bad, which may affect how it's handled in ranking
417 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900418 // Timeout in case the "actively prefer bad wifi" feature is on
419 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
420 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900421 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900422
junyulai0ac374f2020-12-14 18:41:52 +0800423 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900424 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
425 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800426 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700427
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800428 // Delimiter used when creating the broadcast delivery group for sending
429 // CONNECTIVITY_ACTION broadcast.
430 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
431
he_won.hwang881307a2022-03-15 21:23:52 +0900432 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900433 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900434
Daniel Brightf9e945b2020-06-15 16:10:01 -0700435 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900436 @VisibleForTesting
437 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700438
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900439 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700440 @VisibleForTesting
441 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900442
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900443 @VisibleForTesting
444 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800445 @VisibleForTesting
446 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900447 // True if the cell radio of the device is capable of time-sharing.
448 @VisibleForTesting
449 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900450
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800451 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800452 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800453 private final int mReleasePendingIntentDelayMs;
454
Chalard Jean46bfbf02022-02-02 00:56:25 +0900455 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900456
Motomu Utsumif360aa62023-01-30 17:52:20 +0900457 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700458
Chalard Jean9473c982021-07-29 20:03:04 +0900459 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800460 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700461 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800462 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700463
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900464 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700465
junyulaif2c67e42018-08-07 19:50:45 +0800466 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000467 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
468 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800469 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900470 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800471
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900472 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900473 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000474 private final int mWakeUpMark;
475 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000476 // The Context is created for UserHandle.ALL.
477 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900478 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900479 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700480 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700481 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800482
Chenbo Feng15416292018-11-08 17:36:21 -0800483 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800484 protected IDnsResolver mDnsResolver;
485 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800486 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700487 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900488 private final NetworkStatsManager mStatsManager;
489 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800490 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700491
Benedict Wong493e04b2018-11-09 14:45:34 -0800492 /**
493 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
494 * instances.
495 */
496 @GuardedBy("mTNSLock")
497 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800498 private final CompanionDeviceManagerProxyService mCdmps;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900499 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800500
501 private final Object mTNSLock = new Object();
502
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700503 private String mCurrentTcpBufferSizes;
504
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900505 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000506 new Class[] {
507 ConnectivityService.class,
508 NetworkAgent.class,
509 NetworkAgentInfo.class,
510 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900511
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500512 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400513 // Tear down networks that have no chance (e.g. even if validated) of becoming
514 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500515 // all networks have been rematched against all NetworkRequests.
516 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400517 // Don't reap networks. This should be passed when some networks have not yet been
518 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500519 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900520 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500521
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900522 private enum UnneededFor {
523 LINGER, // Determine whether this network is unneeded and should be lingered.
524 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
525 }
526
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700527 /**
paulhuaa0743d2021-05-26 21:56:03 +0800528 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800529 * should have priority. The order is passed to netd which will use it together
530 * with UID ranges to generate the corresponding IP rule. This serves to
531 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800532 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800533 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000534 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800535 *
paulhu48291862021-07-14 14:53:57 +0800536 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
537 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800538 */
paulhu48291862021-07-14 14:53:57 +0800539 // Used when sending to netd to code for "no order".
540 static final int PREFERENCE_ORDER_NONE = 0;
541 // Order for requests that don't code for a per-app preference. As it is
542 // out of the valid range, the corresponding order should be
543 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800544 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800545 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800546 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800547 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
548 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800549 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800550 static final int PREFERENCE_ORDER_OEM = 10;
551 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800552 // See {@link #setProfileNetworkPreference}.
553 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800554 static final int PREFERENCE_ORDER_PROFILE = 20;
555 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800556 // better scores are connected.
557 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800558 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800559 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900560 // Preference order that signifies the network shouldn't be set as a default network for
561 // the UIDs, only give them access to it. TODO : replace this with a boolean
562 // in NativeUidRangeConfig
563 @VisibleForTesting
564 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
565 // Bound for the lowest valid preference order.
566 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800567
568 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700569 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700570 * from one net to another. Clear happens when we get a new
571 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
572 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700573 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700574 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700575
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700576 /**
577 * used internally to reload global proxy settings
578 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700579 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700580
Robert Greenwalt34848c02011-03-25 13:09:25 -0700581 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400582 * PAC manager has received new port.
583 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800584 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400585
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700586 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900587 * used internally when registering NetworkProviders
588 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700589 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900590 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700591
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700592 /**
593 * used internally when registering NetworkAgents
594 * obj = Messenger
595 */
596 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
597
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700598 /**
599 * used to add a network request
600 * includes a NetworkRequestInfo
601 */
602 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
603
604 /**
605 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900606 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700607 * cancel it.
608 * includes a NetworkRequestInfo
609 */
610 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
611
612 /**
613 * used to add a network listener - no request
614 * includes a NetworkRequestInfo
615 */
616 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
617
618 /**
619 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400620 * arg1 = UID of caller
621 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700622 */
623 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
624
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700625 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900626 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700627 * obj = Messenger
628 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900629 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700630
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700631 /**
632 * used internally to expire a wakelock when transitioning
633 * from one net to another. Expire happens when we fail to find
634 * a new network (typically after 1 minute) -
635 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
636 * a replacement network.
637 */
638 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
639
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700640 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800641 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400642 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800643 */
644 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
645
646 /**
647 * used to remove a pending intent and its associated network request.
648 * arg1 = UID of caller
649 * obj = PendingIntent
650 */
651 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
652
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900653 /**
654 * used to specify whether a network should be used even if unvalidated.
655 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
656 * arg2 = whether to remember this choice in the future (1 or 0)
657 * obj = network
658 */
659 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
660
661 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700662 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900663 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700664 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900665
Paul Jensenc8873fc2015-06-17 14:15:39 -0400666 /**
667 * used to add a network listener with a pending intent
668 * obj = NetworkRequestInfo
669 */
670 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
671
Hugo Benichid6b510a2017-04-06 17:22:18 +0900672 /**
673 * used to specify whether a network should not be penalized when it becomes unvalidated.
674 */
675 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
676
677 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700678 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900679 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700680 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900681
Erik Kline31b4a9e2018-01-11 21:07:29 +0900682 // Handle changes in Private DNS settings.
683 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
684
dalyk1720e542018-03-05 12:42:22 -0500685 // Handle private DNS validation status updates.
686 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
687
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900688 /**
689 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
690 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800691 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
692 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
693 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900694 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900695 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900696
697 /**
698 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
699 * config was resolved.
700 * obj = PrivateDnsConfig
701 * arg2 = netid
702 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900703 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900704
705 /**
706 * Request ConnectivityService display provisioning notification.
707 * arg1 = Whether to make the notification visible.
708 * arg2 = NetID.
709 * obj = Intent to be launched when notification selected by user, null if !arg1.
710 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900711 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900712
713 /**
lucaslin2240ef62019-03-12 13:08:03 +0800714 * Used to specify whether a network should be used even if connectivity is partial.
715 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
716 * false)
717 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
718 * obj = network
719 */
lucaslin444d43a2020-02-20 16:56:59 +0800720 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800721
722 /**
lucasline117e2e2019-10-22 18:27:33 +0800723 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
724 * Both of the arguments are bitmasks, and the value of bits come from
725 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900726 * arg1 = unused
727 * arg2 = netId
728 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800729 */
lucaslin444d43a2020-02-20 16:56:59 +0800730 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800731
732 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900733 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
734 * arg1 = unused
735 * arg2 = netId
736 * obj = captive portal data
737 */
lucaslin444d43a2020-02-20 16:56:59 +0800738 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900739
740 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900741 * Used by setRequireVpnForUids.
742 * arg1 = whether the specified UID ranges are required to use a VPN.
743 * obj = Array of UidRange objects.
744 */
745 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
746
747 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900748 * Used internally when setting the default networks for OemNetworkPreferences.
749 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800750 */
751 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
752
753 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800754 * Used to indicate the system default network becomes active.
755 */
756 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
757
758 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900759 * Used internally when setting a network preference for a user profile.
760 * obj = Pair<ProfileNetworkPreference, Listener>
761 */
762 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
763
764 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000765 * Event to specify that reasons for why an uid is blocked changed.
766 * arg1 = uid
767 * arg2 = blockedReasons
768 */
769 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
770
771 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900772 * Event to register a new network offer
773 * obj = NetworkOffer
774 */
775 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
776
777 /**
778 * Event to unregister an existing network offer
779 * obj = INetworkOfferCallback
780 */
781 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
782
783 /**
paulhu51f77dc2021-06-07 02:34:20 +0000784 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
785 */
786 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
787
788 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800789 * Event to set temporary allow bad wifi within a limited time to override
790 * {@code config_networkAvoidBadWifi}.
791 */
792 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
793
794 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100795 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
796 */
797 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
798
799 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900800 * The initial evaluation period is over for this network.
801 *
802 * If no form of connectivity has been found on this network (valid, partial, captive portal)
803 * then the stack will now consider it to have been determined bad.
804 */
805 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
806
807 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000808 * Used internally when the user does not want the network from captive portal app.
809 * obj = Network
810 */
811 private static final int EVENT_USER_DOES_NOT_WANT = 58;
812
813 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000814 * Event to set VPN as preferred network for specific apps.
815 * obj = VpnNetworkPreferenceInfo
816 */
817 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
818
819 /**
chiachangwange0192a72023-02-06 13:25:01 +0000820 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
821 */
822 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
823
824 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000825 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
826 */
827 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
828
829 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900830 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
831 * should be shown.
832 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900833 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900834
835 /**
836 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
837 * should be hidden.
838 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900839 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900840
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800841 /**
842 * The maximum alive time to allow bad wifi configuration for testing.
843 */
844 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
845
Patrick Rohr2857ac42022-01-21 14:58:16 +0100846 /**
chiachangwange0192a72023-02-06 13:25:01 +0000847 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
848 * testing.
849 */
850 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
851
852 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100853 * The priority of the tc police rate limiter -- smaller value is higher priority.
854 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
855 */
856 private static final short TC_PRIO_POLICE = 1;
857
858 /**
859 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
860 */
861 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700862 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100863
Hugo Benichi47011212017-03-30 10:46:05 +0900864 private static String eventName(int what) {
865 return sMagicDecoderRing.get(what, Integer.toString(what));
866 }
867
paulhua10d8212020-11-10 15:32:56 +0800868 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900869 final DnsResolverServiceManager dsm = context.getSystemService(
870 DnsResolverServiceManager.class);
871 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800872 }
873
Cody Kesting73708bf2019-12-18 10:57:50 -0800874 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900875 @VisibleForTesting
876 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700877 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700878 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700879 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700880 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800881 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
882 @VisibleForTesting
883 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
884
Erik Kline32120082017-12-13 19:40:49 +0900885 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900886 @VisibleForTesting
887 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700888
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400889 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800890 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400891
Chalard Jean46bfbf02022-02-02 00:56:25 +0900892 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800893 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700894
Chalard Jean5d70ba42018-06-07 16:44:04 +0900895 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
896 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800897 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400898
Erik Kline05f2b402015-04-30 12:58:40 +0900899 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700900
Chalard Jean46bfbf02022-02-02 00:56:25 +0900901 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400902
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700903 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900904 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700905
Valentin Iftime9fa35092019-09-24 13:32:13 +0200906 private Set<String> mWolSupportedInterfaces;
907
Roshan Pius08c94fb2020-01-16 12:17:17 -0800908 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800909 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800910 private final AppOpsManager mAppOpsManager;
911
912 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400913
chiachangwang3d60bac2023-01-17 14:38:08 +0000914 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900915 private final QosCallbackTracker mQosCallbackTracker;
916 private final NetworkNotificationManager mNotifier;
917 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900918
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700919 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800920 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700921
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900922 // Sequence number for NetworkProvider IDs.
923 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
924 NetworkProvider.FIRST_PROVIDER_ID);
925
Erik Klineedf878b2015-07-09 18:24:03 +0900926 // NetworkRequest activity String log entries.
927 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
928 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
929
Hugo Benichid159fdd2016-07-11 11:05:12 +0900930 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900931 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900932 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
933
Hugo Benichi47011212017-03-30 10:46:05 +0900934 private static final int MAX_WAKELOCK_LOGS = 20;
935 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900936 private int mTotalWakelockAcquisitions = 0;
937 private int mTotalWakelockReleases = 0;
938 private long mTotalWakelockDurationMs = 0;
939 private long mMaxWakelockDurationMs = 0;
940 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900941
Hugo Benichi208c0102016-07-28 17:53:06 +0900942 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900943
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700944 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900945 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700946
Erik Kline95ecfee2016-10-02 18:02:14 +0900947 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900948 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900949
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900950 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800951 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
952 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800953
Patrick Rohr2857ac42022-01-21 14:58:16 +0100954 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
955 // configured via {@link
956 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
957 // Only the handler thread is allowed to access this field.
958 private long mIngressRateLimit = -1;
959
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900960 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
961 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900962 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900963 @GuardedBy("mSelfCertifiedCapabilityCache")
964 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
965 mSelfCertifiedCapabilityCache = new HashMap<>();
966
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900967 // Flag to enable the feature of closing frozen app sockets.
968 private final boolean mDestroyFrozenSockets;
969
970 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
971 private final boolean mDelayDestroyFrozenSockets;
972
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900973 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
974 private final boolean mAllowSysUiConnectivityReports;
975
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900976 // Uids that ConnectivityService is pending to close sockets of.
977 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
978
Robert Greenwalt802c1102014-06-02 15:32:02 -0700979 /**
980 * Implements support for the legacy "one network per network type" model.
981 *
982 * We used to have a static array of NetworkStateTrackers, one for each
983 * network type, but that doesn't work any more now that we can have,
984 * for example, more that one wifi network. This class stores all the
985 * NetworkAgentInfo objects that support a given type, but the legacy
986 * API will only see the first one.
987 *
988 * It serves two main purposes:
989 *
990 * 1. Provide information about "the network for a given type" (since this
991 * API only supports one).
992 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
993 * the first network for a given type changes, or if the default network
994 * changes.
995 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900996 @VisibleForTesting
997 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900998
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900999 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001000 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001001
Robert Greenwalt802c1102014-06-02 15:32:02 -07001002 /**
1003 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1004 * Each list holds references to all NetworkAgentInfos that are used to
1005 * satisfy requests for that network type.
1006 *
1007 * This array is built out at startup such that an unsupported network
1008 * doesn't get an ArrayList instance, making this a tristate:
1009 * unsupported, supported but not active and active.
1010 *
1011 * The actual lists are populated when we scan the network types that
1012 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001013 *
1014 * Threading model:
1015 * - addSupportedType() is only called in the constructor
1016 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1017 * They are therefore not thread-safe with respect to each other.
1018 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1019 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001020 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001021 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001022 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001023 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001024 @NonNull
1025 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001026
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001027 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1028 // an entry have no timer (equivalent to -1). Lazily loaded.
1029 @NonNull
1030 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1031
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001032 LegacyTypeTracker(@NonNull ConnectivityService service) {
1033 mService = service;
1034 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001035 }
1036
Chiachang Wang3bc52762021-11-25 14:17:57 +08001037 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1038 // addressed.
1039 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001040 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1041 final PackageManager pm = ctx.getPackageManager();
1042 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1043 addSupportedType(TYPE_WIFI);
1044 }
1045 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1046 addSupportedType(TYPE_WIFI_P2P);
1047 }
1048 if (tm.isDataCapable()) {
1049 // Telephony does not have granular support for these types: they are either all
1050 // supported, or none is supported
1051 addSupportedType(TYPE_MOBILE);
1052 addSupportedType(TYPE_MOBILE_MMS);
1053 addSupportedType(TYPE_MOBILE_SUPL);
1054 addSupportedType(TYPE_MOBILE_DUN);
1055 addSupportedType(TYPE_MOBILE_HIPRI);
1056 addSupportedType(TYPE_MOBILE_FOTA);
1057 addSupportedType(TYPE_MOBILE_IMS);
1058 addSupportedType(TYPE_MOBILE_CBS);
1059 addSupportedType(TYPE_MOBILE_IA);
1060 addSupportedType(TYPE_MOBILE_EMERGENCY);
1061 }
1062 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1063 addSupportedType(TYPE_BLUETOOTH);
1064 }
1065 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1066 // TYPE_PROXY is only used on Wear
1067 addSupportedType(TYPE_PROXY);
1068 }
1069 // Ethernet is often not specified in the configs, although many devices can use it via
1070 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001071 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001072 addSupportedType(TYPE_ETHERNET);
1073 }
1074
1075 // Always add TYPE_VPN as a supported type
1076 addSupportedType(TYPE_VPN);
1077 }
1078
1079 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001080 if (mTypeLists[type] != null) {
1081 throw new IllegalStateException(
1082 "legacy list for type " + type + "already initialized");
1083 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001084 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001085 }
1086
Robert Greenwalt802c1102014-06-02 15:32:02 -07001087 public boolean isTypeSupported(int type) {
1088 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1089 }
1090
1091 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001092 synchronized (mTypeLists) {
1093 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1094 return mTypeLists[type].get(0);
1095 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001096 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001097 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001098 }
1099
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001100 public int getRestoreTimerForType(int type) {
1101 synchronized (mTypeLists) {
1102 if (mRestoreTimers == null) {
1103 mRestoreTimers = loadRestoreTimers();
1104 }
1105 return mRestoreTimers.getOrDefault(type, -1);
1106 }
1107 }
1108
1109 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1110 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001111 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001112 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1113 for (final String config : configs) {
1114 final String[] splits = TextUtils.split(config, ",");
1115 if (splits.length != 2) {
1116 logwtf("Invalid restore timer token count: " + config);
1117 continue;
1118 }
1119 try {
1120 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1121 } catch (NumberFormatException e) {
1122 logwtf("Invalid restore timer number format: " + config, e);
1123 }
1124 }
1125 return ret;
1126 }
1127
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001128 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001129 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001130 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001131 log("Sending " + state
1132 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001133 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001134 }
1135 }
1136
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001137 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1138 // network type, to preserve previous behaviour.
1139 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1140 if (vpnNai != mService.getLegacyLockdownNai()) return;
1141
1142 if (vpnNai.declaredUnderlyingNetworks == null
1143 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1144 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1145 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1146 return;
1147 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001148 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001149 vpnNai.declaredUnderlyingNetworks[0]);
1150 if (underlyingNai == null) return;
1151
1152 final int type = underlyingNai.networkInfo.getType();
1153 final DetailedState state = DetailedState.CONNECTED;
1154 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1155 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1156 }
1157
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001158 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001159 public void add(int type, NetworkAgentInfo nai) {
1160 if (!isTypeSupported(type)) {
1161 return; // Invalid network type.
1162 }
1163 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1164
1165 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1166 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001167 return;
1168 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001169 synchronized (mTypeLists) {
1170 list.add(nai);
1171 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001172
Chalard Jean5b409c72021-02-04 13:12:59 +09001173 // Send a broadcast if this is the first network of its type or if it's the default.
1174 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001175
1176 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1177 // to preserve previous behaviour.
1178 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001179 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001180 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1181 mService.sendLegacyNetworkBroadcast(nai, state, type);
1182 }
1183
1184 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1185 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001186 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001187 }
1188
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001189 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001190 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001191 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1192 if (list == null || list.isEmpty()) {
1193 return;
1194 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001195 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001196
Hugo Benichi389633f2016-06-21 09:48:07 +09001197 synchronized (mTypeLists) {
1198 if (!list.remove(nai)) {
1199 return;
1200 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001201 }
1202
Lorenzo Colitti49767722015-05-01 00:30:10 +09001203 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001204 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1205 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001206 }
1207
1208 if (!list.isEmpty() && wasFirstNetwork) {
1209 if (DBG) log("Other network available for type " + type +
1210 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001211 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001212 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001213 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001214 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001215 }
1216 }
1217
1218 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001219 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1220 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001221 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001222 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001223 }
1224 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001225
Chalard Jean46bfbf02022-02-02 00:56:25 +09001226 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001227 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001228 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001229 final DetailedState state = nai.networkInfo.getDetailedState();
1230 for (int type = 0; type < mTypeLists.length; type++) {
1231 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001232 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001233 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001234 if (isFirst || contains && isDefault) {
1235 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001236 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001237 }
1238 }
1239 }
1240
Robert Greenwalt94e22142014-07-30 16:31:24 -07001241 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001242 pw.println("mLegacyTypeTracker:");
1243 pw.increaseIndent();
1244 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001245 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001246 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001247 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001248 pw.println();
1249 pw.println("Current state:");
1250 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001251 synchronized (mTypeLists) {
1252 for (int type = 0; type < mTypeLists.length; type++) {
1253 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1254 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001255 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001256 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001257 }
1258 }
1259 pw.decreaseIndent();
1260 pw.decreaseIndent();
1261 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001262 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001263 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001264 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001265
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001266 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001267 /**
1268 * Helper class which parses out priority arguments and dumps sections according to their
1269 * priority. If priority arguments are omitted, function calls the legacy dump command.
1270 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001271 private class LocalPriorityDump {
1272 private static final String PRIORITY_ARG = "--dump-priority";
1273 private static final String PRIORITY_ARG_HIGH = "HIGH";
1274 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001275 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001276
1277 LocalPriorityDump() {}
1278
1279 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Laif8dba342023-10-12 17:01:03 +08001280 if (!HandlerUtils.runWithScissors(mHandler, () -> {
1281 doDump(fd, pw, new String[]{DIAG_ARG});
1282 doDump(fd, pw, new String[]{SHORT_ARG});
1283 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1284 pw.println("dumpHigh timeout");
1285 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001286 }
1287
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001288 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Laif8dba342023-10-12 17:01:03 +08001289 if (!HandlerUtils.runWithScissors(mHandler, () -> doDump(fd, pw, args),
1290 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1291 pw.println("dumpNormal timeout");
1292 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001293 }
1294
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001295 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1296 if (args == null) {
1297 dumpNormal(fd, pw, args);
1298 return;
1299 }
1300
1301 String priority = null;
1302 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1303 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1304 argIndex++;
1305 priority = args[argIndex];
1306 }
1307 }
1308
1309 if (PRIORITY_ARG_HIGH.equals(priority)) {
1310 dumpHigh(fd, pw);
1311 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1312 dumpNormal(fd, pw, args);
1313 } else {
1314 // ConnectivityService publishes binder service using publishBinderService() with
1315 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001316 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1317 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001318 // TODO: Integrate into signal dump.
1319 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001320 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001321 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001322 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001323
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001324 /**
1325 * Dependencies of ConnectivityService, for injection in tests.
1326 */
1327 @VisibleForTesting
1328 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001329 public int getCallingUid() {
1330 return Binder.getCallingUid();
1331 }
1332
Chalard Jeandf29a852023-05-29 17:02:43 +09001333 public boolean isAtLeastS() {
1334 return SdkLevel.isAtLeastS();
1335 }
1336
1337 public boolean isAtLeastT() {
1338 return SdkLevel.isAtLeastT();
1339 }
1340
1341 public boolean isAtLeastU() {
1342 return SdkLevel.isAtLeastU();
1343 }
1344
Chalard Jeaneb663892023-10-07 15:17:07 +09001345 public boolean isAtLeastV() {
1346 return SdkLevel.isAtLeastV();
1347 }
1348
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001349 /**
1350 * Get system properties to use in ConnectivityService.
1351 */
1352 public MockableSystemProperties getSystemProperties() {
1353 return new MockableSystemProperties();
1354 }
1355
1356 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001357 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1358 */
1359 public ConnectivityResources getResources(@NonNull Context ctx) {
1360 return new ConnectivityResources(ctx);
1361 }
1362
1363 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001364 * Create a HandlerThread to use in ConnectivityService.
1365 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001366 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1367 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001368 }
1369
1370 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001371 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001372 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001373 public NetworkStackClientBase getNetworkStack() {
1374 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001375 }
1376
1377 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001378 * @see ProxyTracker
1379 */
1380 public ProxyTracker makeProxyTracker(@NonNull Context context,
1381 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001382 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001383 }
1384
1385 /**
1386 * @see NetIdManager
1387 */
1388 public NetIdManager makeNetIdManager() {
1389 return new NetIdManager();
1390 }
1391
1392 /**
1393 * @see NetworkUtils#queryUserAccess(int, int)
1394 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001395 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1396 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001397 }
1398
1399 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001400 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1401 * requires CAP_NET_ADMIN, which the unit tests do not have.
1402 */
1403 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1404 InetSocketAddress remote) {
1405 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1406 }
1407
1408 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001409 * @see MultinetworkPolicyTracker
1410 */
1411 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1412 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1413 return new MultinetworkPolicyTracker(c, h, r);
1414 }
1415
Aaron Huang330a4c02020-10-27 03:36:19 +08001416 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001417 * @see AutomaticOnOffKeepaliveTracker
1418 */
1419 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1420 @NonNull Context c, @NonNull Handler h) {
1421 return new AutomaticOnOffKeepaliveTracker(c, h);
1422 }
1423
1424 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001425 * @see BatteryStatsManager
1426 */
1427 public void reportNetworkInterfaceForTransports(Context context, String iface,
1428 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001429 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001430 context.getSystemService(BatteryStatsManager.class);
1431 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1432 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001433
1434 public boolean getCellular464XlatEnabled() {
1435 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1436 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001437
1438 /**
1439 * @see PendingIntent#intentFilterEquals
1440 */
1441 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1442 return a.intentFilterEquals(b);
1443 }
1444
1445 /**
1446 * @see LocationPermissionChecker
1447 */
1448 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1449 return new LocationPermissionChecker(context);
1450 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001451
1452 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001453 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001454 *
1455 * This method returns null in versions before T, where carrier privilege
1456 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001457 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001458 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001459 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1460 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001461 if (isAtLeastT()) {
Chalard Jean96ff9542023-11-02 14:24:47 +09001462 return new CarrierPrivilegeAuthenticator(context, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001463 } else {
1464 return null;
1465 }
1466 }
1467
1468 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001469 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001470 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001471 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001472 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001473 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001474
1475 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001476 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1477 */
1478 public boolean isFeatureNotChickenedOut(Context context, String name) {
1479 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1480 }
1481
1482 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001483 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001484 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001485 * @return BpfNetMaps implementation.
1486 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001487 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1488 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001489 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001490
1491 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001492 * @see ClatCoordinator
1493 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001494 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001495 public ClatCoordinator getClatCoordinator(INetd netd) {
1496 return new ClatCoordinator(
1497 new ClatCoordinator.Dependencies() {
1498 @NonNull
1499 public INetd getNetd() {
1500 return netd;
1501 }
1502 });
1503 }
1504
1505 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001506 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1507 */
1508 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1509 final InterfaceParams params = InterfaceParams.getByName(iface);
1510 if (params == null) {
1511 // the interface might have disappeared.
1512 logw("Failed to get interface params for interface " + iface);
1513 return;
1514 }
1515 try {
1516 // converting rateInBytesPerSecond from long to int is safe here because the
1517 // setting's range is limited to INT_MAX.
1518 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001519 Log.i(TAG,
1520 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001521 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1522 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1523 } catch (IOException e) {
1524 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1525 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1526 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1527 + ") failure: ", e);
1528 }
1529 }
1530
1531 /**
1532 * Wraps {@link TcUtils#tcFilterDelDev}
1533 */
1534 public void disableIngressRateLimit(String iface) {
1535 final InterfaceParams params = InterfaceParams.getByName(iface);
1536 if (params == null) {
1537 // the interface might have disappeared.
1538 logw("Failed to get interface params for interface " + iface);
1539 return;
1540 }
1541 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001542 Log.i(TAG,
1543 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001544 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1545 } catch (IOException e) {
1546 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1547 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1548 }
1549 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001550
1551 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001552 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1553 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001554 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001555 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001556 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001557 }
1558
1559 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001560 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1561 */
1562 // TODO: when available in all active branches:
1563 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1564 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1565 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1566 return BroadcastOptionsShimImpl.newInstance(options);
1567 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001568
1569 /**
1570 * Wrapper method for
1571 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1572 *
1573 * @param changeId The ID of the compatibility change in question.
1574 * @param packageName The package name of the app in question.
1575 * @param user The user that the operation is done for.
1576 * @return {@code true} if the change is enabled for the specified package.
1577 */
1578 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1579 @NonNull final UserHandle user) {
1580 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1581 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001582
1583 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001584 * As above but with a UID.
1585 * @see CompatChanges#isChangeEnabled(long, int)
1586 */
1587 public boolean isChangeEnabled(final long changeId, final int uid) {
1588 return CompatChanges.isChangeEnabled(changeId, uid);
1589 }
1590
1591 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001592 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1593 *
1594 * @param ranges target uid ranges
1595 * @param exemptUids uids to skip close socket
1596 */
1597 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1598 @NonNull final Set<Integer> exemptUids)
1599 throws SocketException, InterruptedIOException, ErrnoException {
1600 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1601 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001602
1603 /**
1604 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1605 *
1606 * @param ownerUids target uids to close sockets
1607 */
1608 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1609 throws SocketException, InterruptedIOException, ErrnoException {
1610 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1611 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001612
1613 /**
1614 * Schedule the evaluation timeout.
1615 *
1616 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1617 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1618 * of these events happen, this time will run out, after which the network is considered
1619 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1620 * on this network and considers it won't provide connectivity. In particular, that means
1621 * it's when the system prefers it to cell if it's wifi and configuration says it should
1622 * prefer bad wifi to cell.
1623 */
1624 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1625 @NonNull final Network network, final long delayMs) {
1626 handler.sendMessageDelayed(
1627 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1628 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001629 }
1630
junyulaie7c7d2a2021-01-26 15:29:15 +08001631 public ConnectivityService(Context context) {
1632 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001633 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1634 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001635 }
1636
1637 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001638 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1639 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001640 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001641
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001642 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001643 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001644 mSystemProperties = mDeps.getSystemProperties();
1645 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001646 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001647 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001648 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1649 // Pass limit - 1 to maintain backward compatibility.
1650 // TODO: Remove the workaround.
1651 mNetworkRequestCounter =
1652 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1653 mSystemNetworkRequestCounter =
1654 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001655
Hugo Benichi208c0102016-07-28 17:53:06 +09001656 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001657 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1658 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001659 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001660 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001661 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001662 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1663 mDefaultNetworkRequests.add(mDefaultRequest);
1664 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001665
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001666 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001667 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001668
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001669 // The default WiFi request is a background request so that apps using WiFi are
1670 // migrated to a better network (typically ethernet) when one comes up, instead
1671 // of staying on WiFi forever.
1672 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1673 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1674
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001675 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1676 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1677 NetworkRequest.Type.BACKGROUND_REQUEST);
1678
Chalard Jean0702f982021-09-16 21:50:07 +09001679 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1680 // TODO: Consider making the timer customizable.
1681 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1682 mCellularRadioTimesharingCapable =
1683 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1684
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001685 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1686 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1687
1688 if (SdkLevel.isAtLeastU()) {
1689 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1690 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1691 final int defaultUMarkMask = 0x80000000; // u32
1692
1693 if ((mark == 0) || (mask == 0)) {
1694 // simply treat unset/disabled as the default U value
1695 mark = defaultUMarkMask;
1696 mask = defaultUMarkMask;
1697 }
1698 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1699 // invalid device overlay settings
1700 throw new IllegalArgumentException(
1701 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1702 }
1703 }
1704
1705 mWakeUpMark = mark;
1706 mWakeUpMask = mask;
1707
Paul Hu51f816b2022-08-11 14:43:47 +00001708 mNetd = netd;
1709 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Chalard Jean96ff9542023-11-02 14:24:47 +09001710 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Paul Hu51f816b2022-08-11 14:43:47 +00001711 mPermissionMonitor =
1712 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001713 mHandlerThread.start();
1714 mHandler = new InternalHandler(mHandlerThread.getLooper());
1715 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001716 mConnectivityDiagnosticsHandler =
1717 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001718
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001719 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001720 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001721
junyulaie7c7d2a2021-01-26 15:29:15 +08001722 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001723 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001724 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001725 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001726
Wink Saville32506bc2013-06-29 21:10:57 -07001727 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001728 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001729 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001730 mCarrierPrivilegeAuthenticator =
1731 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001732
Sudheer Shanka9967d462021-03-18 19:09:25 +00001733 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001734 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1735 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001736 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001737
1738 final PowerManager powerManager = (PowerManager) context.getSystemService(
1739 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001740 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001741 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001742
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001743 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1744 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001745 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001746 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001747 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001748 mProtectedNetworks.add(p);
1749 } else {
1750 if (DBG) loge("Ignoring protectedNetwork " + p);
1751 }
1752 }
1753
soma, kawata29444ae2019-05-23 09:30:40 +09001754 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1755
James Mattis02220e22021-03-13 19:27:21 -08001756 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001757 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001758 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001759 final IntentFilter userIntentFilter = new IntentFilter();
1760 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1761 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1762 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1763 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001764
James Mattis02220e22021-03-13 19:27:21 -08001765 // Listen to package add/removes for netd
1766 final IntentFilter packageIntentFilter = new IntentFilter();
1767 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1768 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1769 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1770 packageIntentFilter.addDataScheme("package");
1771 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001772 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001773
Junyu Lai38c75032023-12-04 07:52:19 +00001774 // This is needed for pre-V devices to propagate the data saver status
1775 // to the BPF map. This isn't supported before Android T because BPF maps are
1776 // unsupported, and it's also unnecessary on Android V and later versions,
1777 // as the platform code handles data saver bit updates. Additionally, checking
1778 // the initial data saver status here is superfluous because the intent won't
1779 // be sent until the system is ready.
1780 if (mDeps.isAtLeastT() && !mDeps.isAtLeastV()) {
1781 final IntentFilter dataSaverIntentFilter =
1782 new IntentFilter(ACTION_RESTRICT_BACKGROUND_CHANGED);
1783 mUserAllContext.registerReceiver(mDataSaverReceiver, dataSaverIntentFilter,
1784 null /* broadcastPermission */, mHandler);
1785 }
1786
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09001787 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
1788 // But reading the trunk stable flags from mainline modules is not supported yet.
1789 // So enabling this feature on V+ release.
1790 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
1791 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
1792 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001793
Chalard Jean46bfbf02022-02-02 00:56:25 +09001794 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001795 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001796 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001797 } catch (RemoteException | ServiceSpecificException e) {
1798 loge("Error registering event listener :" + e);
1799 }
1800
Erik Kline05f2b402015-04-30 12:58:40 +09001801 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1802 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001803
chiachangwang7c17c282023-02-02 05:58:59 +00001804 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001805 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001806 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001807
1808 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001809 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001810 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1811 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001812 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001813 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1814 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001815
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001816 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001817 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001818 mNetworkRanker =
1819 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1820
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001821 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001822
Chiachang Wangc1215d32020-10-20 15:38:58 +08001823 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001824 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001825
Chalard Jean28018572020-12-21 18:36:52 +09001826 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1827 // request that doesn't allow fallback to the default network. It should never be visible
1828 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1829 // arguments like the handler or the DnsResolver.
1830 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001831 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001832 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001833 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001834 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001835 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001836 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1837 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001838
1839 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001840 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1841 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1842 // Even if it could, running on S would at least require mocking out the BPF map,
1843 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1844 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001845 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001846 mDscpPolicyTracker = new DscpPolicyTracker();
1847 }
Tyler Wear72388212021-09-09 14:49:02 -07001848 } catch (ErrnoException e) {
1849 loge("Unable to create DscpPolicyTracker");
1850 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001851
1852 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1853 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001854
Chalard Jeandf29a852023-05-29 17:02:43 +09001855 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001856 mCdmps = new CompanionDeviceManagerProxyService(context);
1857 } else {
1858 mCdmps = null;
1859 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001860
Chalard Jean2fb66f12023-08-25 12:50:37 +09001861 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
1862
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001863 mDestroyFrozenSockets = mDeps.isAtLeastU()
1864 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1865 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1866 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001867 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1868 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001869 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001870 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1871 new UidFrozenStateChangedCallback() {
1872 @Override
1873 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1874 if (uids.length != frozenStates.length) {
1875 Log.wtf(TAG, "uids has length " + uids.length
1876 + " but frozenStates has length " + frozenStates.length);
1877 return;
1878 }
1879
1880 final UidFrozenStateChangedArgs args =
1881 new UidFrozenStateChangedArgs(uids, frozenStates);
1882
1883 mHandler.sendMessage(
1884 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1885 }
1886 };
1887
1888 final ActivityManager activityManager =
1889 mContext.getSystemService(ActivityManager.class);
1890 activityManager.registerUidFrozenStateChangedCallback(
1891 (Runnable r) -> r.run(), frozenStateChangedCallback);
1892 }
Yuyang Huang41557552023-11-28 12:47:22 +09001893
1894 if (mDeps.isFeatureNotChickenedOut(mContext, LOG_BPF_RC)) {
1895 mHandler.post(BpfLoaderRcUtils::checkBpfLoaderRc);
1896 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001897 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001898
Xiao Ma0a171c02022-01-23 16:14:51 +00001899 /**
1900 * Check whether or not the device supports Ethernet transport.
1901 */
1902 public static boolean deviceSupportsEthernet(final Context context) {
1903 final PackageManager pm = context.getPackageManager();
1904 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1905 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1906 }
1907
Chalard Jean46adcf32018-04-18 20:18:38 +09001908 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001909 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1910 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001911 }
1912
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001913 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1914 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001915 final NetworkCapabilities netCap = new NetworkCapabilities();
1916 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001917 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001918 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001919 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001920 return netCap;
1921 }
1922
James Mattis45d81842021-01-10 14:24:24 -08001923 private NetworkRequest createDefaultRequest() {
1924 return createDefaultInternetRequestForTransport(
1925 TYPE_NONE, NetworkRequest.Type.REQUEST);
1926 }
1927
lucaslin3ba7cc22022-12-19 02:35:33 +00001928 private NetworkRequest createVpnRequest() {
1929 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1930 .withoutDefaultCapabilities()
1931 .addTransportType(TRANSPORT_VPN)
1932 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1933 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1934 .build();
1935 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1936 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1937 }
1938
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001939 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001940 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001941 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001942 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001943 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001944 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001945 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001946 netCap.addTransportType(transportType);
1947 }
James Mattis45d81842021-01-10 14:24:24 -08001948 return createNetworkRequest(type, netCap);
1949 }
1950
1951 private NetworkRequest createNetworkRequest(
1952 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001953 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001954 }
1955
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001956 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1957 NetworkRequest.Type type) {
1958 final NetworkCapabilities netCap = new NetworkCapabilities();
1959 netCap.clearAll();
1960 netCap.addCapability(capability);
1961 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1962 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1963 }
1964
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001965 // Used only for testing.
1966 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001967 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001968 // changing ContentResolver to make registerContentObserver non-final).
1969 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1970 // by subclassing SettingsObserver.
1971 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001972 void updateAlwaysOnNetworks() {
1973 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001974 }
1975
Erik Kline9a62f012018-03-21 07:18:33 -07001976 // See FakeSettingsProvider comment above.
1977 @VisibleForTesting
1978 void updatePrivateDnsSettings() {
1979 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1980 }
1981
paulhu51f77dc2021-06-07 02:34:20 +00001982 @VisibleForTesting
1983 void updateMobileDataPreferredUids() {
1984 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1985 }
1986
Patrick Rohr2857ac42022-01-21 14:58:16 +01001987 @VisibleForTesting
1988 void updateIngressRateLimit() {
1989 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1990 }
1991
Aaron Huang40b52442021-06-08 04:34:24 +08001992 @VisibleForTesting
1993 void simulateUpdateProxyInfo(@Nullable final Network network,
1994 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001995 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001996 new Pair<>(network, proxyInfo)).sendToTarget();
1997 }
1998
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001999 private void handleAlwaysOnNetworkRequest(
2000 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002001 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002002 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002003 handleAlwaysOnNetworkRequest(networkRequest, enable);
2004 }
2005
2006 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002007 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002008 if (enable == isEnabled) {
2009 return; // Nothing to do.
2010 }
2011
2012 if (enable) {
2013 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002014 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002015 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002016 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002017 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002018 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2019 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002020 }
2021 }
2022
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002023 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002024 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2025 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2026 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2027 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002028 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2029 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002030 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002031 }
2032
paulhu51f77dc2021-06-07 02:34:20 +00002033 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002034 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002035 private void registerSettingsCallbacks() {
2036 // Watch for global HTTP proxy changes.
2037 mSettingsObserver.observe(
2038 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2039 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2040
Chalard Jean46bfbf02022-02-02 00:56:25 +09002041 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002042 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002043 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002044 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2045
Chalard Jean46bfbf02022-02-02 00:56:25 +09002046 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002047 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002048 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002049 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002050
2051 // Watch for mobile data preferred uids changes.
2052 mSettingsObserver.observe(
2053 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2054 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002055
2056 // Watch for ingress rate limit changes.
2057 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002058 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002059 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2060 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002061 }
2062
Erik Kline31b4a9e2018-01-11 21:07:29 +09002063 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002064 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2065 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002066 }
2067 }
2068
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002069 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002070 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2071 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002072 return mNextNetworkRequestId++;
2073 }
2074
junyulai74f9a8b2018-06-13 15:00:37 +08002075 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002076 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002077 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002078 if (network == null) {
2079 return null;
2080 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002081 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002082 }
2083
2084 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002085 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002086 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002087 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002088 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002089
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002090 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002091 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002092 private NetworkAgentInfo getVpnForUid(int uid) {
2093 synchronized (mNetworkForNetId) {
2094 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2095 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002096 if (nai.isVPN() && nai.everConnected()
2097 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002098 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002099 }
2100 }
2101 }
2102 return null;
2103 }
2104
Chalard Jean46bfbf02022-02-02 00:56:25 +09002105 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002106 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002107 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002108 final NetworkAgentInfo nai = getVpnForUid(uid);
2109 if (nai != null) return nai.declaredUnderlyingNetworks;
2110 return null;
2111 }
2112
Lorenzo Colittia7574052021-01-19 01:33:05 +09002113 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002114 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002115
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002116 final Network[] networks = getVpnUnderlyingNetworks(uid);
2117 if (networks != null) {
2118 // getUnderlyingNetworks() returns:
2119 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2120 // empty array => the VPN explicitly said "no default network".
2121 // non-empty array => the VPN specified one or more default networks; we use the
2122 // first one.
2123 if (networks.length > 0) {
2124 nai = getNetworkAgentInfoForNetwork(networks[0]);
2125 } else {
2126 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002127 }
2128 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002129 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002130 }
2131
2132 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002133 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002134 */
paulhu7aeba372020-12-30 00:42:19 +08002135 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2136 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002137 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002138 if (ignoreBlocked) {
2139 return false;
2140 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002141 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002142 final long ident = Binder.clearCallingIdentity();
2143 try {
2144 final boolean metered = nc == null ? true : nc.isMetered();
2145 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2146 } finally {
2147 Binder.restoreCallingIdentity(ident);
2148 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002149 }
2150
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002151 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002152 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2153 return;
2154 }
Hugo Benichi47011212017-03-30 10:46:05 +09002155 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002156 synchronized (mBlockedAppUids) {
2157 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002158 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002159 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002160 blocked = false;
2161 } else {
2162 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002163 }
2164 }
Hugo Benichi47011212017-03-30 10:46:05 +09002165 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2166 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2167 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002168 }
2169
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002170 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002171 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2172 return;
2173 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002174 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002175 final int requestId = nri.getActiveRequest() != null
2176 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002177 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002178 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002179 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002180 }
2181
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002182 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002183 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002184 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002185 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002186 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002187 @NonNull
2188 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2189 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002190 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2191 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2192 // but only exists if an app asks about them or requests them. Ensure the requesting app
2193 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002194 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002195 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2196 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2197 null /* extraInfo */);
2198 }
2199 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002200 return filtered;
2201 }
2202
2203 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2204 boolean ignoreBlocked) {
2205 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2206 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002207 }
2208
2209 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002210 * Return NetworkInfo for the active (i.e., connected) network interface.
2211 * It is assumed that at most one network is active at a time. If more
2212 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002213 * @return the info for the active network, or {@code null} if none is
2214 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002215 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002216 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002217 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002218 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002219 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002220 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002221 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2222 if (nai == null) return null;
2223 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2224 maybeLogBlockedNetworkInfo(networkInfo, uid);
2225 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002226 }
2227
Paul Jensen1f567382015-02-13 14:18:39 -05002228 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002229 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002230 public Network getActiveNetwork() {
2231 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002232 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002233 }
2234
2235 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002236 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002237 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002238 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002239 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002240 }
2241
Chalard Jean46bfbf02022-02-02 00:56:25 +09002242 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002243 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002244 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2245 if (vpnNai != null) {
2246 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2247 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2248 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002249 }
Paul Jensen1f567382015-02-13 14:18:39 -05002250 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002251
James Mattis2516da32021-01-31 17:06:19 -08002252 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002253 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2254 ignoreBlocked)) {
2255 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002256 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002257 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002258 }
2259
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002260 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002261 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002262 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002263 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002264 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2265 if (nai == null) return null;
2266 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002267 }
2268
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002269 /** Returns a NetworkInfo object for a network that doesn't exist. */
2270 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2271 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2272 getNetworkTypeName(networkType), "" /* subtypeName */);
2273 info.setIsAvailable(true);
2274 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2275 // background data is restricted.
2276 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2277 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2278 ? DetailedState.BLOCKED
2279 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002280 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2281 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002282 return info;
2283 }
2284
Lorenzo Colittia7574052021-01-19 01:33:05 +09002285 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002286 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2287 return null;
2288 }
2289 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002290 if (nai == null) {
2291 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002292 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002293 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2294 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002295 }
2296
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002297 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002298 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002299 public NetworkInfo getNetworkInfo(int networkType) {
2300 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002301 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002302 if (getVpnUnderlyingNetworks(uid) != null) {
2303 // A VPN is active, so we may need to return one of its underlying networks. This
2304 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002305 // getNetworkAgentInfoForUid.
2306 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2307 if (nai == null) return null;
2308 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2309 if (networkInfo.getType() == networkType) {
2310 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002311 }
2312 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002313 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002314 }
2315
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002316 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002317 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002318 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002319 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002320 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002321 if (nai == null) return null;
2322 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002323 }
2324
2325 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002326 public NetworkInfo[] getAllNetworkInfo() {
2327 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002328 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002329 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2330 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002331 NetworkInfo info = getNetworkInfo(networkType);
2332 if (info != null) {
2333 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002334 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002335 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002336 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002337 }
2338
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002339 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002340 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002341 public Network getNetworkForType(int networkType) {
2342 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002343 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2344 return null;
2345 }
2346 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2347 if (nai == null) {
2348 return null;
2349 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002350 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002351 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2352 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002353 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002354 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002355 }
2356
2357 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002358 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002359 public Network[] getAllNetworks() {
2360 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002361 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002362 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002363 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002364 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002365 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002366 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002367 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002368 }
2369
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002370 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002371 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002372 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002373 // The basic principle is: if an app's traffic could possibly go over a
2374 // network, without the app doing anything multinetwork-specific,
2375 // (hence, by "default"), then include that network's capabilities in
2376 // the array.
2377 //
2378 // In the normal case, app traffic only goes over the system's default
2379 // network connection, so that's the only network returned.
2380 //
2381 // With a VPN in force, some app traffic may go into the VPN, and thus
2382 // over whatever underlying networks the VPN specifies, while other app
2383 // traffic may go over the system default network (e.g.: a split-tunnel
2384 // VPN, or an app disallowed by the VPN), so the set of networks
2385 // returned includes the VPN's underlying networks and the system
2386 // default.
2387 enforceAccessPermission();
2388
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002389 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002390
James Mattis2516da32021-01-31 17:06:19 -08002391 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2392 if (!nri.isBeingSatisfied()) {
2393 continue;
2394 }
2395 final NetworkAgentInfo nai = nri.getSatisfier();
2396 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2397 if (null != nc
2398 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2399 && !result.containsKey(nai.network)) {
2400 result.put(
2401 nai.network,
2402 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002403 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002404 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2405 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002406 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002407 }
2408
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002409 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002410 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002411 if (null != networks) {
2412 for (final Network network : networks) {
2413 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2414 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002415 result.put(
2416 network,
2417 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002418 nc,
2419 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002420 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002421 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002422 }
2423 }
2424 }
2425
2426 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2427 out = result.values().toArray(out);
2428 return out;
2429 }
2430
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002431 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2432 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2433 // can call sampleConnectivityState and make the checks on it.
2434 @NonNull
2435 private StatsEvent sampleConnectivityStateToStatsEvent() {
2436 final ConnectivityStateSample sample = sampleConnectivityState();
2437 return ConnectivityStatsLog.buildStatsEvent(
2438 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2439 sample.getNetworkCountPerTransports().toByteArray(),
2440 sample.getConnectionDurationPerTransports().toByteArray(),
2441 sample.getNetworkRequestCount().toByteArray(),
2442 sample.getNetworks().toByteArray());
2443 }
2444
2445 /**
2446 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2447 *
2448 * This is used for metrics. These snapshots will be sampled and constitute a base for
2449 * statistics about connectivity state of devices.
2450 */
2451 @VisibleForTesting
2452 @NonNull
2453 public ConnectivityStateSample sampleConnectivityState() {
2454 ensureRunningOnConnectivityServiceThread();
2455 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2456 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2457 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2458 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2459 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2460 return builder.build();
2461 }
2462
2463 private static NetworkCountPerTransports sampleNetworkCount(
2464 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2465 final SparseIntArray countPerTransports = new SparseIntArray();
2466 for (final NetworkAgentInfo nai : nais) {
2467 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2468 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2469 }
2470 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2471 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2472 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2473 c.setTransportTypes(countPerTransports.keyAt(i));
2474 c.setNetworkCount(countPerTransports.valueAt(i));
2475 builder.addNetworkCountForTransports(c);
2476 }
2477 return builder.build();
2478 }
2479
2480 private static ConnectionDurationPerTransports sampleConnectionDuration(
2481 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2482 final ConnectionDurationPerTransports.Builder builder =
2483 ConnectionDurationPerTransports.newBuilder();
2484 for (final NetworkAgentInfo nai : nais) {
2485 final ConnectionDurationForTransports.Builder c =
2486 ConnectionDurationForTransports.newBuilder();
2487 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2488 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2489 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2490 // Add millisPerSecond/2 to round up or down to the nearest value
2491 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2492 builder.addConnectionDurationForTransports(c);
2493 }
2494 return builder.build();
2495 }
2496
2497 private static NetworkRequestCount sampleNetworkRequestCount(
2498 @NonNull final Collection<NetworkRequestInfo> nris) {
2499 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2500 final SparseIntArray countPerType = new SparseIntArray();
2501 for (final NetworkRequestInfo nri : nris) {
2502 final int type;
2503 if (Process.SYSTEM_UID == nri.mAsUid) {
2504 // The request is filed "as" the system, so it's the system on its own behalf.
2505 type = RequestType.RT_SYSTEM.getNumber();
2506 } else if (Process.SYSTEM_UID == nri.mUid) {
2507 // The request is filed by the system as some other app, so it's the system on
2508 // behalf of an app.
2509 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2510 } else {
2511 // Not the system, so it's an app requesting on its own behalf.
2512 type = RequestType.RT_APP.getNumber();
2513 }
2514 countPerType.put(type, countPerType.get(type, 0));
2515 }
2516 for (int i = countPerType.size() - 1; i >= 0; --i) {
2517 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2518 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2519 r.setRequestCount(countPerType.valueAt(i));
2520 builder.addRequestCountForType(r);
2521 }
2522 return builder.build();
2523 }
2524
2525 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2526 final NetworkList.Builder builder = NetworkList.newBuilder();
2527 for (final NetworkAgentInfo nai : nais) {
2528 final NetworkCapabilities nc = nai.networkCapabilities;
2529 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2530 d.setTransportTypes((int) nc.getTransportTypesInternal());
2531 final MeteredState meteredState;
2532 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2533 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2534 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2535 meteredState = MeteredState.METERED_NO;
2536 } else {
2537 meteredState = MeteredState.METERED_YES;
2538 }
2539 d.setMeteredState(meteredState);
2540 final ValidatedState validatedState;
2541 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2542 validatedState = ValidatedState.VS_PORTAL;
2543 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2544 validatedState = ValidatedState.VS_PARTIAL;
2545 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2546 validatedState = ValidatedState.VS_VALID;
2547 } else {
2548 validatedState = ValidatedState.VS_INVALID;
2549 }
2550 d.setValidatedState(validatedState);
2551 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2552 d.setCapabilities(nc.getCapabilitiesInternal());
2553 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2554 builder.addNetworkDescription(d);
2555 }
2556 return builder.build();
2557 }
2558
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002559 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002560 public boolean isNetworkSupported(int networkType) {
2561 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002562 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002563 }
2564
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002565 /**
2566 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002567 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002568 * @return the ip properties for the active network, or {@code null} if
2569 * none is active
2570 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002571 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002572 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002573 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002574 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002575 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2576 if (nai == null) return null;
2577 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002578 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002579 }
2580
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002581 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002582 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002583 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002584 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002585 final LinkProperties lp = getLinkProperties(nai);
2586 if (lp == null) return null;
2587 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002588 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002589 }
2590
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002591 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002592 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002593 public LinkProperties getLinkProperties(Network network) {
2594 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002595 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2596 if (lp == null) return null;
2597 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002598 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002599 }
2600
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002601 @Nullable
2602 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002603 if (nai == null) {
2604 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002605 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002606 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002607 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002608 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002609 }
2610
lucaslinc582d502022-01-27 09:07:00 +08002611 @Override
2612 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002613 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002614 @NonNull String packageName, @Nullable String callingAttributionTag) {
2615 Objects.requireNonNull(packageName);
2616 Objects.requireNonNull(lp);
2617 enforceNetworkStackOrSettingsPermission();
2618 if (!checkAccessPermission(-1 /* pid */, uid)) {
2619 return null;
2620 }
2621 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2622 }
2623
Qingxi Lib2748102020-01-08 12:51:49 -08002624 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2625 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2626 }
2627
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002628 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002629 if (nai == null) return null;
2630 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002631 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002632 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002633 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002634 }
2635
2636 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002637 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2638 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002639 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002640 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002641 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002642 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002643 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002644 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002645 }
2646
lucaslinc582d502022-01-27 09:07:00 +08002647 @Override
lucaslind2b06132022-03-02 10:56:57 +08002648 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2649 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2650 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002651 Objects.requireNonNull(nc);
2652 Objects.requireNonNull(packageName);
2653 enforceNetworkStackOrSettingsPermission();
2654 if (!checkAccessPermission(-1 /* pid */, uid)) {
2655 return null;
2656 }
2657 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2658 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2659 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2660 callingAttributionTag);
2661 }
2662
lucaslin69e1aa92022-03-22 18:15:09 +08002663 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2664 if (nc.getUnderlyingNetworks() != null
2665 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2666 nc.setUnderlyingNetworks(null);
2667 }
2668 }
2669
Chalard Jean53017782022-11-24 17:13:44 +09002670 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
2671 return Process.SYSTEM_UID == uid
Chalard Jean53017782022-11-24 17:13:44 +09002672 || checkAnyPermissionOf(mContext, pid, uid,
2673 android.Manifest.permission.NETWORK_FACTORY);
2674 }
2675
Qingxi Libb8da982020-01-17 17:54:27 -08002676 @VisibleForTesting
2677 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002678 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002679 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2680 // this would be expensive (one more permission check every time any NC callback is
2681 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2682 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2683 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002684 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002685 if (!checkSettingsPermission(callerPid, callerUid)) {
2686 newNc.setUids(null);
2687 newNc.setSSID(null);
2688 }
Etan Cohen107ae952018-12-30 17:59:59 -08002689 if (newNc.getNetworkSpecifier() != null) {
2690 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2691 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002692 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2693 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002694 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2695 newNc.setAdministratorUids(new int[0]);
2696 }
Chalard Jean53017782022-11-24 17:13:44 +09002697 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09002698 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002699 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002700 }
lucaslin69e1aa92022-03-22 18:15:09 +08002701 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002702
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002703 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002704 }
2705
Roshan Pius98f59ec2021-02-23 08:47:39 -08002706 /**
2707 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002708 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002709 * NetworkCapabilities.
2710 * Note: This wrapper does not support any sort of invalidation and thus must not be
2711 * persistent or long-lived. It may only be used for the time necessary to
2712 * compute the redactions required by one particular NetworkCallback or
2713 * synchronous call.
2714 */
2715 private class RedactionPermissionChecker {
2716 private final int mCallingPid;
2717 private final int mCallingUid;
2718 @NonNull private final String mCallingPackageName;
2719 @Nullable private final String mCallingAttributionTag;
2720
2721 private Boolean mHasLocationPermission = null;
2722 private Boolean mHasLocalMacAddressPermission = null;
2723 private Boolean mHasSettingsPermission = null;
2724
2725 RedactionPermissionChecker(int callingPid, int callingUid,
2726 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2727 mCallingPid = callingPid;
2728 mCallingUid = callingUid;
2729 mCallingPackageName = callingPackageName;
2730 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002731 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002732
2733 private boolean hasLocationPermissionInternal() {
2734 final long token = Binder.clearCallingIdentity();
2735 try {
2736 return mLocationPermissionChecker.checkLocationPermission(
2737 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2738 null /* message */);
2739 } finally {
2740 Binder.restoreCallingIdentity(token);
2741 }
2742 }
2743
2744 /**
2745 * Returns whether the app holds location permission or not (might return cached result
2746 * if the permission was already checked before).
2747 */
2748 public boolean hasLocationPermission() {
2749 if (mHasLocationPermission == null) {
2750 // If there is no cached result, perform the check now.
2751 mHasLocationPermission = hasLocationPermissionInternal();
2752 }
2753 return mHasLocationPermission;
2754 }
2755
2756 /**
2757 * Returns whether the app holds local mac address permission or not (might return cached
2758 * result if the permission was already checked before).
2759 */
2760 public boolean hasLocalMacAddressPermission() {
2761 if (mHasLocalMacAddressPermission == null) {
2762 // If there is no cached result, perform the check now.
2763 mHasLocalMacAddressPermission =
2764 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2765 }
2766 return mHasLocalMacAddressPermission;
2767 }
2768
2769 /**
2770 * Returns whether the app holds settings permission or not (might return cached
2771 * result if the permission was already checked before).
2772 */
2773 public boolean hasSettingsPermission() {
2774 if (mHasSettingsPermission == null) {
2775 // If there is no cached result, perform the check now.
2776 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2777 }
2778 return mHasSettingsPermission;
2779 }
2780 }
2781
2782 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2783 @NetworkCapabilities.NetCapability long redaction) {
2784 return (redactions & redaction) != 0;
2785 }
2786
2787 /**
2788 * Use the provided |applicableRedactions| to check the receiving app's
2789 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2790 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2791 * before being sent to the corresponding app.
2792 */
2793 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2794 @NetworkCapabilities.RedactionType long applicableRedactions,
2795 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2796 boolean includeLocationSensitiveInfo) {
2797 long redactions = applicableRedactions;
2798 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2799 if (includeLocationSensitiveInfo
2800 && redactionPermissionChecker.hasLocationPermission()) {
2801 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2802 }
2803 }
2804 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2805 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2806 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2807 }
2808 }
2809 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2810 if (redactionPermissionChecker.hasSettingsPermission()) {
2811 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2812 }
2813 }
2814 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002815 }
2816
Qingxi Lib2748102020-01-08 12:51:49 -08002817 @VisibleForTesting
2818 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002819 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002820 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002821 int callingPid, int callingUid, @NonNull String callingPkgName,
2822 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002823 if (nc == null) {
2824 return null;
2825 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002826 // Avoid doing location permission check if the transport info has no location sensitive
2827 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002828 final RedactionPermissionChecker redactionPermissionChecker =
2829 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2830 callingAttributionTag);
2831 final long redactions = retrieveRequiredRedactions(
2832 nc.getApplicableRedactions(), redactionPermissionChecker,
2833 includeLocationSensitiveInfo);
2834 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002835 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002836 // TODO : calling UID is redacted because apps should generally not know what UID is
2837 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002838 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002839 newNc.setOwnerUid(INVALID_UID);
2840 return newNc;
2841 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002842 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2843 if (nc.hasTransport(TRANSPORT_VPN)) {
2844 // Owner UIDs already checked above. No need to re-check.
2845 return newNc;
2846 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002847 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2848 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002849 // compatibility for older apps.
2850 if (!includeLocationSensitiveInfo
2851 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002852 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002853 newNc.setOwnerUid(INVALID_UID);
2854 return newNc;
2855 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002856 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002857 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002858 newNc.setOwnerUid(INVALID_UID);
2859 }
Qingxi Lib2748102020-01-08 12:51:49 -08002860 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002861 }
2862
lucaslinc582d502022-01-27 09:07:00 +08002863 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002864 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2865 LinkProperties lp, int callerPid, int callerUid) {
2866 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002867 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2868 // this would be expensive (one more permission check every time any LP callback is
2869 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2870 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2871 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002872
2873 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2874 final boolean needsSanitization =
2875 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2876 if (!needsSanitization) {
2877 return new LinkProperties(lp);
2878 }
2879
2880 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002881 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002882 }
2883
2884 final LinkProperties newLp = new LinkProperties(lp);
2885 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2886 // object gets parceled.
2887 newLp.setCaptivePortalApiUrl(null);
2888 newLp.setCaptivePortalData(null);
2889 return newLp;
2890 }
2891
Roshan Pius08c94fb2020-01-16 12:17:17 -08002892 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2893 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002894 // There is no need to track the effective UID of the request here. If the caller
2895 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002896 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002897 // Unprivileged apps can only pass in null or their own UID.
2898 if (nc.getUids() == null) {
2899 // If the caller passes in null, the callback will also match networks that do not
2900 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2901 // In this case, redact everything in the request immediately. This ensures that the
2902 // app is not able to get any redacted information by filing an unredacted request
2903 // and observing whether the request matches something.
2904 if (nc.getNetworkSpecifier() != null) {
2905 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2906 }
2907 } else {
2908 nc.setSingleUid(callerUid);
2909 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002910 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002911 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002912 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002913
2914 // Clear owner UID; this can never come from an app.
2915 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002916 }
2917
Chalard Jean38354d12018-03-20 19:13:57 +09002918 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002919 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002920 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2921 }
2922 }
2923
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002924 @Override
2925 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2926 enforceAccessPermission();
2927 final int callerUid = Binder.getCallingUid();
2928 final long token = Binder.clearCallingIdentity();
2929 try {
2930 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2931 } finally {
2932 Binder.restoreCallingIdentity(token);
2933 }
2934 }
2935
junyulaiebd15162021-03-03 12:09:05 +08002936 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002937 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002938 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002939 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002940 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002941
Serik Beketayev05130302021-01-15 16:47:25 -08002942 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002943 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002944 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2945 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002946 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002947 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002948 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002949 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2950 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002951 }
2952 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002953 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002954 }
2955
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002956 @Override
junyulaiebd15162021-03-03 12:09:05 +08002957 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002958 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002959 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002960 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002961
2962 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2963 for (Network network : getAllNetworks()) {
2964 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002965 final boolean includeNetwork = (nai != null) && nai.isCreated();
2966 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002967 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2968 // NetworkCapabilities, which may contain UIDs of apps to which the
2969 // network applies. Should the UIDs be cleared so as not to leak or
2970 // interfere ?
2971 result.add(nai.getNetworkStateSnapshot());
2972 }
2973 }
2974 return result;
2975 }
2976
2977 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002978 public boolean isActiveNetworkMetered() {
2979 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002980
Qingxi Lib2748102020-01-08 12:51:49 -08002981 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002982 if (caps != null) {
2983 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2984 } else {
2985 // Always return the most conservative value
2986 return true;
2987 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002988 }
2989
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002990 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002991 * Ensures that the system cannot call a particular method.
2992 */
2993 private boolean disallowedBecauseSystemCaller() {
2994 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002995 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2996 // for devices launched with Q and above. However, existing devices upgrading to Q and
2997 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002998 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002999 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003000 log("This method exists only for app backwards compatibility"
3001 + " and must not be called by system services.");
3002 return true;
3003 }
3004 return false;
3005 }
3006
paulhub2c28682021-08-18 18:35:54 +08003007 private int getAppUid(final String app, final UserHandle user) {
3008 final PackageManager pm =
3009 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
3010 final long token = Binder.clearCallingIdentity();
3011 try {
3012 return pm.getPackageUid(app, 0 /* flags */);
3013 } catch (PackageManager.NameNotFoundException e) {
3014 return -1;
3015 } finally {
3016 Binder.restoreCallingIdentity(token);
3017 }
3018 }
3019
3020 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
3021 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
3022 if (getAppUid(packageName, user) != callingUid) {
3023 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
3024 }
3025 }
3026
Lorenzo Colitti23862912018-09-28 11:31:55 +09003027 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003028 * Ensure that a network route exists to deliver traffic to the specified
3029 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003030 * @param networkType the type of the network over which traffic to the
3031 * specified host is to be routed
3032 * @param hostAddress the IP address of the host to which the route is
3033 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003034 * @return {@code true} on success, {@code false} on failure
3035 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003036 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003037 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3038 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003039 if (disallowedBecauseSystemCaller()) {
3040 return false;
3041 }
paulhub2c28682021-08-18 18:35:54 +08003042 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003043 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003044 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003045 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003046 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003047
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003048 InetAddress addr;
3049 try {
3050 addr = InetAddress.getByAddress(hostAddress);
3051 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003052 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003053 return false;
3054 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003055
The Android Open Source Project28527d22009-03-03 19:31:44 -08003056 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003057 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003058 return false;
3059 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003060
3061 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3062 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003063 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003064 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3065 } else {
3066 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3067 }
3068 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003069 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003070
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003071 DetailedState netState;
3072 synchronized (nai) {
3073 netState = nai.networkInfo.getDetailedState();
3074 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003075
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003076 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003077 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003078 log("requestRouteToHostAddress on down network "
3079 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003080 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003081 }
3082 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003083 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003084
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003085 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003086 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003087 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003088 LinkProperties lp;
3089 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003090 synchronized (nai) {
3091 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003092 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003093 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003094 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003095 if (DBG) {
3096 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3097 }
Wink Saville32506bc2013-06-29 21:10:57 -07003098 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003099 } finally {
3100 Binder.restoreCallingIdentity(token);
3101 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003102 }
3103
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003104 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003105 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003106 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003107 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003108 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003109 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003110 if (bestRoute.getGateway().equals(addr)) {
3111 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003112 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003113 } else {
3114 // if we will connect to this through another route, add a direct route
3115 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003116 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003117 }
3118 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003119 if (DBG) log("Adding legacy route " + bestRoute +
3120 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003121
3122 final String dst = bestRoute.getDestinationLinkAddress().toString();
3123 final String nextHop = bestRoute.hasGateway()
3124 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003125 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003126 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3127 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003128 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003129 return false;
3130 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003131 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003132 }
3133
paulhu7c0a2e62021-01-08 00:51:49 +08003134 class DnsResolverUnsolicitedEventCallback extends
3135 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003136 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003137 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003138 try {
3139 mHandler.sendMessage(mHandler.obtainMessage(
3140 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003141 new PrivateDnsValidationUpdate(event.netId,
3142 InetAddresses.parseNumericAddress(event.ipAddress),
3143 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003144 } catch (IllegalArgumentException e) {
3145 loge("Error parsing ip address in validation event");
3146 }
3147 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003148
3149 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003150 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3151 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003152 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3153 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3154 // event callback for certain nai. e.g. cellular. Register here to pass to
3155 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003156 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003157 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3158 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003159 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003160 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003161 }
3162 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003163
3164 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003165 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3166 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3167 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003168 }
dalyk1720e542018-03-05 12:42:22 -05003169
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003170 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003171 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003172 return this.VERSION;
3173 }
3174
3175 @Override
3176 public String getInterfaceHash() {
3177 return this.HASH;
3178 }
paulhu7c0a2e62021-01-08 00:51:49 +08003179 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003180
3181 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003182 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3183 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003184
paulhu7c0a2e62021-01-08 00:51:49 +08003185 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003186 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003187 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003188 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003189 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003190 }
3191 }
3192
Sudheer Shanka9967d462021-03-18 19:09:25 +00003193 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003194 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003195 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003196 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3197 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003198 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003199 };
3200
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003201 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003202 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003203 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003204 }
3205
Mark Fasheh7c999d82023-05-04 20:23:11 +00003206 static final class UidFrozenStateChangedArgs {
3207 final int[] mUids;
3208 final int[] mFrozenStates;
3209
3210 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3211 mUids = uids;
3212 mFrozenStates = frozenStates;
3213 }
3214 }
3215
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003216 /**
3217 * Check if the cell network is idle.
3218 * @return true if the cell network state is idle
3219 * false if the cell network state is active or unknown
3220 */
3221 private boolean isCellNetworkIdle() {
3222 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3223 if (defaultNai == null
3224 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3225 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3226 // cell network is not the default network, cell network state is unknown.
3227 // TODO(b/279380356): Track cell network state when the cell is not the default network
3228 return false;
3229 }
3230
3231 return !mNetworkActivityTracker.isDefaultNetworkActive();
3232 }
3233
Mark Fasheh7c999d82023-05-04 20:23:11 +00003234 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003235 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003236
3237 for (int i = 0; i < uids.length; i++) {
3238 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003239 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003240 } else {
3241 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003242 }
3243 }
3244
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003245 if (ownerUids.isEmpty()) {
3246 return;
3247 }
3248
3249 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3250 // Delay closing sockets to avoid waking the cell modem up.
3251 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3252 // than waking cell modem up.
3253 mPendingFrozenUids.addAll(ownerUids);
3254 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003255 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003256 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003257 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003258 loge("Exception in socket destroy: " + e);
3259 }
3260 }
3261 }
3262
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003263 private void closePendingFrozenSockets() {
3264 ensureRunningOnConnectivityServiceThread();
3265
3266 try {
3267 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3268 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3269 loge("Failed to close pending frozen app sockets: " + e);
3270 }
3271 mPendingFrozenUids.clear();
3272 }
3273
3274 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3275 mNetworkActivityTracker.handleReportNetworkActivity(params);
3276
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003277 final boolean isCellNetworkActivity;
3278 if (mTrackMultiNetworkActivities) {
3279 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3280 // nai could be null if netd receives a netlink message and calls the network
3281 // activity change callback after the network is unregistered from ConnectivityService.
3282 isCellNetworkActivity = nai != null
3283 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3284 } else {
3285 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3286 }
3287
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003288 if (mDelayDestroyFrozenSockets
3289 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003290 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003291 && !mPendingFrozenUids.isEmpty()) {
3292 closePendingFrozenSockets();
3293 }
3294 }
3295
3296 /**
3297 * If the cellular network is no longer the default network, close pending frozen sockets.
3298 *
3299 * @param newNetwork new default network
3300 * @param oldNetwork old default network
3301 */
3302 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3303 NetworkAgentInfo oldNetwork) {
3304 final boolean isOldNetworkCellular = oldNetwork != null
3305 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3306 final boolean isNewNetworkCellular = newNetwork != null
3307 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3308
3309 if (isOldNetworkCellular
3310 && !isNewNetworkCellular
3311 && !mPendingFrozenUids.isEmpty()) {
3312 closePendingFrozenSockets();
3313 }
3314 }
3315
3316 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3317 pw.println("CloseFrozenAppSockets:");
3318 pw.increaseIndent();
3319 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3320 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3321 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3322 pw.decreaseIndent();
3323 }
3324
Junyu Lai155760b2023-10-05 14:51:00 +08003325 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3326 pw.println("Bpf Program Status:");
3327 pw.increaseIndent();
3328 try {
3329 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003330 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003331 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003332 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003333 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003334 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003335 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003336 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003337 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003338 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003339 } catch (IOException e) {
3340 pw.println(" IOException");
3341 }
3342 pw.decreaseIndent();
3343 }
3344
Mark Fasheh7c999d82023-05-04 20:23:11 +00003345 @VisibleForTesting
3346 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003347 @VisibleForTesting
3348 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3349 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003350
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003351 @VisibleForTesting
3352 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3353 "allow_sysui_connectivity_reports";
3354
Yuyang Huang41557552023-11-28 12:47:22 +09003355 public static final String LOG_BPF_RC = "log_bpf_rc_force_disable";
3356
Paul Jensen83f5d572014-08-29 09:54:01 -04003357 private void enforceInternetPermission() {
3358 mContext.enforceCallingOrSelfPermission(
3359 android.Manifest.permission.INTERNET,
3360 "ConnectivityService");
3361 }
3362
The Android Open Source Project28527d22009-03-03 19:31:44 -08003363 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003364 mContext.enforceCallingOrSelfPermission(
3365 android.Manifest.permission.ACCESS_NETWORK_STATE,
3366 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003367 }
3368
lucaslinc582d502022-01-27 09:07:00 +08003369 private boolean checkAccessPermission(int pid, int uid) {
3370 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3371 == PERMISSION_GRANTED;
3372 }
3373
paulhua6ee2122021-02-22 15:40:43 +08003374 /**
3375 * Performs a strict and comprehensive check of whether a calling package is allowed to
3376 * change the state of network, as the condition differs for pre-M, M+, and
3377 * privileged/preinstalled apps. The caller is expected to have either the
3378 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3379 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3380 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3381 * permission and cannot be revoked. See http://b/23597341
3382 *
3383 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3384 * of this app will be updated to the current time.
3385 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003386 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003387 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3388 == PackageManager.PERMISSION_GRANTED) {
3389 return;
3390 }
3391
3392 if (callingPkg == null) {
3393 throw new SecurityException("Calling package name is null.");
3394 }
3395
3396 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3397 final int uid = mDeps.getCallingUid();
3398 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3399 callingPkg, callingAttributionTag, null /* message */);
3400
3401 if (mode == AppOpsManager.MODE_ALLOWED) {
3402 return;
3403 }
3404
3405 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3406 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3407 return;
3408 }
3409
3410 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3411 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3412 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003413 }
3414
Charles He9369e612017-05-15 17:07:18 +01003415 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003416 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003417 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003418 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003419 }
3420
Quang Luong98858d62023-02-11 00:25:24 +00003421 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003422 enforceAnyPermissionOf(mContext,
3423 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003424 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003425 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3426 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3427 }
3428
paulhu8e96a752019-08-12 16:25:11 +08003429 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003430 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003431 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003432 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003433 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003434 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003435 }
3436
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003437 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003438 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003439 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003440 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003441 android.Manifest.permission.NETWORK_SETTINGS,
3442 android.Manifest.permission.NETWORK_FACTORY,
3443 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3444 }
3445
3446 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003447 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003448 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003449 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003450 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3451 android.Manifest.permission.NETWORK_FACTORY,
3452 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3453 }
3454
lucaslin69e1aa92022-03-22 18:15:09 +08003455 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3456 return PERMISSION_GRANTED == mContext.checkPermission(
3457 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3458 || PERMISSION_GRANTED == mContext.checkPermission(
3459 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3460 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003461 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003462 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003463 }
3464
Chalard Jean9a396cc2018-02-21 18:43:54 +09003465 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003466 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003467 android.Manifest.permission.NETWORK_SETTINGS,
3468 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003469 }
3470
3471 private boolean checkSettingsPermission(int pid, int uid) {
3472 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003473 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3474 || PERMISSION_GRANTED == mContext.checkPermission(
3475 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003476 }
3477
paulhu8e96a752019-08-12 16:25:11 +08003478 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003479 enforceNetworkStackPermissionOr(mContext,
3480 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003481 }
3482
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003483 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003484 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003485 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003486 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003487 }
3488
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003489 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003490 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003491 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3492 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003493 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003494 }
3495
James Mattis8378aec2021-01-26 14:05:36 -08003496 private void enforceOemNetworkPreferencesPermission() {
3497 mContext.enforceCallingOrSelfPermission(
3498 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3499 "ConnectivityService");
3500 }
3501
James Mattisfa270db2021-05-31 17:11:10 -07003502 private void enforceManageTestNetworksPermission() {
3503 mContext.enforceCallingOrSelfPermission(
3504 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3505 "ConnectivityService");
3506 }
3507
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003508 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003509 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003510 android.Manifest.permission.NETWORK_STACK,
3511 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003512 }
3513
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003514 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003515 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003516 android.Manifest.permission.NETWORK_STACK,
3517 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3518 }
3519
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003520 private boolean checkSystemBarServicePermission(int pid, int uid) {
3521 return checkAnyPermissionOf(mContext, pid, uid,
3522 android.Manifest.permission.STATUS_BAR_SERVICE);
3523 }
3524
paulhu1a407652019-03-22 16:35:06 +08003525 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003526 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003527 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003528 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3529 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003530 }
3531
Paul Hu8fc2a552022-05-04 18:44:42 +08003532 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3533 boolean checkUidsAllowedList) {
3534 if (PermissionUtils.checkAnyPermissionOf(mContext,
3535 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3536 return true;
3537 }
3538
3539 // fallback to ConnectivityInternalPermission
3540 // TODO: Remove this fallback check after all apps have declared
3541 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3542 if (PermissionUtils.checkAnyPermissionOf(mContext,
3543 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3544 return true;
3545 }
3546
3547 // Check whether uid is in allowed on restricted networks list.
3548 if (checkUidsAllowedList
3549 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3550 return true;
3551 }
3552 return false;
3553 }
3554
3555 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3556 final int callingUid = mDeps.getCallingUid();
3557 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3558 throw new SecurityException("ConnectivityService: user " + callingUid
3559 + " has no permission to access restricted network.");
3560 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003561 }
3562
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003563 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003564 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003565 }
3566
Roshan Pius98f59ec2021-02-23 08:47:39 -08003567 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3568 return PERMISSION_GRANTED == mContext.checkPermission(
3569 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3570 }
3571
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003572 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003573 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003574 }
3575
3576 private void sendInetConditionBroadcast(NetworkInfo info) {
3577 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3578 }
3579
Wink Saville4f0de1e2011-08-04 15:01:58 -07003580 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003581 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003582 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003583 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003584 if (info.isFailover()) {
3585 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3586 info.setFailover(false);
3587 }
3588 if (info.getReason() != null) {
3589 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3590 }
3591 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003592 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3593 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003594 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003595 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003596 return intent;
3597 }
3598
3599 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3600 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3601 }
3602
Michael Groover73f69482023-01-27 11:01:25 -06003603 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3604 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003605 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3606 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003607 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003608 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003609 if (!mSystemReady
3610 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003611 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003612 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003613 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003614 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003615 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003616 }
3617
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003618 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003619 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003620 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003621 final NetworkInfo ni = intent.getParcelableExtra(
3622 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003623 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3624 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003625 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003626 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003627 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003628 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003629 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003630 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003631 } finally {
3632 Binder.restoreCallingIdentity(ident);
3633 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003634 }
3635 }
3636
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003637 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3638 NetworkInfo info) {
3639 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003640 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003641
3642 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3643 try {
3644 // This allows us to discard older broadcasts still waiting to be delivered
3645 // which have the same namespace and key.
3646 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3647 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3648 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003649 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003650 } catch (UnsupportedApiLevelException e) {
3651 Log.wtf(TAG, "Using unsupported API" + e);
3652 }
3653 }
3654
3655 @VisibleForTesting
3656 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3657 final StringBuilder sb = new StringBuilder();
3658 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3659 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3660 sb.append(info.getExtraInfo());
3661 return sb.toString();
3662 }
3663
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003664 /**
Aaron Huang96011892020-06-27 07:18:23 +08003665 * Called by SystemServer through ConnectivityManager when the system is ready.
3666 */
3667 @Override
3668 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003669 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003670 throw new SecurityException("Calling Uid is not system uid.");
3671 }
3672 systemReadyInternal();
3673 }
3674
3675 /**
3676 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003677 */
3678 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003679 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003680 // Load flags after PackageManager is ready to query module version
3681 mFlags.loadFlags(mDeps, mContext);
3682
Aaron Huang9a57acf2020-12-08 10:03:29 +08003683 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3684 // listening network request which is sent by MultipathPolicyTracker won't be added
3685 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3686 // be called after PermissionMonitor#startMonitoring().
3687 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3688 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3689 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003690 final ConditionVariable startMonitoringDone = new ConditionVariable();
3691 mHandler.post(() -> {
3692 mPermissionMonitor.startMonitoring();
3693 startMonitoringDone.open();
3694 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003695 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003696 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003697
Hugo Benichie5220992017-04-26 14:53:28 +09003698 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003699 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003700 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003701 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003702 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003703 }
3704 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003705
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003706 // Create network requests for always-on networks.
3707 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003708
3709 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003710 // Note that updating can be skipped here if the list is empty only because no uid
3711 // rules are applied before system ready. Normally, the empty uid list means to clear
3712 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003713 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3714 updateMobileDataPreferredUids();
3715 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003716
3717 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003718 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003719 mBpfNetMaps.setPullAtomCallback(mContext);
3720 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003721 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3722 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003723 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3724 // have permission problem. While CV#block() is unbounded in time and can in principle block
3725 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3726 // could have blocked forever too.
3727 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003728 }
3729
The Android Open Source Project28527d22009-03-03 19:31:44 -08003730 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003731 * Start listening for default data network activity state changes.
3732 */
3733 @Override
3734 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003735 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003736 }
3737
3738 /**
3739 * Stop listening for default data network activity state changes.
3740 */
3741 @Override
3742 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003743 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003744 }
3745
3746 /**
3747 * Check whether the default network radio is currently active.
3748 */
3749 @Override
3750 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003751 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003752 }
3753
3754 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003755 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003756 * and set it on it's iface.
3757 */
Junyu Lai970963e2022-10-25 15:46:47 +08003758 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003759 final String iface = newLp.getInterfaceName();
3760 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003761 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003762 // Silently ignore unset MTU value.
3763 return;
3764 }
Hansen Kurli04252032022-12-07 11:21:49 +00003765 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3766 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3767 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003768 return;
3769 }
Hansen Kurli04252032022-12-07 11:21:49 +00003770 // Cannot set MTU without interface name
3771 if (TextUtils.isEmpty(iface)) {
3772 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003773 return;
3774 }
sy.yun4aa73922013-09-02 05:24:09 +09003775
Hansen Kurli04252032022-12-07 11:21:49 +00003776 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3777 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003778 return;
3779 }
3780
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003781 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003782 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003783 mNetd.interfaceSetMtu(iface, mtu);
3784 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003785 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003786 }
3787 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003788
Chenbo Feng15416292018-11-08 17:36:21 -08003789 @VisibleForTesting
3790 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003791
Junyu Lai970963e2022-10-25 15:46:47 +08003792 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003793 String[] values = null;
3794 if (tcpBufferSizes != null) {
3795 values = tcpBufferSizes.split(",");
3796 }
3797
3798 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003799 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003800 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3801 values = tcpBufferSizes.split(",");
3802 }
3803
3804 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3805
3806 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003807 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003808
Chenbo Feng15416292018-11-08 17:36:21 -08003809 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3810 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3811 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003812 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003813 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003814 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003815 }
3816 }
3817
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003818 @Override
3819 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003820 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003821 NETWORK_RESTORE_DELAY_PROP_NAME);
3822 if(restoreDefaultNetworkDelayStr != null &&
3823 restoreDefaultNetworkDelayStr.length() != 0) {
3824 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003825 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003826 } catch (NumberFormatException e) {
3827 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003828 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003829 // if the system property isn't set, use the value for the apn type
3830 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3831
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003832 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3833 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003834 }
3835 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003836 }
3837
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003838 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003839 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003840 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003841 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003842 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003843 // Start gathering diagnostic information.
3844 netDiags.add(new NetworkDiagnostics(
3845 nai.network,
3846 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003847 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003848 DIAG_TIME_MS));
3849 }
3850
3851 for (NetworkDiagnostics netDiag : netDiags) {
3852 pw.println();
3853 netDiag.waitForMeasurements();
3854 netDiag.dump(pw);
3855 }
3856 }
3857
The Android Open Source Project28527d22009-03-03 19:31:44 -08003858 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003859 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3860 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003861 if (!checkDumpPermission(mContext, TAG, writer)) return;
3862
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003863 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003864 }
3865
lucaslin99473f62020-12-10 15:10:54 +08003866 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3867 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3868 != PackageManager.PERMISSION_GRANTED) {
3869 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003870 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003871 + " due to missing android.permission.DUMP permission");
3872 return false;
3873 } else {
3874 return true;
3875 }
3876 }
3877
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003878 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003879 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003880
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003881 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003882 dumpNetworkDiagnostics(pw);
3883 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003884 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003885 dumpNetworks(pw);
3886 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003887 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003888 dumpNetworkRequests(pw);
3889 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003890 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3891 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3892 dumpTrafficController(pw, fd, verbose);
3893 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003894 }
Erik Kline9647f382015-06-05 17:47:34 +09003895
Junyu Lai0da479b2022-04-20 15:06:29 +08003896 pw.println("NetworkProviders for:");
3897 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003898 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003899 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003900 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003901 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003902 pw.println();
3903
Chalard Jean5b409c72021-02-04 13:12:59 +09003904 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003905 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003906 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003907 pw.println("none");
3908 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003909 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003910 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003911 pw.println();
3912
James Mattis8b298a02021-06-01 22:34:04 -07003913 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003914 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003915 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003916 pw.decreaseIndent();
3917 pw.println();
3918
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003919 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003920 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003921 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003922 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003923 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003924
junyulaif2c67e42018-08-07 19:50:45 +08003925 pw.println("Status for known UIDs:");
3926 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003927 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003928 for (int i = 0; i < size; i++) {
3929 // Don't crash if the array is modified while dumping in bugreports.
3930 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003931 final int uid = mUidBlockedReasons.keyAt(i);
3932 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3933 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003934 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003935 } catch (ArrayIndexOutOfBoundsException e) {
3936 pw.println(" ArrayIndexOutOfBoundsException");
3937 } catch (ConcurrentModificationException e) {
3938 pw.println(" ConcurrentModificationException");
3939 }
3940 }
3941 pw.println();
3942 pw.decreaseIndent();
3943
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003944 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003945 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003946 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003947 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003948 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003949
Junyu Lai0da479b2022-04-20 15:06:29 +08003950 pw.println("Network Offers:");
3951 pw.increaseIndent();
3952 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3953 pw.println(offerInfo.offer);
3954 }
3955 pw.decreaseIndent();
3956 pw.println();
3957
Robert Greenwalt94e22142014-07-30 16:31:24 -07003958 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003959
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003960 pw.println();
markchien5e866652019-09-30 14:40:57 +08003961 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003962
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003963 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003964 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003965
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003966 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003967 dumpCloseFrozenAppSockets(pw);
3968
3969 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003970 dumpBpfProgramStatus(pw);
3971
Chalard Jean53017782022-11-24 17:13:44 +09003972 if (null != mCarrierPrivilegeAuthenticator) {
3973 pw.println();
3974 mCarrierPrivilegeAuthenticator.dump(pw);
3975 }
3976
Junyu Lai155760b2023-10-05 14:51:00 +08003977 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003978
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003979 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003980 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003981 pw.println("mNetworkRequestInfoLogs (most recent first):");
3982 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003983 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003984 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003985
3986 pw.println();
3987 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3988 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003989 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003990 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003991
3992 pw.println();
3993 pw.println("NetTransition WakeLock activity (most recent first):");
3994 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003995 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3996 pw.println("total releases: " + mTotalWakelockReleases);
3997 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3998 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3999 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
4000 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4001 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
4002 }
James Mattiscb1e0362021-04-06 17:07:42 -07004003 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004004
4005 pw.println();
4006 pw.println("bandwidth update requests (by uid):");
4007 pw.increaseIndent();
4008 synchronized (mBandwidthRequests) {
4009 for (int i = 0; i < mBandwidthRequests.size(); i++) {
4010 pw.println("[" + mBandwidthRequests.keyAt(i)
4011 + "]: " + mBandwidthRequests.valueAt(i));
4012 }
4013 }
4014 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004015 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004016
James Mattiscb1e0362021-04-06 17:07:42 -07004017 pw.println();
4018 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4019 pw.increaseIndent();
4020 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004021 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004022 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004023
4024 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004025
4026 pw.println();
4027 pw.println("Permission Monitor:");
4028 pw.increaseIndent();
4029 mPermissionMonitor.dump(pw);
4030 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004031
4032 pw.println();
4033 pw.println("Legacy network activity:");
4034 pw.increaseIndent();
4035 mNetworkActivityTracker.dump(pw);
4036 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08004037 }
4038
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004039 private void dumpNetworks(IndentingPrintWriter pw) {
4040 for (NetworkAgentInfo nai : networksSortedById()) {
4041 pw.println(nai.toString());
4042 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004043 pw.println("Nat464Xlat:");
4044 pw.increaseIndent();
4045 nai.dumpNat464Xlat(pw);
4046 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004047 pw.println(String.format(
4048 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4049 nai.numForegroundNetworkRequests(),
4050 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4051 nai.numBackgroundNetworkRequests(),
4052 nai.numNetworkRequests()));
4053 pw.increaseIndent();
4054 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4055 pw.println(nai.requestAt(i).toString());
4056 }
4057 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004058 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004059 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004060 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004061 pw.decreaseIndent();
4062 pw.decreaseIndent();
4063 }
4064 }
4065
James Mattis8b298a02021-06-01 22:34:04 -07004066 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4067 if (!mProfileNetworkPreferences.isEmpty()) {
4068 pw.println("Profile preferences:");
4069 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004070 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004071 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004072 }
James Mattis8b298a02021-06-01 22:34:04 -07004073 if (!mOemNetworkPreferences.isEmpty()) {
4074 pw.println("OEM preferences:");
4075 pw.increaseIndent();
4076 pw.println(mOemNetworkPreferences);
4077 pw.decreaseIndent();
4078 }
4079 if (!mMobileDataPreferredUids.isEmpty()) {
4080 pw.println("Mobile data preferred UIDs:");
4081 pw.increaseIndent();
4082 pw.println(mMobileDataPreferredUids);
4083 pw.decreaseIndent();
4084 }
James Mattis45d81842021-01-10 14:24:24 -08004085
James Mattis8b298a02021-06-01 22:34:04 -07004086 pw.println("Default requests:");
4087 pw.increaseIndent();
4088 dumpPerAppDefaultRequests(pw);
4089 pw.decreaseIndent();
4090 }
4091
4092 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004093 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4094 if (mDefaultRequest == defaultRequest) {
4095 continue;
4096 }
4097
James Mattis8b298a02021-06-01 22:34:04 -07004098 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4099 final String networkOutput;
4100 if (null == satisfier) {
4101 networkOutput = "null";
4102 } else if (mNoServiceNetwork.equals(satisfier)) {
4103 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004104 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004105 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004106 }
James Mattis8b298a02021-06-01 22:34:04 -07004107 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4108 ? "" : " asUid: " + defaultRequest.mAsUid;
4109 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4110 + defaultRequest.mPid + asUidString + "]";
4111 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4112 + " Preference order: " + defaultRequest.mPreferenceOrder
4113 + " Tracked UIDs: " + defaultRequest.getUids();
4114 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004115 }
4116 }
4117
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004118 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004119 NetworkRequestInfo[] infos = null;
4120 while (infos == null) {
4121 try {
4122 infos = requestsSortedById();
4123 } catch (ConcurrentModificationException e) {
4124 // mNetworkRequests should only be accessed from handler thread, except dump().
4125 // As dump() is never called in normal usage, it would be needlessly expensive
4126 // to lock the collection only for its benefit. Instead, retry getting the
4127 // requests if ConcurrentModificationException is thrown during dump().
4128 }
4129 }
4130 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004131 pw.println(nri.toString());
4132 }
4133 }
4134
Ken Chene6d511f2022-01-25 11:10:42 +08004135 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4136 boolean verbose) {
4137 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004138 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004139 } catch (ServiceSpecificException e) {
4140 pw.println(e.getMessage());
4141 } catch (IOException e) {
4142 loge("Dump BPF maps failed, " + e);
4143 }
4144 }
4145
Chalard Jean524f0b12021-10-25 21:11:56 +09004146 private void dumpAllRequestInfoLogsToLogcat() {
4147 try (PrintWriter logPw = new PrintWriter(new Writer() {
4148 @Override
4149 public void write(final char[] cbuf, final int off, final int len) {
4150 // This method is called with 0-length and 1-length arrays for empty strings
4151 // or strings containing only the DEL character.
4152 if (len <= 1) return;
4153 Log.e(TAG, new String(cbuf, off, len));
4154 }
4155 @Override public void flush() {}
4156 @Override public void close() {}
4157 })) {
4158 mNetworkRequestInfoLogs.dump(logPw);
4159 }
4160 }
4161
Hugo Benichia480ba52018-09-03 08:19:02 +09004162 /**
4163 * Return an array of all current NetworkAgentInfos sorted by network id.
4164 */
4165 private NetworkAgentInfo[] networksSortedById() {
4166 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004167 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004168 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004169 return networks;
4170 }
4171
4172 /**
4173 * Return an array of all current NetworkRequest sorted by request id.
4174 */
James Mattis258ea3c2020-11-15 15:04:40 -08004175 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004176 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004177 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004178 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004179 // Sort the array based off the NRI containing the min requestId in its requests.
4180 Arrays.sort(requests,
4181 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4182 Comparator.comparingInt(req -> req.requestId)).requestId
4183 )
4184 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004185 return requests;
4186 }
4187
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004188 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004189 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004190 if (officialNai != null && officialNai.equals(nai)) return true;
4191 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004192 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004193 " - " + nai);
4194 }
4195 return false;
4196 }
4197
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004198 private boolean isDisconnectRequest(Message msg) {
4199 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4200 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4201 return info.getState() == NetworkInfo.State.DISCONNECTED;
4202 }
4203
Robert Greenwalt2034b912009-08-12 16:08:25 -07004204 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004205 private class NetworkStateTrackerHandler extends Handler {
4206 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004207 super(looper);
4208 }
4209
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004210 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004211 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4212 final NetworkAgentInfo nai = arg.first;
4213 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004214 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004215 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004216 }
4217 return;
4218 }
4219
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004220 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004221 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004222 return;
4223 }
4224
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004225 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004226 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004227 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4228 if (!nai.respectsNcStructuralConstraints(proposed)) {
4229 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4230 + nai.networkCapabilities + " -> " + proposed);
4231 disconnectAndDestroyNetwork(nai);
4232 return;
4233 }
4234 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004235 final NetworkCapabilities sanitized =
4236 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004237 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004238 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004239 break;
4240 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004241 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004242 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004243 processLinkPropertiesFromAgent(nai, newLp);
4244 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004245 break;
4246 }
4247 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004248 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004249 updateNetworkInfo(nai, info);
4250 break;
4251 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004252 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4253 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004254 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004255 break;
4256 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004257 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004258 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004259 break;
4260 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004261 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004262 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004263 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004264 // Note that if the NAI had been connected, this would affect the
4265 // score, and therefore would require re-mixing the score and performing
4266 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004267 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004268 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4269 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004270 // Mark the network as temporarily accepting partial connectivity so that it
4271 // will be validated (and possibly become default) even if it only provides
4272 // partial internet access. Note that if user connects to partial connectivity
4273 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4274 // out of wifi coverage) and if the same wifi is available again, the device
4275 // will auto connect to this wifi even though the wifi has "no internet".
4276 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004277 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004278 break;
4279 }
junyulai011b1f12019-01-03 18:50:15 +08004280 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004281 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004282 break;
4283 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004284 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004285 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004286 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004287
4288 if (isLegacyLockdownNai(nai)
4289 && (underlying == null || underlying.size() != 1)) {
4290 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4291 + " must have exactly one underlying network: " + underlying);
4292 }
4293
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004294 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4295 nai.declaredUnderlyingNetworks = (underlying != null)
4296 ? underlying.toArray(new Network[0]) : null;
4297
4298 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4299 if (DBG) {
4300 log(nai.toShortString() + " changed underlying networks to "
4301 + Arrays.toString(nai.declaredUnderlyingNetworks));
4302 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004303 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004304 notifyIfacesChangedForNetworkStats();
4305 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004306 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004307 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004308 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4309 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4310 nai.teardownDelayMs = msg.arg1;
4311 } else {
4312 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4313 }
Chalard Jean550b5212021-03-05 23:07:53 +09004314 break;
4315 }
4316 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4317 nai.setLingerDuration((int) arg.second);
4318 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004319 }
Tyler Wear72388212021-09-09 14:49:02 -07004320 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4321 DscpPolicy policy = (DscpPolicy) arg.second;
4322 if (mDscpPolicyTracker != null) {
4323 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4324 }
4325 break;
4326 }
4327 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4328 if (mDscpPolicyTracker != null) {
4329 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4330 }
4331 break;
4332 }
4333 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4334 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004335 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004336 }
4337 break;
4338 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004339 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004340 if (!nai.everConnected()) {
4341 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4342 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004343 teardownUnneededNetwork(nai);
4344 break;
4345 }
4346
4347 if (nai.isDestroyed()) {
4348 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4349 + ", ignoring");
4350 break;
4351 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004352
4353 final int timeoutMs = (int) arg.second;
4354 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4355 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4356 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4357 }
4358
4359 // Marking a network awaiting replacement is used to ensure that any requests
4360 // satisfied by the network do not switch to another network until a
4361 // replacement is available or the wait for a replacement times out.
4362 // If the network is inactive (i.e., nascent or lingering), then there are no
4363 // such requests, and there is no point keeping it. Just tear it down.
4364 // Note that setLingerDuration(0) cannot be used to do this because the network
4365 // could be nascent.
4366 nai.clearInactivityState();
4367 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4368 Log.d(TAG, nai.toShortString()
4369 + " marked awaiting replacement is unneeded, tearing down instead");
4370 teardownUnneededNetwork(nai);
4371 break;
4372 }
4373
4374 Log.d(TAG, "Marking " + nai.toShortString()
4375 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4376 destroyNativeNetwork(nai);
4377
4378 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4379 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4380 // consider the fact that the network could already have disconnected or been
4381 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4382 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4383 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4384 mKeepaliveTracker.handleStopAllKeepalives(nai,
4385 SocketKeepalive.ERROR_INVALID_NETWORK);
4386
4387 nai.updateScoreForNetworkAgentUpdate();
4388 // This rematch is almost certainly not going to result in any changes, because
4389 // the destroyed flag is only just above the "current satisfier wins"
4390 // tie-breaker. But technically anything that affects scoring should rematch.
4391 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004392 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004393 break;
4394 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004395 }
4396 }
4397
4398 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004399 final int netId = msg.arg2;
4400 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004401 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004402 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004403 switch (msg.what) {
4404 default:
4405 return false;
lucasline117e2e2019-10-22 18:27:33 +08004406 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004407 if (nai == null) {
4408 break;
4409 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004410 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4411 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004412 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004413 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004414 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004415 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004416 if (probePrivateDnsCompleted) {
4417 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4418 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004419 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004420 }
4421 // Only show the notification when the private DNS is broken and the
4422 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004423 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004424 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4425 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004426 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004427 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4428 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4429 // private DNS is broken, it means this network is being reevaluated.
4430 // Either probing private DNS is not necessary any more or it hasn't been
4431 // done yet. In either case, the networkCapabilities should be updated to
4432 // reflect the new status.
4433 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004434 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004435 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004436 }
4437 break;
4438 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004439 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004440 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4441
Erik Kline31b4a9e2018-01-11 21:07:29 +09004442 if (nai == null) break;
4443
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004444 handleNetworkTested(nai, results.mTestResult,
4445 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004446 break;
4447 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004448 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004449 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004450 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004451 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004452 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004453 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004454 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4455 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004456 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004457 if (nai == null) {
4458 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4459 break;
4460 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004461 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004462 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004463 (PendingIntent) msg.obj,
4464 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004465 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004466 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004467 break;
4468 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004469 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004470 if (nai == null) break;
4471
Erik Kline9a62f012018-03-21 07:18:33 -07004472 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004473 break;
4474 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004475 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004476 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004477 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004478 break;
4479 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004480 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004481 return true;
4482 }
4483
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004484 private void handleNetworkTested(
4485 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004486 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4487 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004488 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004489
4490 // If there is any kind of working networking, then the NAI has been evaluated
4491 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4492 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004493 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004494 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004495 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4496 // any callback that receives onAvailable for that rematch receives an extra caps
4497 // callback. To prevent that, update the score in the agent so the updates below won't
4498 // see an update to both caps and score at the same time.
4499 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004500 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4501
he_won.hwang881307a2022-03-15 21:23:52 +09004502 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4503 // Assume the validation failure is due to a temporary failure after roaming
4504 // and ignore it. NetworkMonitor will continue to retry validation. If it
4505 // continues to fail after the block timeout expires, the network will be
4506 // marked unvalidated. If it succeeds, then validation state will not change.
4507 return;
4508 }
4509
Chalard Jean254bd162022-08-25 13:04:51 +09004510 final boolean wasValidated = nai.isValidated();
4511 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004512 final boolean wasPortal = nai.captivePortalDetected();
4513 nai.setPartialConnectivity(partial);
4514 nai.setCaptivePortalDetected(portal);
4515 nai.updateScoreForNetworkAgentUpdate();
4516 final boolean partialConnectivityChanged = (wasPartial != partial);
4517 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004518
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004519 if (DBG) {
4520 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4521 ? " with redirect to " + redirectUrl
4522 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004523 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004524 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004525 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004526 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004527 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004528 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004529 if (valid) {
4530 handleFreshlyValidatedNetwork(nai);
4531 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4532 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004533 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004534 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004535 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004536 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004537 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004538 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004539 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004540 NotificationType.PRIVATE_DNS_BROKEN);
4541 // If network becomes valid, the hasShownBroken should be reset for
4542 // that network so that the notification will be fired when the private
4543 // DNS is broken again.
4544 nai.networkAgentConfig.hasShownBroken = false;
4545 }
4546 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004547 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004548 } else if (portalChanged) {
4549 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004550 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004551 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4552 nai.onPreventAutomaticReconnect();
4553 teardownUnneededNetwork(nai);
4554 return;
4555 } else {
4556 updateCapabilitiesForNetwork(nai);
4557 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004558 } else if (becameEvaluated) {
4559 // If valid or partial connectivity changed, updateCapabilities* has
4560 // done the rematch.
4561 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004562 }
4563 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004564
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004565 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004566 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004567 nai.onValidationStatusChanged(
4568 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4569 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004570
4571 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004572 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004573 // immediately. Re-notify partial connectivity silently if no internet
4574 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004575 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004576 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004577 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4578 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004579 }
4580
Chalard Jean254bd162022-08-25 13:04:51 +09004581 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004582 handleNetworkUnvalidated(nai);
4583 }
4584 }
4585
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004586 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4587 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4588 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4589 // Do not avoid captive portal when network is wear proxy.
4590 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4591 }
4592
Calvin Ondada1452016-10-11 15:10:46 -07004593 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004594 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4595 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004596 }
4597
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004598 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4599 switch (msg.what) {
4600 default:
4601 return false;
4602 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4603 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4604 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4605 handleLingerComplete(nai);
4606 }
4607 break;
4608 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004609 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4610 handleNetworkAgentRegistered(msg);
4611 break;
4612 }
4613 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4614 handleNetworkAgentDisconnected(msg);
4615 break;
4616 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004617 }
4618 return true;
4619 }
4620
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004621 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004622 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004623 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004624 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004625 maybeHandleNetworkAgentMessage(msg);
4626 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004627 }
4628 }
4629
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004630 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004631 private final int mNetId;
4632 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004633
4634 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004635 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004636 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004637 }
4638
4639 @Override
4640 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4641 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004642 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004643 }
4644
4645 @Override
4646 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004647 // Legacy version of notifyNetworkTestedWithExtras.
4648 // Would only be called if the system has a NetworkStack module older than the
4649 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004650 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004651 }
4652
4653 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004654 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004655 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4656 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004657 final Message msg = mTrackerHandler.obtainMessage(
4658 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004659 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004660 new NetworkTestedResults(
4661 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004662 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004663
4664 // Invoke ConnectivityReport generation for this Network test event.
4665 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4666 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004667
Cody Kestingf1120be2020-08-03 18:01:40 -07004668 // NetworkMonitor reports the network validation result as a bitmask while
4669 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4670 // logical value for ConnectivityDiagnostics.
4671 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4672 p.result);
4673
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004674 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004675 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004676 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4677 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4678
Aaron Huang959d3642021-01-21 15:47:41 +08004679 ConnectivityReportEvent reportEvent =
4680 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4681 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004682 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004683 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004684 }
4685
4686 @Override
4687 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4688 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4689 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004690 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004691 }
4692
4693 @Override
lucasline117e2e2019-10-22 18:27:33 +08004694 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4695 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4696 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004697 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004698 }
4699
4700 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004701 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4702 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4703 EVENT_CAPPORT_DATA_CHANGED,
4704 0, mNetId, data));
4705 }
4706
4707 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004708 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004709 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004710 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004711
4712 final PendingIntent pendingIntent;
4713 // Only the system server can register notifications with package "android"
4714 final long token = Binder.clearCallingIdentity();
4715 try {
paulhu7746e4e2020-06-09 19:07:03 +08004716 pendingIntent = PendingIntent.getBroadcast(
4717 mContext,
4718 0 /* requestCode */,
4719 intent,
4720 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004721 } finally {
4722 Binder.restoreCallingIdentity(token);
4723 }
4724 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4725 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004726 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004727 }
4728
4729 @Override
4730 public void hideProvisioningNotification() {
4731 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004732 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004733 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004734
4735 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004736 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004737 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004738 }
4739
4740 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004741 public int getInterfaceVersion() {
4742 return this.VERSION;
4743 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004744
4745 @Override
4746 public String getInterfaceHash() {
4747 return this.HASH;
4748 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004749 }
4750
Cody Kestingf1120be2020-08-03 18:01:40 -07004751 /**
4752 * Converts the given NetworkMonitor-specific validation result bitmask to a
4753 * ConnectivityDiagnostics-specific validation result int.
4754 */
4755 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4756 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4757 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4758 }
4759 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4760 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4761 }
4762 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4763 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4764 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4765 }
4766
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004767 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004768 log("Data stall detected with methods: " + p.detectionMethod);
4769
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004770 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004771 int detectionMethod = 0;
4772 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4773 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4774 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4775 }
4776 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4777 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4778 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4779 p.tcpMetricsCollectionPeriodMillis);
4780 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004781 }
4782
Cody Kestingf53a0752020-04-15 12:33:28 -07004783 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004784 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004785 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004786
4787 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4788 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4789 // the cost of going through two handlers.
4790 mConnectivityDiagnosticsHandler.sendMessage(msg);
4791 }
4792
Cody Kestingb37958e2020-05-15 10:36:01 -07004793 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4794 return (p.detectionMethod & detectionMethod) != 0;
4795 }
4796
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004797 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4798 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004799 }
4800
Erik Klinea73af002018-06-26 18:53:43 +09004801 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4802 if (nai == null) return;
4803 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4804 // in order to restart a validation pass from within netd.
4805 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00004806 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004807 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004808 }
4809 }
4810
Erik Kline31b4a9e2018-01-11 21:07:29 +09004811 private void handlePrivateDnsSettingsChanged() {
4812 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4813
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004814 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004815 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004816 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004817 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4818 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004819 }
4820 }
4821
Erik Kline9a62f012018-03-21 07:18:33 -07004822 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4823 // Private DNS only ever applies to networks that might provide
4824 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004825 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004826
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004827 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004828 // schedule DNS resolutions. If a DNS resolution is required the
4829 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004830 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004831
4832 // With Private DNS bypass support, we can proceed to update the
4833 // Private DNS config immediately, even if we're in strict mode
4834 // and have not yet resolved the provider name into a set of IPs.
4835 updatePrivateDns(nai, cfg);
4836 }
4837
4838 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4839 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004840 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004841 }
4842
dalyk1720e542018-03-05 12:42:22 -05004843 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4844 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4845 if (nai == null) {
4846 return;
4847 }
4848 mDnsManager.updatePrivateDnsValidation(update);
4849 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4850 }
4851
paulhu7c0a2e62021-01-08 00:51:49 +08004852 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004853 int prefixLength) {
4854 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4855 if (nai == null) return;
4856
paulhu7c0a2e62021-01-08 00:51:49 +08004857 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4858 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004859
4860 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004861 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004862 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004863 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004864 prefixLength);
4865 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004866 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004867 return;
4868 }
4869 }
4870
Lorenzo Colittid523d142020-04-01 20:16:30 +09004871 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004872 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4873 }
4874
Hai Shalome58bdc62021-01-11 18:45:34 -08004875 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004876 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004877 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004878 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4879 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4880 }
4881
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004882 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004883 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004884 * @param nai the agent info to update
4885 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004886 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004887 */
junyulai2b6f0c22021-02-03 20:15:30 +08004888 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4889 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4890 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004891 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004892 // one lingered request, set inactive.
4893 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004894 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004895 if (DBG) log("Unsetting inactive " + nai.toShortString());
4896 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004897 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004898 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004899 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004900 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4901 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004902 }
junyulai2b6f0c22021-02-03 20:15:30 +08004903 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004904 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004905 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004906 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004907 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004908 }
4909
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004910 private void handleNetworkAgentRegistered(Message msg) {
4911 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4912 if (!mNetworkAgentInfos.contains(nai)) {
4913 return;
4914 }
4915
4916 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4917 if (VDBG) log("NetworkAgent registered");
4918 } else {
4919 loge("Error connecting NetworkAgent");
4920 mNetworkAgentInfos.remove(nai);
4921 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004922 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004923 synchronized (mNetworkForNetId) {
4924 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004925 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004926 mNetIdManager.releaseNetId(nai.network.getNetId());
4927 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004928 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004929 }
4930 }
4931 }
Paul Jensend5f53392014-11-25 15:26:53 -05004932
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004933 @VisibleForTesting
4934 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004935 // The feature of creating the networks immediately was slated for U, but race conditions
4936 // detected late required this was flagged off.
4937 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4938 // in NetworkAgentTest.
4939 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004940 }
4941
4942 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4943 @NonNull NetworkInfo.State state) {
4944 if (nai.isCreated()) return false;
4945 if (state == NetworkInfo.State.CONNECTED) return true;
4946 if (state != NetworkInfo.State.CONNECTING) {
4947 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004948 if (shouldCreateNetworksImmediately()) {
4949 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4950 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004951 return false;
4952 }
4953 return nai.isVPN() || shouldCreateNetworksImmediately();
4954 }
4955
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004956 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004957 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004958 }
4959
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004960 @VisibleForTesting
4961 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004962 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004963 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004964
4965 // If the network never roamed, return false. The check below is not sufficient if time
4966 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4967 if (nai.lastRoamTime == 0) return false;
4968
he_won.hwang881307a2022-03-15 21:23:52 +09004969 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4970 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004971 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004972 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004973 final long currentTimeMs = SystemClock.elapsedRealtime();
4974 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004975 if (timeSinceLastRoam <= blockTimeOut) {
4976 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4977 return true;
4978 }
4979 }
4980 return false;
4981 }
4982
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004983 private void handleNetworkAgentDisconnected(Message msg) {
4984 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004985 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004986 }
4987
Chalard Jeand9fffc32018-05-11 20:19:20 +09004988 // Destroys a network, remove references to it from the internal state managed by
4989 // ConnectivityService, free its interfaces and clean up.
4990 // Must be called on the Handler thread.
4991 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004992 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004993
4994 if (!mNetworkAgentInfos.contains(nai)) return;
4995
Chalard Jeand9fffc32018-05-11 20:19:20 +09004996 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004997 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004998 }
lucaslinb25c9a62019-02-12 15:30:13 +08004999 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005000 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005001 // A network agent has disconnected.
5002 // TODO - if we move the logic to the network agent (have them disconnect
5003 // because they lost all their requests or because their score isn't good)
5004 // then they would disconnect organically, report their new state and then
5005 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08005006 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005007 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
5008 null, null);
5009 }
Chalard Jean5b409c72021-02-04 13:12:59 +09005010 final boolean wasDefault = isDefaultNetwork(nai);
5011 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005012 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09005013 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005014 if (mTrackMultiNetworkActivities) {
5015 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
5016 // the network becomes no longer the default network.
5017 mNetworkActivityTracker.removeDataActivityTracking(nai);
5018 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005019 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005020 // If this was a local network forwarded to some upstream, or if some local network was
5021 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005022 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005023 // If this is a local network with an upstream selector, remove the associated network
5024 // request.
5025 if (nai.isLocalNetwork()) {
5026 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5027 if (null != selector) {
5028 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5029 }
5030 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005031 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5032 // by other networks that are already connected. Perhaps that can be done by
5033 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5034 // of rematchAllNetworksAndRequests
5035 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005036 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005037
5038 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005039 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5040 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005041 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005042 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005043 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005044 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005045 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005046 synchronized (mNetworkForNetId) {
5047 // Remove the NetworkAgent, but don't mark the netId as
5048 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005049 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005050 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005051 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005052 // Update allowed network lists in netd. This should be called after removing nai
5053 // from mNetworkAgentInfos.
5054 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005055 // Remove all previously satisfied requests.
5056 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005057 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005058 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005059 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005060 if (currentNetwork != null
5061 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005062 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005063 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5064 // rematch not to keep disconnected agents instead of setting it here ; this
5065 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005066 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005067 for (final NetworkOfferInfo noi : mNetworkOffers) {
5068 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005069 }
James Mattise3ef1912020-12-20 11:09:58 -08005070
Chalard Jean5b409c72021-02-04 13:12:59 +09005071 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005072 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005073 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005074 ensureNetworkTransitionWakelock(nai.toShortString());
5075 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005076 }
5077 }
junyulai2b6f0c22021-02-03 20:15:30 +08005078 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005079 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005080 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005081 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005082 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005083 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005084 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005085
Aaron Huang9fe47be2021-06-08 13:11:45 +08005086 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5087 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5088 // not called by the rematch in this case. This is because the code above unset
5089 // this network from the default request's satisfier, and that is what the rematch
5090 // is using as its source data to know what the old satisfier was. So as far as the
5091 // rematch above is concerned, the old default network was null.
5092 // Therefore if there is no new default, the default network was null and is still
5093 // null, thus there was no change so makeDefault() is not called. So if the old
5094 // network had a proxy and there is no new default, the proxy tracker should be told
5095 // that there is no longer a default proxy.
5096 // Strictly speaking this is not essential because having a proxy setting when
5097 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5098 mProxyTracker.setDefaultProxy(null);
5099 }
5100
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005101 // Immediate teardown.
5102 if (nai.teardownDelayMs == 0) {
5103 destroyNetwork(nai);
5104 return;
5105 }
5106
5107 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005108 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305109 try {
5110 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5111 } catch (RemoteException e) {
5112 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5113 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005114 }
5115 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5116 }
5117
5118 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005119 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005120 // Tell netd to clean up the configuration for this network
5121 // (routing rules, DNS, etc).
5122 // This may be slow as it requires a lot of netd shelling out to ip and
5123 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005124 // after we've rematched networks with requests (which might change the default
5125 // network or service a new request from an app), so network traffic isn't interrupted
5126 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005127 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005128 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005129 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005130 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5131 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5132 // false if the network was never created.
5133 // TODO: delete when S is no longer supported.
5134 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005135 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005136 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005137 }
5138
Chalard Jean1e4c2182023-10-06 18:45:53 +09005139 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005140 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005141 // Step 1 : maybe this network was the upstream for one or more local networks.
5142 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5143 if (!local.isLocalNetwork()) continue;
5144 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5145 if (null == selector) continue;
5146 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5147 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5148 // called after removing all associated NRIs from mNetworkRequests.
5149 if (null == nri) continue;
5150 final NetworkAgentInfo satisfier = nri.getSatisfier();
5151 if (disconnecting != satisfier) continue;
5152 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005153 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5154 // correctly contains null as an upstream.
5155 if (sendCallbacks) {
5156 nri.setSatisfier(null, null);
5157 notifyNetworkCallbacks(local,
5158 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5159 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005160 }
5161
5162 // Step 2 : maybe this is a local network that had an upstream.
5163 if (!disconnecting.isLocalNetwork()) return;
5164 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5165 if (null == selector) return;
5166 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5167 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5168 // is called after removing all associated NRIs from mNetworkRequests.
5169 if (null == nri) return;
5170 final NetworkAgentInfo satisfier = nri.getSatisfier();
5171 if (null == satisfier) return;
5172 removeLocalNetworkUpstream(disconnecting, satisfier);
5173 }
5174
5175 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5176 @NonNull final NetworkAgentInfo upstream) {
5177 try {
5178 mRoutingCoordinatorService.removeInterfaceForward(
5179 localAgent.linkProperties.getInterfaceName(),
5180 upstream.linkProperties.getInterfaceName());
5181 } catch (RemoteException e) {
5182 loge("Couldn't remove interface forward for "
5183 + localAgent.linkProperties.getInterfaceName() + " to "
5184 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5185 }
5186 }
5187
Ken Chen6df7a902021-04-09 15:08:42 +08005188 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005189 try {
5190 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005191 final NativeNetworkConfig config;
5192 if (nai.isVPN()) {
5193 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005194 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005195 return false;
5196 }
5197 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5198 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005199 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005200 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005201 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005202 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005203 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5204 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005205 getNetworkPermission(nai.networkCapabilities),
5206 false /* secure */,
5207 VpnManager.TYPE_VPN_NONE,
5208 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005209 }
Ken Chen6df7a902021-04-09 15:08:42 +08005210 mNetd.networkCreate(config);
5211 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005212 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5213 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005214 return true;
5215 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005216 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005217 return false;
5218 }
5219 }
5220
Ken Chen6df7a902021-04-09 15:08:42 +08005221 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005222 if (mDscpPolicyTracker != null) {
5223 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5224 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005225 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005226 // the interface is going to go away. Don't send the callbacks however ; if the network
5227 // was is being disconnected the callbacks have already been sent, and if it is being
5228 // destroyed pending replacement they will be sent when it is disconnected.
5229 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005230 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005231 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005232 } catch (RemoteException | ServiceSpecificException e) {
5233 loge("Exception destroying network(networkDestroy): " + e);
5234 }
5235 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005236 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005237 } catch (RemoteException | ServiceSpecificException e) {
5238 loge("Exception destroying network: " + e);
5239 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005240 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5241 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5242 // gets created, could add data to DnsManager data structures that will never get deleted.
5243 mDnsManager.removeNetwork(nai.network);
5244
5245 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005246 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005247 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5248 }
5249
Chalard Jean254bd162022-08-25 13:04:51 +09005250 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005251 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005252 }
5253
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005254 // If this method proves to be too slow then we can maintain a separate
5255 // pendingIntent => NetworkRequestInfo map.
5256 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5257 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005258 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5259 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5260 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005261 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005262 return entry.getValue();
5263 }
5264 }
5265 return null;
5266 }
5267
Chalard Jean524f0b12021-10-25 21:11:56 +09005268 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005269 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005270 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5271 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5272 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5273 // bug is fixed.
5274 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005275 throw new IllegalStateException("This NRI is already registered. New : " + nri
5276 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005277 }
5278 }
5279 }
5280 }
5281
Chalard Jeanac9ace02022-01-26 16:54:05 +09005282 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5283 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005284 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09005285 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09005286 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005287 }
5288 return false;
5289 }
5290
James Mattisf7027322020-12-13 16:28:14 -08005291 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005292 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005293 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5294 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5295 final NetworkRequestInfo existingRequest =
5296 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005297 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005298 if (DBG) {
5299 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5300 + nri.mRequests.get(0) + " because their intents matched.");
5301 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005302 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005303 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005304 }
Erik Kline05f2b402015-04-30 12:58:40 +09005305 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005306 }
5307
James Mattisf7027322020-12-13 16:28:14 -08005308 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005309 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005310 }
5311
James Mattis3ce3d3c2021-02-09 18:18:28 -08005312 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005313 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005314 for (final NetworkRequestInfo nri : nris) {
5315 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005316 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005317 for (final NetworkRequest req : nri.mRequests) {
5318 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005319 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005320 if (req.isListen()) {
5321 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5322 if (req.networkCapabilities.hasSignalStrength()
5323 && network.satisfiesImmutableCapabilitiesOf(req)) {
5324 updateSignalStrengthThresholds(network, "REGISTER", req);
5325 }
James Mattisf7027322020-12-13 16:28:14 -08005326 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005327 }
5328 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005329
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005330 // If this NRI has a satisfier already, it is replacing an older request that
5331 // has been removed. Track it.
5332 final NetworkRequest activeRequest = nri.getActiveRequest();
5333 if (null != activeRequest) {
5334 // If there is an active request, then for sure there is a satisfier.
5335 nri.getSatisfier().addRequest(activeRequest);
5336 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005337 }
James Mattisf7027322020-12-13 16:28:14 -08005338
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005339 if (mFlags.noRematchAllRequestsOnRegister()) {
5340 rematchNetworksAndRequests(nris);
5341 } else {
5342 rematchAllNetworksAndRequests();
5343 }
James Mattis45d81842021-01-10 14:24:24 -08005344
Chalard Jean0354d8c2021-01-12 10:58:56 +09005345 // Requests that have not been matched to a network will not have been sent to the
5346 // providers, because the old satisfier and the new satisfier are the same (null in this
5347 // case). Send these requests to the providers.
5348 for (final NetworkRequestInfo nri : nris) {
5349 for (final NetworkOfferInfo noi : mNetworkOffers) {
5350 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005351 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005352 }
5353 }
5354
James Mattisf7027322020-12-13 16:28:14 -08005355 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5356 final int callingUid) {
5357 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005358 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005359 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5360 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5361 handleReleaseNetworkRequest(
5362 nri.mRequests.get(0),
5363 callingUid,
5364 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005365 }
5366 }
5367
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005368 // Determines whether the network is the best (or could become the best, if it validated), for
5369 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5370 // on the value of reason:
5371 //
5372 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5373 // then it should be torn down.
5374 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5375 // then it should be lingered.
5376 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005377 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005378
Chalard Jean254bd162022-08-25 13:04:51 +09005379 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005380 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5381 return false;
5382 }
5383
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005384 final int numRequests;
5385 switch (reason) {
5386 case TEARDOWN:
5387 numRequests = nai.numRequestNetworkRequests();
5388 break;
5389 case LINGER:
5390 numRequests = nai.numForegroundNetworkRequests();
5391 break;
5392 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005393 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005394 return true;
5395 }
5396
Chalard Jean947acd42021-03-08 22:29:27 +09005397 if (numRequests > 0) return false;
5398
Paul Jensende49eb12015-06-25 15:30:08 -04005399 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005400 if (reason == UnneededFor.LINGER
5401 && !nri.isMultilayerRequest()
5402 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005403 // Background requests don't affect lingering.
5404 continue;
5405 }
5406
James Mattis3d229892020-11-16 16:46:28 -08005407 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005408 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005409 }
5410 }
Paul Jensende49eb12015-06-25 15:30:08 -04005411 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005412 }
5413
James Mattis3d229892020-11-16 16:46:28 -08005414 private boolean isNetworkPotentialSatisfier(
5415 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005416 // While destroyed network sometimes satisfy requests (including occasionally newly
5417 // satisfying requests), *potential* satisfiers are networks that might beat a current
5418 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5419 // because it's never a good idea to keep a destroyed network in case it validates.
5420 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5421 // candidate after it's been replaced by another unvalidated network.
5422 if (candidate.isDestroyed()) return false;
5423 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005424 // request, return immediately. For multilayer requests, check to see if any of the
5425 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005426 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5427 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005428 return false;
5429 }
5430 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005431 // This multilayer listen request is satisfied therefore no further requests need to be
5432 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005433 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005434 return false;
5435 }
James Mattis3d229892020-11-16 16:46:28 -08005436 // As non-multilayer listen requests have already returned, the below would only happen
5437 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005438 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005439 continue;
5440 }
Chalard Jean80685f42023-10-30 18:31:27 +09005441 // If there is hope for this network might validate and subsequently become the best
5442 // network for that request, then it is needed. Note that this network can't already
5443 // be the best for this request, or it would be the current satisfier, and therefore
5444 // there would be no need to call this method to find out if it is a *potential*
5445 // satisfier ("unneeded", the only caller, only calls this if this network currently
5446 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005447 if (candidate.satisfies(req)) {
5448 // As soon as a network is found that satisfies a request, return. Specifically for
5449 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5450 // is important so as to not evaluate lower priority requests further in
5451 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005452 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5453 ? nri.getSatisfier() : null;
5454 // Note that this catches two important cases:
5455 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5456 // is currently satisfying the request. This is desirable when
5457 // cellular ends up validating but WiFi does not.
5458 // 2. Unvalidated WiFi will not be reaped when validated cellular
5459 // is currently satisfying the request. This is desirable when
5460 // WiFi ends up validating and out scoring cellular.
5461 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005462 }
5463 }
5464
5465 return false;
5466 }
5467
Erik Kline0c04b742016-07-07 16:50:58 +09005468 private NetworkRequestInfo getNriForAppRequest(
5469 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005470 // Looking up the app passed param request in mRequests isn't possible since it may return
5471 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5472 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005473 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5474 // to avoid potential race conditions when validating a package->uid mapping when sending
5475 // the callback on the very low-chance that an application shuts down prior to the callback
5476 // being sent.
5477 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5478 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005479
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005480 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005481 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005482 log(String.format("UID %d attempted to %s for unowned request %s",
5483 callingUid, requestedOperation, nri));
5484 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005485 }
Erik Kline0c04b742016-07-07 16:50:58 +09005486 }
5487
5488 return nri;
5489 }
5490
James Mattisf7027322020-12-13 16:28:14 -08005491 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5492 final String callingMethod) {
5493 if (nri.isMultilayerRequest()) {
5494 throw new IllegalStateException(
5495 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005496 }
5497 }
5498
James Mattisf7027322020-12-13 16:28:14 -08005499 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005500 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005501 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5502 // single NetworkRequest and thus does not apply to multilayer requests.
5503 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5504 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005505 return;
5506 }
James Mattis2516da32021-01-31 17:06:19 -08005507 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005508 return;
5509 }
James Mattisf7027322020-12-13 16:28:14 -08005510 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5511 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005512 }
5513 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005514 callCallbackForRequest(
5515 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005516 }
5517
James Mattisf7027322020-12-13 16:28:14 -08005518 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5519 final int callingUid,
5520 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005521 final NetworkRequestInfo nri =
5522 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5523 if (nri == null) {
5524 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005525 }
James Mattisf7027322020-12-13 16:28:14 -08005526 if (VDBG || (DBG && request.isRequest())) {
5527 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005528 }
5529 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005530 if (callOnUnavailable) {
5531 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5532 }
Erik Kline155a59a2015-11-25 12:49:38 +09005533 }
Erik Kline0c04b742016-07-07 16:50:58 +09005534
James Mattisa076c532020-12-02 14:12:41 -08005535 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005536 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005537 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005538 if (null == mNetworkRequests.remove(req)) {
5539 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5540 continue;
5541 }
James Mattisa076c532020-12-02 14:12:41 -08005542 if (req.isListen()) {
5543 removeListenRequestFromNetworks(req);
5544 }
5545 }
James Mattis8f036802021-06-20 16:26:01 -07005546 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005547 if (mDefaultNetworkRequests.remove(nri)) {
5548 // If this request was one of the defaults, then the UID rules need to be updated
5549 // WARNING : if the app(s) for which this network request is the default are doing
5550 // traffic, this will kill their connected sockets, even if an equivalent request
5551 // is going to be reinstated right away ; unconnected traffic will go on the default
5552 // until the new default is set, which will happen very soon.
5553 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5554 // remove ranges for those requests that won't have a replacement
5555 final NetworkAgentInfo satisfier = nri.getSatisfier();
5556 if (null != satisfier) {
5557 try {
paulhu0e79d952021-06-09 16:11:35 +08005558 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5559 satisfier.network.getNetId(),
5560 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005561 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005562 } catch (RemoteException e) {
5563 loge("Exception setting network preference default network", e);
5564 }
5565 }
5566 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005567
Junyu Lai00d92df2022-07-05 11:01:52 +08005568 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005569 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005570 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005571
5572 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005573 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005574 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005575 }
5576 }
5577
Chalard Jean0354d8c2021-01-12 10:58:56 +09005578 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5579 // needed for this offer.
5580 for (final NetworkOfferInfo noi : mNetworkOffers) {
5581 for (final NetworkRequest req : nri.mRequests) {
5582 if (req.isRequest() && noi.offer.neededFor(req)) {
5583 noi.offer.onNetworkUnneeded(req);
5584 }
5585 }
5586 }
James Mattisa076c532020-12-02 14:12:41 -08005587 }
5588
James Mattis3ce3d3c2021-02-09 18:18:28 -08005589 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5590 for (final NetworkRequestInfo nri : nris) {
5591 if (mDefaultRequest == nri) {
5592 // Make sure we never remove the default request.
5593 continue;
5594 }
5595 handleRemoveNetworkRequest(nri);
5596 }
5597 }
5598
James Mattisa076c532020-12-02 14:12:41 -08005599 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5600 // listens don't have a singular affected Network. Check all networks to see
5601 // if this listen request applies and remove it.
5602 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5603 nai.removeRequest(req.requestId);
5604 if (req.networkCapabilities.hasSignalStrength()
5605 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5606 updateSignalStrengthThresholds(nai, "RELEASE", req);
5607 }
5608 }
5609 }
5610
5611 /**
5612 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5613 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5614 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5615 */
5616 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5617 boolean wasKept = false;
5618 final NetworkAgentInfo nai = nri.getSatisfier();
5619 if (nai != null) {
5620 final int requestLegacyType = nri.getActiveRequest().legacyType;
5621 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5622 nai.removeRequest(nri.getActiveRequest().requestId);
5623 if (VDBG || DDBG) {
5624 log(" Removing from current network " + nai.toShortString()
5625 + ", leaving " + nai.numNetworkRequests() + " requests.");
5626 }
5627 // If there are still lingered requests on this network, don't tear it down,
5628 // but resume lingering instead.
5629 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005630 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005631 notifyNetworkLosing(nai, now);
5632 }
5633 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5634 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5635 teardownUnneededNetwork(nai);
5636 } else {
5637 wasKept = true;
5638 }
James Mattisa076c532020-12-02 14:12:41 -08005639 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5640 // Went from foreground to background.
5641 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005642 }
5643
Erik Kline0c04b742016-07-07 16:50:58 +09005644 // Maintain the illusion. When this request arrived, we might have pretended
5645 // that a network connected to serve it, even though the network was already
5646 // connected. Now that this request has gone away, we might have to pretend
5647 // that the network disconnected. LegacyTypeTracker will generate that
5648 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005649 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005650 boolean doRemove = true;
5651 if (wasKept) {
5652 // check if any of the remaining requests for this network are for the
5653 // same legacy type - if so, don't remove the nai
5654 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5655 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005656 if (otherRequest.legacyType == requestLegacyType
5657 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005658 if (DBG) log(" still have other legacy request - leaving");
5659 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005660 }
5661 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005662 }
5663
Erik Kline0c04b742016-07-07 16:50:58 +09005664 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005665 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005666 }
5667 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005668 }
5669 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005670
Junyu Lai00d92df2022-07-05 11:01:52 +08005671 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005672 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005673 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5674 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5675 }
5676
Lorenzo Colittid6459092016-07-04 12:55:44 +09005677 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005678 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005679 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005680 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005681 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005682 }
5683
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005684 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005685 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5686 enforceNetworkStackSettingsOrSetup();
5687 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5688 encodeBool(accept), encodeBool(always), network));
5689 }
5690
5691 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005692 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005693 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005694 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5695 }
5696
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005697 @Override
5698 public void setTestAllowBadWifiUntil(long timeMs) {
5699 enforceSettingsPermission();
5700 if (!Build.isDebuggable()) {
5701 throw new IllegalStateException("Does not support in non-debuggable build");
5702 }
5703
5704 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5705 throw new IllegalArgumentException("It should not exceed "
5706 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5707 }
5708
5709 mHandler.sendMessage(
5710 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5711 }
5712
chiachangwange0192a72023-02-06 13:25:01 +00005713 @Override
5714 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5715 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005716
5717 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5718 throw new IllegalArgumentException("Argument should not exceed "
5719 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5720 }
5721
5722 mHandler.sendMessage(
5723 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5724 }
5725
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005726 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5727 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5728 " accept=" + accept + " always=" + always);
5729
5730 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5731 if (nai == null) {
5732 // Nothing to do.
5733 return;
5734 }
5735
Chalard Jean254bd162022-08-25 13:04:51 +09005736 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005737 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005738 return;
5739 }
5740
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005741 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005742 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005743 }
5744
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005745 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5746 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005747 // If network becomes partial connectivity and user already accepted to use this
5748 // network, we should respect the user's option and don't need to popup the
5749 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005750 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005751 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005752 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005753 }
5754
5755 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005756 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005757 }
5758
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005759 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005760 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005761 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005762 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005763 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005764 }
5765
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005766 }
5767
lucaslin2240ef62019-03-12 13:08:03 +08005768 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5769 boolean always) {
5770 if (DBG) {
5771 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5772 + " always=" + always);
5773 }
5774
5775 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5776 if (nai == null) {
5777 // Nothing to do.
5778 return;
5779 }
5780
Chalard Jean254bd162022-08-25 13:04:51 +09005781 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005782 // The network validated while the dialog box was up. Take no action.
5783 return;
5784 }
5785
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005786 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5787 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005788 }
5789
5790 // TODO: Use the current design or save the user choice into IpMemoryStore.
5791 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005792 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005793 }
5794
5795 if (!accept) {
5796 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005797 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005798 // Tear down the network.
5799 teardownUnneededNetwork(nai);
5800 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005801 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5802 // result in a partial connectivity result which will be processed by
5803 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005804 //
5805 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5806 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005807 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005808 }
5809 }
5810
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005811 private void handleSetAvoidUnvalidated(Network network) {
5812 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005813 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005814 // Nothing to do. The network either disconnected or revalidated.
5815 return;
5816 }
Chalard Jean254bd162022-08-25 13:04:51 +09005817 if (0L == nai.getAvoidUnvalidated()) {
5818 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005819 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005820 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005821 }
5822 }
5823
Chalard Jean5fb43c72022-09-08 19:03:14 +09005824 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005825 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005826 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005827 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005828 }
5829
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005830 @Override
5831 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005832 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005833 mHandler.post(() -> {
5834 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5835 if (nai == null) return;
5836 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005837 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005838 });
5839 }
5840
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005841 /**
5842 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5843 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005844 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005845 * @param appExtras Bundle to use as intent extras for the captive portal application.
5846 * Must be treated as opaque to avoid preventing the captive portal app to
5847 * update its arguments.
5848 */
5849 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005850 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005851 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5852 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005853
5854 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5855 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005856 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5857 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005858 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5859
lucaslin75ff7022020-12-17 04:14:35 +08005860 final long token = Binder.clearCallingIdentity();
5861 try {
5862 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5863 } finally {
5864 Binder.restoreCallingIdentity(token);
5865 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005866 }
5867
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005868 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5869 private final Network mNetwork;
5870
5871 private CaptivePortalImpl(Network network) {
5872 mNetwork = network;
5873 }
5874
5875 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005876 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005877 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5878 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005879 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5880 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5881 // Since the network will be disconnected, skip notifying NetworkMonitor
5882 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005883 }
5884
Chiachang Wang938bfba2020-01-09 13:50:55 +08005885 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005886 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005887 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005888 }
5889
5890 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005891 public void appRequest(final int request) {
5892 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5893 if (nm == null) return;
5894
5895 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005896 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005897 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005898 }
5899 }
5900
5901 @Nullable
5902 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5903 // getNetworkAgentInfoForNetwork is thread-safe
5904 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5905 if (nai == null) return null;
5906
5907 // nai.networkMonitor() is thread-safe
5908 return nai.networkMonitor();
5909 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005910 }
5911
Hugo Benichic9048bc2016-09-14 23:23:08 +00005912 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005913 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005914 }
5915
Chalard Jean020b93a2022-09-01 13:20:14 +09005916 private boolean activelyPreferBadWifi() {
5917 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5918 }
5919
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005920 /**
5921 * Return whether the device should maintain continuous, working connectivity by switching away
5922 * from WiFi networks having no connectivity.
5923 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5924 */
5925 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005926 if (!checkNetworkStackPermission()) {
5927 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5928 }
5929 return avoidBadWifi();
5930 }
5931
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005932 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005933 ensureRunningOnConnectivityServiceThread();
5934 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005935 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005936 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005937 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005938 if (avoidBadWifi) {
5939 // If the device is now avoiding bad wifi, remove notifications that might have
5940 // been put up when the device didn't.
5941 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5942 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005943 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005944 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5945 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5946 for (final NetworkOfferInfo noi : offersToUpdate) {
5947 updateOfferScore(noi.offer);
5948 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005949 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005950 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005951 }
5952
Erik Kline95ecfee2016-10-02 18:02:14 +09005953 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005954 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005955 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005956 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005957 if (!configRestrict) {
5958 pw.println("Bad Wi-Fi avoidance: unrestricted");
5959 return;
5960 }
5961
5962 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5963 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005964 pw.println("Config restrict: " + configRestrict);
5965 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005966
Chalard Jeane0fdea32022-09-14 21:44:22 +09005967 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005968 String description;
5969 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005970 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005971 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005972 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005973 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005974 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005975 description = "avoid";
5976 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005977 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005978 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005979 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005980
5981 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5982 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005983 if (null == configValue) {
5984 description = "unset";
5985 } else if (configValue) {
5986 description = "force true";
5987 } else {
5988 description = "force false";
5989 }
5990 pw.println("Actively prefer bad wifi conf: " + description);
5991 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005992 pw.println("Network overrides:");
5993 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005994 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005995 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005996 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005997 }
5998 }
5999 pw.decreaseIndent();
6000 pw.decreaseIndent();
6001 }
6002
paulhu7746e4e2020-06-09 19:07:03 +08006003 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
6004 // unify the method.
6005 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
6006 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
6007 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
6008 return settingsComponent != null
6009 ? settingsComponent.getPackageName() : "com.android.settings";
6010 }
6011
lucaslinb1e8e382019-01-24 15:55:30 +08006012 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006013 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006014 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006015 switch (type) {
6016 case NO_INTERNET:
6017 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006018 // High priority because it is only displayed for explicitly selected networks.
6019 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006020 break;
lucasline117e2e2019-10-22 18:27:33 +08006021 case PRIVATE_DNS_BROKEN:
6022 action = Settings.ACTION_WIRELESS_SETTINGS;
6023 // High priority because we should let user know why there is no internet.
6024 highPriority = true;
6025 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006026 case LOST_INTERNET:
6027 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006028 // High priority because it could help the user avoid unexpected data usage.
6029 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006030 break;
lucaslin2240ef62019-03-12 13:08:03 +08006031 case PARTIAL_CONNECTIVITY:
6032 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006033 // Don't bother the user with a high-priority notification if the network was not
6034 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006035 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006036 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006037 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006038 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006039 return;
6040 }
6041
6042 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006043 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006044 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006045 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006046 // Some OEMs have their own Settings package. Thus, need to get the current using
6047 // Settings package name instead of just use default name "com.android.settings".
6048 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6049 intent.setClassName(settingsPkgName,
6050 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006051 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006052
paulhu2af50222020-10-11 22:52:27 +08006053 PendingIntent pendingIntent = PendingIntent.getActivity(
6054 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006055 0 /* requestCode */,
6056 intent,
paulhu2af50222020-10-11 22:52:27 +08006057 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006058
Serik Beketayevec8ad212020-12-07 22:43:07 -08006059 mNotifier.showNotification(
6060 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006061 }
6062
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006063 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6064 // Don't prompt if the network is validated, and don't prompt on captive portals
6065 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006066 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006067 return false;
6068 }
6069
6070 // If a network has partial connectivity, always prompt unless the user has already accepted
6071 // partial connectivity and selected don't ask again. This ensures that if the device
6072 // automatically connects to a network that has partial Internet access, the user will
6073 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006074 // because we have prompted them.
6075 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006076 return true;
6077 }
6078
6079 // If a network has no Internet access, only prompt if the network was explicitly selected
6080 // and if the user has not already told us to use the network regardless of whether it
6081 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006082 if (nai.networkAgentConfig.explicitlySelected
6083 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006084 return true;
6085 }
6086
6087 return false;
6088 }
6089
Chalard Jean5fb43c72022-09-08 19:03:14 +09006090 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6091 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006092
Chalard Jean5fb43c72022-09-08 19:03:14 +09006093 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6094 if (null == nai) return;
6095
6096 if (nai.setEvaluated()) {
6097 // If setEvaluated() returned true, the network never had any form of connectivity.
6098 // This may have an impact on request matching if bad WiFi avoidance is off and the
6099 // network was found not to have Internet access.
6100 nai.updateScoreForNetworkAgentUpdate();
6101 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006102
6103 // Also, if this is WiFi and it should be preferred actively, now is the time to
6104 // prompt the user that they walked past and connected to a bad WiFi.
6105 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6106 && !avoidBadWifi()
6107 && activelyPreferBadWifi()) {
6108 // The notification will be removed if the network validates or disconnects.
6109 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6110 return;
6111 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006112 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006113
Chalard Jean5fb43c72022-09-08 19:03:14 +09006114 if (!shouldPromptUnvalidated(nai)) return;
6115
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006116 // Stop automatically reconnecting to this network in the future. Automatically connecting
6117 // to a network that provides no or limited connectivity is not useful, because the user
6118 // cannot use that network except through the notification shown by this method, and the
6119 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006120 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006121
Chalard Jean254bd162022-08-25 13:04:51 +09006122 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006123 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006124 } else {
6125 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6126 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006127 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006128
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006129 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6130 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006131 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006132
lucaslin2240ef62019-03-12 13:08:03 +08006133 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6134 return;
6135 }
6136
6137 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006138 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006139 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006140 }
6141
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006142 @Override
6143 public int getMultipathPreference(Network network) {
6144 enforceAccessPermission();
6145
6146 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006147 if (nai != null && nai.networkCapabilities
6148 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006149 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6150 }
6151
Aaron Huang9a57acf2020-12-08 10:03:29 +08006152 final NetworkPolicyManager netPolicyManager =
6153 mContext.getSystemService(NetworkPolicyManager.class);
6154
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006155 final long token = Binder.clearCallingIdentity();
6156 final int networkPreference;
6157 try {
6158 networkPreference = netPolicyManager.getMultipathPreference(network);
6159 } finally {
6160 Binder.restoreCallingIdentity(token);
6161 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006162 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006163 return networkPreference;
6164 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006165 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6166 }
6167
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006168 @Override
6169 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006170 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006171 }
6172
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006173 private class InternalHandler extends Handler {
6174 public InternalHandler(Looper looper) {
6175 super(looper);
6176 }
6177
6178 @Override
6179 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006180 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006181 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006182 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006183 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006184 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006185 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006186 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006187 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006188 break;
6189 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006190 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006191 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006192 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006193 break;
6194 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006195 case EVENT_REGISTER_NETWORK_PROVIDER: {
6196 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006197 break;
6198 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006199 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6200 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006201 break;
6202 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006203 case EVENT_REGISTER_NETWORK_OFFER: {
6204 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6205 break;
6206 }
6207 case EVENT_UNREGISTER_NETWORK_OFFER: {
6208 final NetworkOfferInfo offer =
6209 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6210 if (null != offer) {
6211 handleUnregisterNetworkOffer(offer);
6212 }
6213 break;
6214 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006215 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006216 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6217 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6218 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006219 break;
6220 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006221 case EVENT_REGISTER_NETWORK_REQUEST:
6222 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006223 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006224 break;
6225 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006226 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6227 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006228 handleRegisterNetworkRequestWithIntent(msg);
6229 break;
6230 }
Erik Kline155a59a2015-11-25 12:49:38 +09006231 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6232 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6233 handleTimedOutNetworkRequest(nri);
6234 break;
6235 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006236 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6237 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6238 break;
6239 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006240 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006241 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6242 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006243 break;
6244 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006245 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006246 Network network = (Network) msg.obj;
6247 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006248 break;
6249 }
lucaslin2240ef62019-03-12 13:08:03 +08006250 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6251 Network network = (Network) msg.obj;
6252 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6253 toBool(msg.arg2));
6254 break;
6255 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006256 case EVENT_SET_AVOID_UNVALIDATED: {
6257 handleSetAvoidUnvalidated((Network) msg.obj);
6258 break;
6259 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006260 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6261 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006262 break;
6263 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006264 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6265 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006266 break;
6267 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006268 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6269 // handler thread.
6270 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006271 mKeepaliveTracker.handleStartKeepalive(msg);
6272 break;
6273 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006274 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006275 final AutomaticOnOffKeepalive ki =
6276 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6277 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006278
chiachangwang676c84e2023-02-14 09:22:05 +00006279 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006280 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006281 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006282 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006283 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6284 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006285 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6286 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006287 }
6288 }
6289
6290 // If the network no longer exists, then the keepalive should have been
6291 // cleaned up already. There is no point trying to resume keepalives.
6292 if (!networkFound) return;
6293
chiachangwang676c84e2023-02-14 09:22:05 +00006294 if (underpinnedNetworkFound) {
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006295 final NetworkCapabilities underpinnedNc =
6296 getNetworkCapabilitiesInternal(underpinnedNetwork);
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006297 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006298 underpinnedNetwork.netId, underpinnedNc.getUids());
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006299 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006300 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006301 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006302 }
6303 break;
6304 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006305 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006306 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006307 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6308 (IBinder) msg.obj);
6309 if (ki == null) {
6310 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006311 return;
6312 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006313 final int reason = msg.arg2;
6314 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006315 break;
6316 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006317 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6318 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6319 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006320 break;
6321 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006322 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6323 handlePrivateDnsSettingsChanged();
6324 break;
dalyk1720e542018-03-05 12:42:22 -05006325 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6326 handlePrivateDnsValidationUpdate(
6327 (PrivateDnsValidationUpdate) msg.obj);
6328 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006329 case EVENT_UID_BLOCKED_REASON_CHANGED:
6330 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006331 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006332 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6333 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6334 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006335 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006336 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6337 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006338 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006339 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006340 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006341 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006342 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6343 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006344 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006345 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006346 }
lucaslin1193a5d2021-01-21 02:04:15 +08006347 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006348 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006349 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006350 break;
paulhu51f77dc2021-06-07 02:34:20 +00006351 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6352 handleMobileDataPreferredUidsChanged();
6353 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006354 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6355 final long timeMs = ((Long) msg.obj).longValue();
6356 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6357 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006358 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6359 handleIngressRateLimitChanged();
6360 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006361 case EVENT_USER_DOES_NOT_WANT:
6362 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6363 if (nai == null) break;
6364 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006365 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006366 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006367 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6368 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6369 break;
chiachangwange0192a72023-02-06 13:25:01 +00006370 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6371 final long time = ((Long) msg.obj).longValue();
6372 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6373 break;
6374 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006375 case EVENT_UID_FROZEN_STATE_CHANGED:
6376 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6377 handleFrozenUids(args.mUids, args.mFrozenStates);
6378 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006379 }
6380 }
6381 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006382
Lorenzo Colittid6459092016-07-04 12:55:44 +09006383 @Override
markchien5776f962019-12-16 20:15:20 +08006384 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006385 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006386 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006387 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6388 Context.TETHERING_SERVICE);
6389 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006390 }
6391
Lorenzo Colittid6459092016-07-04 12:55:44 +09006392 @Override
markchien5776f962019-12-16 20:15:20 +08006393 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006394 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006395 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006396 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6397 Context.TETHERING_SERVICE);
6398 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006399 }
6400
Lorenzo Colittid6459092016-07-04 12:55:44 +09006401 @Override
markchien5776f962019-12-16 20:15:20 +08006402 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006403 public String[] getTetheredIfaces() {
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.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006408 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006409
markchien5776f962019-12-16 20:15:20 +08006410
Lorenzo Colittid6459092016-07-04 12:55:44 +09006411 @Override
markchien5776f962019-12-16 20:15:20 +08006412 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006413 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006414 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006415 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6416 Context.TETHERING_SERVICE);
6417
6418 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006419 }
6420
Lorenzo Colittid6459092016-07-04 12:55:44 +09006421 @Override
markchien5776f962019-12-16 20:15:20 +08006422 @Deprecated
6423 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006424 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006425 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6426 Context.TETHERING_SERVICE);
6427
6428 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006429 }
6430
Udam Saini8f7d6a72017-06-07 12:06:28 -07006431 @Override
markchien5776f962019-12-16 20:15:20 +08006432 @Deprecated
6433 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006434 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006435 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6436 Context.TETHERING_SERVICE);
6437 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006438 }
6439
Robert Greenwalte0b00512014-07-02 09:59:16 -07006440 // Called when we lose the default network and have no replacement yet.
6441 // This will automatically be cleared after X seconds or a new default network
6442 // becomes CONNECTED, whichever happens first. The timer is started by the
6443 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006444 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006445 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006446 if (mNetTransitionWakeLock.isHeld()) {
6447 return;
6448 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006449 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006450 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6451 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006452 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006453 mWakelockLogs.log("ACQUIRE for " + forWhom);
6454 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006455 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006456 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006457 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006458 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006459
Hugo Benichi471b62a2017-03-30 23:18:10 +09006460 // Called when we gain a new default network to release the network transition wakelock in a
6461 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6462 // message is cancelled.
6463 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006464 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006465 if (!mNetTransitionWakeLock.isHeld()) {
6466 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006467 }
6468 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006469 // Cancel self timeout on wakelock hold.
6470 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6471 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6472 mHandler.sendMessageDelayed(msg, 1000);
6473 }
6474
6475 // Called when either message of ensureNetworkTransitionWakelock or
6476 // scheduleReleaseNetworkTransitionWakelock is processed.
6477 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6478 String event = eventName(eventId);
6479 synchronized (this) {
6480 if (!mNetTransitionWakeLock.isHeld()) {
6481 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006482 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006483 return;
6484 }
6485 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006486 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6487 mTotalWakelockDurationMs += lockDuration;
6488 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6489 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006490 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006491 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006492 }
6493
Robert Greenwalt986c7412010-09-08 15:24:47 -07006494 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006495 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006496 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006497 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006498 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006499 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006500 }
6501
Lorenzo Colittid6459092016-07-04 12:55:44 +09006502 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006503 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006504 enforceAccessPermission();
6505 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006506 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006507 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006508
6509 final NetworkAgentInfo nai;
6510 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006511 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006512 } else {
6513 nai = getNetworkAgentInfoForNetwork(network);
6514 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006515
6516 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006517 mHandler.obtainMessage(
6518 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006519 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006520
Hugo Benichid6b510a2017-04-06 17:22:18 +09006521 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006522 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006523 if (nai == null
6524 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006525 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006526 return;
6527 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006528 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006529 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006530 mConnectivityDiagnosticsHandler.sendMessage(
6531 mConnectivityDiagnosticsHandler.obtainMessage(
6532 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6533 new ReportedNetworkConnectivityInfo(
6534 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006535 return;
6536 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006537 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006538 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006539 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006540 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006541 // Validating a network that has not yet connected could result in a call to
6542 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006543 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006544 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006545 }
paulhu7aeba372020-12-30 00:42:19 +08006546 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6547 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006548 return;
6549 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006550
6551 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6552 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6553 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6554 // completed.
6555 mConnectivityDiagnosticsHandler.sendMessage(
6556 mConnectivityDiagnosticsHandler.obtainMessage(
6557 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6558 new ReportedNetworkConnectivityInfo(
6559 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006560 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006561 }
6562
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006563 // TODO: call into netd.
6564 private boolean queryUserAccess(int uid, Network network) {
6565 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6566 if (nai == null) return false;
6567
6568 // Any UID can use its default network.
6569 if (nai == getDefaultNetworkForUid(uid)) return true;
6570
6571 // Privileged apps can use any network.
6572 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6573 return true;
6574 }
6575
6576 // An unprivileged UID can use a VPN iff the VPN applies to it.
6577 if (nai.isVPN()) {
6578 return nai.networkCapabilities.appliesToUid(uid);
6579 }
6580
6581 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6582 // sockets, i.e., if it is the owner.
6583 final NetworkAgentInfo vpn = getVpnForUid(uid);
6584 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6585 && uid != vpn.networkCapabilities.getOwnerUid()) {
6586 return false;
6587 }
6588
6589 // The UID's permission must be at least sufficient for the network. Since the restricted
6590 // permission was already checked above, that just leaves background networks.
6591 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6592 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6593 }
6594
6595 // Unrestricted network. Anyone gets to use it.
6596 return true;
6597 }
6598
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006599 /**
6600 * Returns information about the proxy a certain network is using. If given a null network, it
6601 * it will return the proxy for the bound network for the caller app or the default proxy if
6602 * none.
6603 *
6604 * @param network the network we want to get the proxy information for.
6605 * @return Proxy information if a network has a proxy configured, or otherwise null.
6606 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006607 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006608 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006609 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006610 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006611 if (network == null) {
6612 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006613 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006614 true);
6615 if (activeNetwork == null) {
6616 return null;
6617 }
6618 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006619 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006620 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6621 // caller may not have.
6622 return getLinkPropertiesProxyInfo(network);
6623 }
6624 // No proxy info available if the calling UID does not have network access.
6625 return null;
6626 }
6627
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006628
6629 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006630 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6631 if (nai == null) return null;
6632 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006633 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6634 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006635 }
6636 }
6637
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006638 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006639 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006640 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006641 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006642 }
6643
Chalard Jean777e2e52018-06-07 18:02:37 +09006644 @Override
6645 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006646 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006647 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006648 }
6649
Aaron Huang9fe47be2021-06-08 13:11:45 +08006650 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006651 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006652 final NetworkAgentInfo nai = getDefaultNetwork();
6653 // TODO : this method should check that net == nai.network, unfortunately at this point
6654 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6655 // is only ever installed on the default network so in practice this is okay.
6656 if (null == nai) return;
6657 // PAC proxies only work on the default network. Therefore, only the default network
6658 // should have its link properties fixed up for PAC proxies.
6659 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6660 if (nai.everConnected()) {
6661 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6662 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006663 }
6664
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006665 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6666 // when any network changes proxy.
6667 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6668 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006669 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6670 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006671 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6672
Chalard Jean7d97afc2018-06-07 17:41:29 +09006673 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006674 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006675 }
6676 }
6677
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006678 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006679 final private HashMap<Uri, Integer> mUriEventMap;
6680 final private Context mContext;
6681 final private Handler mHandler;
6682
6683 SettingsObserver(Context context, Handler handler) {
6684 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006685 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006686 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006687 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006688 }
6689
Erik Kline05f2b402015-04-30 12:58:40 +09006690 void observe(Uri uri, int what) {
6691 mUriEventMap.put(uri, what);
6692 final ContentResolver resolver = mContext.getContentResolver();
6693 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006694 }
6695
6696 @Override
6697 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006698 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006699 }
6700
6701 @Override
6702 public void onChange(boolean selfChange, Uri uri) {
6703 final Integer what = mUriEventMap.get(uri);
6704 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006705 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006706 } else {
6707 loge("No matching event to send for URI=" + uri);
6708 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006709 }
6710 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006711
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006712 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006713 Log.d(TAG, s);
6714 }
6715
6716 private static void logw(String s) {
6717 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006718 }
6719
Daniel Brightf9e945b2020-06-15 16:10:01 -07006720 private static void logwtf(String s) {
6721 Log.wtf(TAG, s);
6722 }
6723
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006724 private static void logwtf(String s, Throwable t) {
6725 Log.wtf(TAG, s, t);
6726 }
6727
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006728 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006729 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006730 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006731
Hugo Benichi39621362017-02-11 17:04:43 +09006732 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006733 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006734 }
6735
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006736 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006737 * Return the information of all ongoing VPNs.
6738 *
6739 * <p>This method is used to update NetworkStatsService.
6740 *
6741 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006742 */
junyulai2050bed2021-01-23 09:46:34 +08006743 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006744 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006745 if (mLockdownEnabled) {
6746 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006747 }
junyulai2050bed2021-01-23 09:46:34 +08006748 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006749 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006750 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006751 if (info != null) {
6752 infoList.add(info);
6753 }
6754 }
junyulai2050bed2021-01-23 09:46:34 +08006755 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006756 }
6757
6758 /**
6759 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006760 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006761 */
junyulai2050bed2021-01-23 09:46:34 +08006762 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006763 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006764 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6765 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006766 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6767 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6768 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006769 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6770 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006771 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006772 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006773 }
6774 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006775
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006776 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006777
6778 List<String> interfaces = new ArrayList<>();
6779 for (Network network : underlyingNetworks) {
6780 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6781 if (underlyingNai == null) continue;
6782 LinkProperties lp = underlyingNai.linkProperties;
6783 for (String iface : lp.getAllInterfaceNames()) {
6784 if (!TextUtils.isEmpty(iface)) {
6785 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006786 }
6787 }
Benedict Wong34857f82019-06-12 17:46:15 +00006788 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006789
6790 if (interfaces.isEmpty()) return null;
6791
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006792 // Must be non-null or NetworkStatsService will crash.
6793 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6794 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006795 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006796 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006797
junyulai2050bed2021-01-23 09:46:34 +08006798 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6799 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006800 }
6801
James Mattisd31bdfa2020-12-23 16:37:26 -08006802 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006803 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6804 Network[] underlyingNetworks) {
6805 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006806 if (underlyingNetworks == null && defaultNetwork != null) {
6807 // null underlying networks means to track the default.
6808 underlyingNetworks = new Network[] { defaultNetwork };
6809 }
6810 return underlyingNetworks;
6811 }
6812
6813 // Returns true iff |network| is an underlying network of |nai|.
6814 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6815 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6816 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006817 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006818 final Network[] underlying = underlyingNetworksOrDefault(
6819 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006820 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006821 }
6822
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006823 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006824 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006825 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006826 * When underlying networks change, such networks may have to update capabilities to reflect
6827 * things like the metered bit, their transports, and so on. The capabilities are calculated
6828 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006829 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006830 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006831 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006832 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006833 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006834 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006835 }
6836 }
6837 }
6838
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006839 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6840 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6841 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6842 // a VPN is not up.
6843 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6844 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6845 for (UidRange range : blockedUidRanges) {
6846 if (range.contains(uid)) return true;
6847 }
6848 return false;
6849 }
6850
6851 @Override
6852 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006853 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006854 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6855 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6856 }
6857
6858 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6859 if (DBG) {
6860 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6861 + Arrays.toString(ranges));
6862 }
6863 // Cannot use a Set since the list of UID ranges might contain duplicates.
6864 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6865 for (int i = 0; i < ranges.length; i++) {
6866 if (requireVpn) {
6867 newVpnBlockedUidRanges.add(ranges[i]);
6868 } else {
6869 newVpnBlockedUidRanges.remove(ranges[i]);
6870 }
6871 }
6872
6873 try {
6874 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6875 } catch (RemoteException | ServiceSpecificException e) {
6876 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6877 + Arrays.toString(ranges) + "): netd command failed: " + e);
6878 }
6879
Chalard Jeandf29a852023-05-29 17:02:43 +09006880 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006881 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6882 }
6883
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006884 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6885 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006886 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6887 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006888 }
6889
6890 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6891 }
6892
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006893 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006894 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006895 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006896 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006897 }
6898
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006899 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6900 return mLockdownEnabled
6901 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6902 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006903 }
6904
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006905 private NetworkAgentInfo getLegacyLockdownNai() {
6906 if (!mLockdownEnabled) {
6907 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006908 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006909 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006910 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6911 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006912
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006913 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006914 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6915 // a local variable. There is no need to make a copy because its contents cannot change.
6916 final Network[] underlying = nai.declaredUnderlyingNetworks;
6917 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006918 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006919 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006920
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006921 // The legacy lockdown VPN always uses the default network.
6922 // If the VPN's underlying network is no longer the current default network, it means that
6923 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006924 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6925 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006926 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006927 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006928 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006929 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006930
6931 return nai;
6932 };
6933
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006934 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6935 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6936 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006937 private DetailedState getLegacyLockdownState(DetailedState origState) {
6938 if (origState != DetailedState.CONNECTED) {
6939 return origState;
6940 }
6941 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6942 ? DetailedState.CONNECTING
6943 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006944 }
6945
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006946 private void filterForLegacyLockdown(NetworkInfo ni) {
6947 if (!mLockdownEnabled || !ni.isConnected()) return;
6948 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6949 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6950 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6951 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6952 // network, this time with a state of CONNECTED.
6953 //
6954 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6955 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6956 // is not too far off the truth, since an always-on VPN, when not connected, is always
6957 // trying to reconnect.
6958 if (getLegacyLockdownNai() == null) {
6959 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6960 }
6961 }
6962
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006963 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006964 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006965 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006966 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006967 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6968 return;
6969 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006970 final long ident = Binder.clearCallingIdentity();
6971 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006972 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006973 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006974 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006975 } finally {
6976 Binder.restoreCallingIdentity(ident);
6977 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006978 }
Wink Savillecb117d32013-08-29 14:57:08 -07006979
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006980 @Override
6981 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006982 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006983 final long ident = Binder.clearCallingIdentity();
6984 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006985 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006986 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006987 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6988 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006989 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006990 } finally {
6991 Binder.restoreCallingIdentity(ident);
6992 }
6993 }
6994
James Mattis02220e22021-03-13 19:27:21 -08006995 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006996 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6997 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6998 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006999 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007000 }
7001
James Mattis02220e22021-03-13 19:27:21 -08007002 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09007003 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007004 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08007005 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
7006 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09007007 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08007008 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7009 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7010 }
junyulaid91e7052020-08-28 13:44:33 +08007011 }
7012
James Mattis02220e22021-03-13 19:27:21 -08007013 private void onPackageChanged(@NonNull final String packageName) {
7014 // This is necessary in case a package is added or removed, but also when it's replaced to
7015 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
7016 // as one in the preferences, then it should follow the same routing as that other package,
7017 // which means updating the rules is never to be needed in this case (whether it joins or
7018 // leaves a UID with a preference).
7019 if (isMappedInOemNetworkPreference(packageName)) {
7020 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7021 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007022
7023 // Invalidates cache entry when the package is updated.
7024 synchronized (mSelfCertifiedCapabilityCache) {
7025 mSelfCertifiedCapabilityCache.remove(packageName);
7026 }
James Mattis02220e22021-03-13 19:27:21 -08007027 }
7028
7029 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007030 @Override
7031 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007032 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007033 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007034 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007035
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007036 // User should be filled for below intents, check the existence.
7037 if (user == null) {
7038 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7039 return;
7040 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007041
Lorenzo Colitticd675292021-02-04 17:32:07 +09007042 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007043 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007044 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007045 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007046 } else {
junyulaid91e7052020-08-28 13:44:33 +08007047 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007048 }
7049 }
7050 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007051
James Mattis02220e22021-03-13 19:27:21 -08007052 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7053 @Override
7054 public void onReceive(Context context, Intent intent) {
7055 ensureRunningOnConnectivityServiceThread();
7056 switch (intent.getAction()) {
7057 case Intent.ACTION_PACKAGE_ADDED:
7058 case Intent.ACTION_PACKAGE_REMOVED:
7059 case Intent.ACTION_PACKAGE_REPLACED:
7060 onPackageChanged(intent.getData().getSchemeSpecificPart());
7061 break;
7062 default:
7063 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7064 }
7065 }
7066 };
7067
Junyu Lai38c75032023-12-04 07:52:19 +00007068 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
7069 private final BroadcastReceiver mDataSaverReceiver = new BroadcastReceiver() {
7070 @Override
7071 public void onReceive(Context context, Intent intent) {
7072 if (mDeps.isAtLeastV()) {
7073 throw new IllegalStateException(
7074 "data saver status should be updated from platform");
7075 }
7076 ensureRunningOnConnectivityServiceThread();
7077 switch (intent.getAction()) {
7078 case ACTION_RESTRICT_BACKGROUND_CHANGED:
7079 // If the uid is present in the deny list, the API will consistently
7080 // return ENABLED. To retrieve the global switch status, the system
7081 // uid is chosen because it will never be included in the deny list.
7082 final int dataSaverForSystemUid =
7083 mPolicyManager.getRestrictBackgroundStatus(Process.SYSTEM_UID);
7084 final boolean isDataSaverEnabled = (dataSaverForSystemUid
7085 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
7086 mBpfNetMaps.setDataSaverEnabled(isDataSaverEnabled);
7087 break;
7088 default:
7089 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7090 }
7091 }
7092 };
7093
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007094 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007095 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007096
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007097 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007098 public final String name;
7099 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007100 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007101 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007102
lifraf3a3492021-03-10 13:58:14 +08007103 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7104 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007105 this.name = name;
7106 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007107 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007108 mDeathRecipient = deathRecipient;
7109
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007110 if (mDeathRecipient == null) {
7111 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007112 }
7113 }
7114
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007115 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007116 try {
7117 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7118 } catch (RemoteException e) {
7119 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007120 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007121 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007122 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007123
James Mattis4fce5d12020-11-12 15:53:42 -08007124 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7125 for (int i = 0; i < requests.size(); i++) {
7126 ensureNetworkRequestHasType(requests.get(i));
7127 }
7128 }
7129
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007130 private void ensureNetworkRequestHasType(NetworkRequest request) {
7131 if (request.type == NetworkRequest.Type.NONE) {
7132 throw new IllegalArgumentException(
7133 "All NetworkRequests in ConnectivityService must have a type");
7134 }
7135 }
7136
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007137 /**
7138 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007139 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007140 */
James Mattis258ea3c2020-11-15 15:04:40 -08007141 @VisibleForTesting
7142 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007143 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7144 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007145 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007146
James Mattisa076c532020-12-02 14:12:41 -08007147 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7148 void setSatisfier(
7149 @Nullable final NetworkAgentInfo satisfier,
7150 @Nullable final NetworkRequest activeRequest) {
7151 mSatisfier = satisfier;
7152 mActiveRequest = activeRequest;
7153 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007154
James Mattisd31bdfa2020-12-23 16:37:26 -08007155 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007156 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007157 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007158 private NetworkAgentInfo mSatisfier;
7159 NetworkAgentInfo getSatisfier() {
7160 return mSatisfier;
7161 }
7162
7163 // The request in mRequests assigned to a network agent. This is null if none of the
7164 // requests in mRequests can be satisfied. This member has the constraint of only being
7165 // accessible on the handler thread.
7166 @Nullable
7167 private NetworkRequest mActiveRequest;
7168 NetworkRequest getActiveRequest() {
7169 return mActiveRequest;
7170 }
7171
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007172 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007173 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007174 @Nullable
7175 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007176
7177 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007178 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007179 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007180 final int mPid;
7181 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007182 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007183 @Nullable
7184 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007185
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007186 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007187 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007188
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007189 // Effective UID of this request. This is different from mUid when a privileged process
7190 // files a request on behalf of another UID. This UID is used to determine blocked status,
7191 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7192 // maximum limit of registered callbacks per UID.
7193 final int mAsUid;
7194
paulhu48291862021-07-14 14:53:57 +08007195 // Preference order of this request.
7196 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007197
James Mattis3ce3d3c2021-02-09 18:18:28 -08007198 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7199 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7200 // maintained for keying off of. This is only a concern when the original nri
7201 // mNetworkRequests changes which happens currently for apps that register callbacks to
7202 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7203 // that match the per-app default nri that currently tracks the calling app's uid so that
7204 // callbacks are fired at the appropriate time. When the callbacks fire,
7205 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7206 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7207 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7208 @NonNull
7209 private final NetworkRequest mNetworkRequestForCallback;
7210 NetworkRequest getNetworkRequestForCallback() {
7211 return mNetworkRequestForCallback;
7212 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007213
James Mattisd31bdfa2020-12-23 16:37:26 -08007214 /**
7215 * Get the list of UIDs this nri applies to.
7216 */
7217 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007218 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007219 // networkCapabilities.getUids() returns a defensive copy.
7220 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007221 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7222 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007223 }
7224
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007225 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7226 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007227 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007228 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007229 }
7230
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007231 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007232 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007233 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007234 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007235 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007236 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007237 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007238 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007239 mBinder = null;
7240 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007241 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007242 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007243 mPerUidCounter = getRequestCounter(this);
7244 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007245 /**
7246 * Location sensitive data not included in pending intent. Only included in
7247 * {@link NetworkCallback}.
7248 */
7249 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007250 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007251 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007252 }
7253
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007254 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007255 @Nullable final IBinder binder,
7256 @NetworkCallback.Flag int callbackFlags,
7257 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007258 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7259 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007260 }
7261
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007262 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007263 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007264 @Nullable final IBinder binder,
7265 @NetworkCallback.Flag int callbackFlags,
7266 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007267 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007268 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007269 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007270 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007271 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007272 mBinder = binder;
7273 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007274 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007275 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007276 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007277 mPerUidCounter = getRequestCounter(this);
7278 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007279 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007280 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007281 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007282 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007283 }
7284
James Mattis3ce3d3c2021-02-09 18:18:28 -08007285 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7286 @NonNull final List<NetworkRequest> r) {
7287 super();
7288 ensureAllNetworkRequestsHaveType(r);
7289 mRequests = initializeRequests(r);
7290 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007291 final NetworkAgentInfo satisfier = nri.getSatisfier();
7292 if (null != satisfier) {
7293 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7294 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007295 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007296 // As this code creates a new NRI with a new set of requests, figure out which of
7297 // the list of requests should be the active request. It is always the first
7298 // request of the list that can be satisfied by the satisfier since the order of
7299 // requests is a priority order.
7300 // Note even in the presence of a satisfier there may not be an active request,
7301 // when the satisfier is the no-service network.
7302 NetworkRequest activeRequest = null;
7303 for (final NetworkRequest candidate : r) {
7304 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7305 activeRequest = candidate;
7306 break;
7307 }
7308 }
7309 setSatisfier(satisfier, activeRequest);
7310 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007311 mMessenger = nri.mMessenger;
7312 mBinder = nri.mBinder;
7313 mPid = nri.mPid;
7314 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007315 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007316 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007317 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007318 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007319 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007320 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007321 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007322 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007323 }
7324
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007325 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007326 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007327 }
7328
paulhue9913722021-05-26 15:19:20 +08007329 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007330 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007331 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007332 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007333 }
7334
James Mattis2516da32021-01-31 17:06:19 -08007335 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7336 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7337 // false.
7338 boolean isBeingSatisfied() {
7339 return (null != mSatisfier && null != mActiveRequest);
7340 }
7341
James Mattis3d229892020-11-16 16:46:28 -08007342 boolean isMultilayerRequest() {
7343 return mRequests.size() > 1;
7344 }
7345
James Mattis45d81842021-01-10 14:24:24 -08007346 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7347 // Creating a defensive copy to prevent the sender from modifying the list being
7348 // reflected in the return value of this method.
7349 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007350 return Collections.unmodifiableList(tempRequests);
7351 }
7352
James Mattisb1392002021-03-31 13:57:52 -07007353 void linkDeathRecipient() {
7354 if (null != mBinder) {
7355 try {
7356 mBinder.linkToDeath(this, 0);
7357 } catch (RemoteException e) {
7358 binderDied();
7359 }
7360 }
7361 }
7362
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007363 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007364 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007365 try {
7366 mBinder.unlinkToDeath(this, 0);
7367 } catch (NoSuchElementException e) {
7368 // Temporary workaround for b/194394697 pending analysis of additional logs
7369 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7370 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007371 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007372 }
7373
paulhu48291862021-07-14 14:53:57 +08007374 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7375 // Compare two preference orders.
7376 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007377 }
7378
paulhu48291862021-07-14 14:53:57 +08007379 int getPreferenceOrderForNetd() {
7380 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7381 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7382 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007383 }
paulhu48291862021-07-14 14:53:57 +08007384 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007385 }
7386
James Mattis4fce5d12020-11-12 15:53:42 -08007387 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007388 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007389 // As an immutable collection, mRequests cannot change by the time the
7390 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7391 // is acceptable. Use handleReleaseNetworkRequest and not directly
7392 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7393 // the app already unregistered the request.
7394 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7395 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007396 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007397
James Mattis4fce5d12020-11-12 15:53:42 -08007398 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007399 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007400 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7401 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007402 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007403 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007404 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007405 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007406 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007407 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007408 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007409 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007410 }
7411
Junyu Lai00d92df2022-07-05 11:01:52 +08007412 // Keep backward compatibility since the ServiceSpecificException is used by
7413 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7414 public static class RequestInfoPerUidCounter extends PerUidCounter {
7415 RequestInfoPerUidCounter(int maxCountPerUid) {
7416 super(maxCountPerUid);
7417 }
7418
7419 @Override
7420 public synchronized void incrementCountOrThrow(int uid) {
7421 try {
7422 super.incrementCountOrThrow(uid);
7423 } catch (IllegalStateException e) {
7424 throw new ServiceSpecificException(
7425 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7426 "Uid " + uid + " exceeded its allotted requests limit");
7427 }
7428 }
7429
7430 @Override
7431 public synchronized void decrementCountOrThrow(int uid) {
7432 throw new UnsupportedOperationException("Use decrementCount instead.");
7433 }
7434
7435 public synchronized void decrementCount(int uid) {
7436 try {
7437 super.decrementCountOrThrow(uid);
7438 } catch (IllegalStateException e) {
7439 logwtf("Exception when decrement per uid request count: ", e);
7440 }
7441 }
7442 }
7443
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007444 // This checks that the passed capabilities either do not request a
7445 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007446 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007447 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007448 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007449 throw new SecurityException("Insufficient permissions to request a specific SSID");
7450 }
paulhu1a407652019-03-22 16:35:06 +08007451
7452 if (nc.hasSignalStrength()
7453 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7454 throw new SecurityException(
7455 "Insufficient permissions to request a specific signal strength");
7456 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007457 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007458
junyulai2217bec2021-04-14 23:33:31 +08007459 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007460 enforceNetworkFactoryPermission();
7461 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007462 }
7463
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007464 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007465 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007466 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007467 // mNetworkRequests may contain the same value multiple times in case of
7468 // multilayer requests. It won't matter in this case because the thresholds
7469 // will then be the same and be deduplicated as they enter the `thresholds` set.
7470 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007471 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7472 for (final NetworkRequest req : nri.mRequests) {
7473 if (req.networkCapabilities.hasSignalStrength()
7474 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7475 thresholds.add(req.networkCapabilities.getSignalStrength());
7476 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007477 }
7478 }
7479 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007480 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007481 }
7482
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007483 private void updateSignalStrengthThresholds(
7484 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007485 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007486
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007487 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007488 String detail;
7489 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7490 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7491 } else {
7492 detail = reason;
7493 }
7494 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007495 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007496 }
7497
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007498 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007499 }
7500
Chalard Jeandd421992021-12-16 23:16:02 +09007501 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007502 if (nc == null) {
7503 return;
7504 }
7505 NetworkSpecifier ns = nc.getNetworkSpecifier();
7506 if (ns == null) {
7507 return;
7508 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007509 if (ns instanceof MatchAllNetworkSpecifier) {
7510 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7511 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007512 }
7513
Chalard Jeandd421992021-12-16 23:16:02 +09007514 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007515 ensureValidNetworkSpecifier(nc);
7516 if (nc.isPrivateDnsBroken()) {
7517 throw new IllegalArgumentException("Can't request broken private DNS");
7518 }
Chalard Jeande665262022-02-25 16:12:12 +09007519 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007520 throw new IllegalArgumentException("Can't request access UIDs");
7521 }
lucasline117e2e2019-10-22 18:27:33 +08007522 }
7523
Chalard Jeandd421992021-12-16 23:16:02 +09007524 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7525 ensureListenableCapabilities(nc);
7526 final String badCapability = nc.describeFirstNonRequestableCapability();
7527 if (badCapability != null) {
7528 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7529 }
7530 }
7531
Chiachang Wang3bc52762021-11-25 14:17:57 +08007532 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7533 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007534 private boolean isTargetSdkAtleast(int version, int callingUid,
7535 @NonNull String callingPackageName) {
7536 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007537 final PackageManager pm =
7538 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007539 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007540 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007541 if (callingVersion < version) return false;
7542 } catch (PackageManager.NameNotFoundException e) { }
7543 return true;
7544 }
7545
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007546 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007547 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007548 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007549 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007550 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007551 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007552 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7553 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007554 throw new SecurityException("Insufficient permissions to specify legacy type");
7555 }
markchienfac84a22020-03-18 21:16:15 +08007556 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007557 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007558 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007559 // Privileged callers can track the default network of another UID by passing in a UID.
7560 if (asUid != Process.INVALID_UID) {
7561 enforceSettingsPermission();
7562 } else {
7563 asUid = callingUid;
7564 }
junyulaiad010792021-01-11 16:53:38 +08007565 final NetworkRequest.Type reqType;
7566 try {
7567 reqType = NetworkRequest.Type.values()[reqTypeInt];
7568 } catch (ArrayIndexOutOfBoundsException e) {
7569 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7570 }
7571 switch (reqType) {
7572 case TRACK_DEFAULT:
7573 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007574 // is unused and will be replaced by ones appropriate for the UID (usually, the
7575 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007576 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007577 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007578 enforceAccessPermission();
7579 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007580 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007581 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007582 networkCapabilities = new NetworkCapabilities(defaultNc);
7583 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007584 case BACKGROUND_REQUEST:
7585 enforceNetworkStackOrSettingsPermission();
7586 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007587 case REQUEST:
7588 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7589 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007590 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007591 // TODO: this is incorrect. We mark the request as metered or not depending on
7592 // the state of the app when the request is filed, but we never change the
7593 // request if the app changes network state. http://b/29964605
7594 enforceMeteredApnPolicy(networkCapabilities);
7595 break;
junyulai1b1c8742021-03-12 20:05:08 +08007596 case LISTEN_FOR_BEST:
7597 enforceAccessPermission();
7598 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7599 break;
junyulaiad010792021-01-11 16:53:38 +08007600 default:
7601 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007602 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007603 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007604 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007605 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007606
junyulai1b1c8742021-03-12 20:05:08 +08007607 // Enforce FOREGROUND if the caller does not have permission to use background network.
7608 if (reqType == LISTEN_FOR_BEST) {
7609 restrictBackgroundRequestForCaller(networkCapabilities);
7610 }
7611
7612 // Set the UID range for this request to the single UID of the requester, unless the
7613 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007614 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7615 // are no visible methods to set the UIDs, an app could use reflection to try and get
7616 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007617 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007618 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7619 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007620
Etan Cohen85000162017-02-05 10:42:27 -08007621 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007622 throw new IllegalArgumentException("Bad timeout specified");
7623 }
Etan Cohen9786d922015-11-18 10:56:15 -08007624
James Mattis3ce3d3c2021-02-09 18:18:28 -08007625 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007626 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007627 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007628 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007629 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007630 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007631
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007632 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7633 // copied from the default request above. (This is necessary to ensure, for example, that
7634 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7635 // changes don't alter request matching.
7636 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7637 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007638 throw new IllegalStateException(
7639 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007640 + networkCapabilities + " vs. " + defaultNc);
7641 }
7642
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007643 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007644 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007645 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007646 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007647 }
7648 return networkRequest;
7649 }
7650
James Mattis3ce3d3c2021-02-09 18:18:28 -08007651 /**
7652 * Return the nri to be used when registering a network request. Specifically, this is used with
7653 * requests registered to track the default request. If there is currently a per-app default
7654 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7655 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007656 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7657 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007658 * @param nr the network request for the nri.
7659 * @param msgr the messenger for the nri.
7660 * @param binder the binder for the nri.
7661 * @param callingAttributionTag the calling attribution tag for the nri.
7662 * @return the nri to register.
7663 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007664 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007665 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007666 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007667 @Nullable String callingAttributionTag) {
7668 final List<NetworkRequest> requests;
7669 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7670 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007671 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007672 } else {
7673 requests = Collections.singletonList(nr);
7674 }
Roshan Pius951c0032020-12-22 15:10:42 -08007675 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007676 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007677 }
7678
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007679 private boolean shouldCheckCapabilitiesDeclaration(
7680 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7681 @NonNull final String callingPackageName) {
7682 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7683 // Only run the check if the change is enabled.
7684 if (!mDeps.isChangeEnabled(
7685 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7686 callingPackageName, user)) {
7687 return false;
7688 }
7689
7690 return networkCapabilities.hasCapability(
7691 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7692 || networkCapabilities.hasCapability(
7693 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7694 }
7695
7696 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007697 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007698 // This check is added to fix the linter error for "current min is 30", which is not going
7699 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007700 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007701 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7702 return;
7703 }
7704 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007705 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007706 try {
7707 synchronized (mSelfCertifiedCapabilityCache) {
7708 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7709 callerPackageName);
7710 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007711 final PackageManager packageManager =
7712 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
7713 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007714 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7715 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7716 callerPackageName
7717 );
7718 final XmlResourceParser parser = packageManager
7719 .getResourcesForApplication(callerPackageName)
7720 .getXml(networkSliceProperty.getResourceId());
7721 applicationNetworkCapabilities =
7722 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7723 mSelfCertifiedCapabilityCache.put(callerPackageName,
7724 applicationNetworkCapabilities);
7725 }
7726
7727 }
7728 } catch (PackageManager.NameNotFoundException ne) {
7729 throw new SecurityException(
7730 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7731 + " property");
7732 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7733 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007734 } finally {
7735 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007736 }
7737
7738 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7739 networkCapabilities);
7740 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007741 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007742 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007743 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7744 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007745 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
7746 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007747 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007748 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007749 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7750 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7751 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7752 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007753 }
junyulai96bd9fe2022-03-08 17:36:42 +08007754 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007755 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007756 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007757 }
7758 }
7759
fenglu3f357402015-03-20 11:29:56 -07007760 @Override
fenglub00f4882015-04-21 17:12:05 -07007761 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007762 enforceAccessPermission();
7763 NetworkAgentInfo nai = null;
7764 if (network == null) {
7765 return false;
7766 }
7767 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007768 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007769 }
7770 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007771 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007772 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007773 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007774 Integer uidReqs = mBandwidthRequests.get(uid);
7775 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007776 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007777 }
7778 mBandwidthRequests.put(uid, ++uidReqs);
7779 }
fenglu3f357402015-03-20 11:29:56 -07007780 return true;
7781 }
7782 return false;
7783 }
7784
Felipe Leme0a5ae422016-06-20 16:36:29 -07007785 private boolean isSystem(int uid) {
7786 return uid < Process.FIRST_APPLICATION_UID;
7787 }
fenglu3f357402015-03-20 11:29:56 -07007788
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007789 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007790 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007791 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007792 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007793 return;
7794 }
Hugo Benichi39621362017-02-11 17:04:43 +09007795 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7796 // Policy already enforced.
7797 return;
7798 }
paulhuaf50d7d2020-12-24 19:47:34 +08007799 final long ident = Binder.clearCallingIdentity();
7800 try {
7801 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7802 // If UID is restricted, don't allow them to bring up metered APNs.
7803 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7804 }
7805 } finally {
7806 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007807 }
7808 }
7809
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007810 @Override
7811 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007812 PendingIntent operation, @NonNull String callingPackageName,
7813 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007814 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007815 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007816 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007817 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007818 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007819 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007820 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007821 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007822 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007823 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7824 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007825
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007826 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007827 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007828 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7829 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007830 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007831 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7832 nri));
7833 return networkRequest;
7834 }
7835
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007836 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7837 mHandler.sendMessageDelayed(
7838 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007839 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007840 }
7841
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007842 @Override
7843 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007844 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007845 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007846 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007847 }
7848
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007849 // In order to implement the compatibility measure for pre-M apps that call
7850 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7851 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7852 // This ensures it has permission to do so.
7853 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7854 if (nc == null) {
7855 return false;
7856 }
7857 int[] transportTypes = nc.getTransportTypes();
7858 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7859 return false;
7860 }
7861 try {
7862 mContext.enforceCallingOrSelfPermission(
7863 android.Manifest.permission.ACCESS_WIFI_STATE,
7864 "ConnectivityService");
7865 } catch (SecurityException e) {
7866 return false;
7867 }
7868 return true;
7869 }
7870
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007871 @Override
7872 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007873 Messenger messenger, IBinder binder,
7874 @NetworkCallback.Flag int callbackFlags,
7875 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007876 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007877 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7878 enforceAccessPermission();
7879 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007880
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007881 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007882 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007883 Binder.getCallingPid(), callingUid, callingPackageName);
7884 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007885 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7886 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7887 // onLost and onAvailable callbacks when networks move in and out of the background.
7888 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7889 // can't request networks.
7890 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007891 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007892
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007893 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007894 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007895 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007896 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007897 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007898 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007899
7900 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7901 return networkRequest;
7902 }
7903
7904 @Override
7905 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007906 PendingIntent operation, @NonNull String callingPackageName,
7907 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007908 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007909 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007910 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7911 enforceAccessPermission();
7912 }
Chalard Jeandd421992021-12-16 23:16:02 +09007913 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007914 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007915 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007916 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007917 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007918
7919 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007920 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007921 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7922 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007923 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007924
WeiZhang1cc3f172021-06-03 19:02:04 -05007925 mHandler.sendMessage(mHandler.obtainMessage(
7926 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007927 }
7928
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007929 /** Returns the next Network provider ID. */
7930 public final int nextNetworkProviderId() {
7931 return mNextNetworkProviderId.getAndIncrement();
7932 }
7933
Erik Kline0c04b742016-07-07 16:50:58 +09007934 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007935 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007936 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007937 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007938 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007939 }
7940
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007941 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7942 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007943 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7944 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7945 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007946 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007947 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007948 return;
7949 }
7950
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007951 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7952 mNetworkProviderInfos.put(npi.messenger, npi);
7953 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007954 }
7955
7956 @Override
7957 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007958 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007959 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007960 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007961 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007962 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7963 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007964 }
7965
7966 @Override
7967 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007968 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007969 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007970 }
7971
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007972 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007973 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007974 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7975 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007976 Objects.requireNonNull(score);
7977 Objects.requireNonNull(caps);
7978 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007979 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007980 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007981 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7982 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007983 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7984 }
7985
Chalard Jeanbb902a52021-08-18 01:35:19 +09007986 private void updateOfferScore(final NetworkOffer offer) {
7987 final boolean yieldToBadWiFi =
7988 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7989 final NetworkOffer newOffer = new NetworkOffer(
7990 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7991 offer.caps, offer.callback, offer.providerId);
7992 if (offer.equals(newOffer)) return;
7993 handleRegisterNetworkOffer(newOffer);
7994 }
7995
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007996 @Override
7997 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007998 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007999 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
8000 }
8001
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008002 private void handleUnregisterNetworkProvider(Messenger messenger) {
8003 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
8004 if (npi == null) {
8005 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008006 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008007 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008008 // Unregister all the offers from this provider
8009 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
8010 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09008011 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008012 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
8013 toRemove.add(noi);
8014 }
8015 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09008016 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008017 handleUnregisterNetworkOffer(noi);
8018 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008019 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07008020 }
8021
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008022 @Override
James Mattisf7027322020-12-13 16:28:14 -08008023 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008024 if (request.hasTransport(TRANSPORT_TEST)) {
8025 enforceNetworkFactoryOrTestNetworksPermission();
8026 } else {
8027 enforceNetworkFactoryPermission();
8028 }
James Mattisf7027322020-12-13 16:28:14 -08008029 final NetworkRequestInfo nri = mNetworkRequests.get(request);
8030 if (nri != null) {
8031 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
8032 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
8033 mHandler.post(() -> handleReleaseNetworkRequest(
8034 nri.mRequests.get(0), mDeps.getCallingUid(), true));
8035 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008036 }
8037
Paul Jensen1f567382015-02-13 14:18:39 -05008038 // NOTE: Accessed on multiple threads, must be synchronized on itself.
8039 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008040 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05008041 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008042 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05008043 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008044 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008045
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008046 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05008047 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008048 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008049
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008050 // UID ranges for users that are currently blocked by VPNs.
8051 // This array is accessed and iterated on multiple threads without holding locks, so its
8052 // contents must never be mutated. When the ranges change, the array is replaced with a new one
8053 // (on the handler thread).
8054 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
8055
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008056 // Must only be accessed on the handler thread
8057 @NonNull
8058 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8059
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008060 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008061 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008062
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008063 // Current OEM network preferences. This object must only be written to on the handler thread.
8064 // Since it is immutable and always non-null, other threads may read it if they only care
8065 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008066 @NonNull
8067 private OemNetworkPreferences mOemNetworkPreferences =
8068 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008069 // Current per-profile network preferences. This object follows the same threading rules as
8070 // the OEM network preferences above.
8071 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008072 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8073 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008074
lucaslin3ba7cc22022-12-19 02:35:33 +00008075 // Current VPN network preferences. This object follows the same threading rules as the OEM
8076 // network preferences above.
8077 @NonNull
8078 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8079 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8080
paulhu51f77dc2021-06-07 02:34:20 +00008081 // A set of UIDs that should use mobile data preferentially if available. This object follows
8082 // the same threading rules as the OEM network preferences above.
8083 @NonNull
8084 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8085
James Mattiscb1e0362021-04-06 17:07:42 -07008086 // OemNetworkPreferences activity String log entries.
8087 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8088 @NonNull
8089 private final LocalLog mOemNetworkPreferencesLogs =
8090 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8091
James Mattis02220e22021-03-13 19:27:21 -08008092 /**
8093 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8094 * @param packageName the package name to check existence of a mapping for.
8095 * @return true if a mapping exists, false otherwise
8096 */
8097 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8098 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8099 }
8100
James Mattise3ef1912020-12-20 11:09:58 -08008101 // The always-on request for an Internet-capable network that apps without a specific default
8102 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008103 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008104 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008105 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008106 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008107 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008108 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008109 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008110
James Mattisd31bdfa2020-12-23 16:37:26 -08008111 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8112 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8113 }
8114
8115 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008116 * Return the default network request currently tracking the given uid.
8117 * @param uid the uid to check.
8118 * @return the NetworkRequestInfo tracking the given uid.
8119 */
8120 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008121 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008122 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008123 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008124 // Checking the first request is sufficient as only multilayer requests will have more
8125 // than one request and for multilayer, all requests will track the same uids.
8126 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008127 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008128 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008129 highestPriorityNri = nri;
8130 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008131 }
8132 }
paulhuaa0743d2021-05-26 21:56:03 +08008133 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008134 }
8135
8136 /**
8137 * Get a copy of the network requests of the default request that is currently tracking the
8138 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008139 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8140 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008141 * @param requestorUid the uid to check the default for.
8142 * @param requestorPackageName the requestor's package name.
8143 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8144 */
8145 @NonNull
8146 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008147 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008148 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008149 getDefaultRequestTrackingUid(asUid).mRequests,
8150 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008151 }
8152
8153 /**
8154 * Copy the given nri's NetworkRequest collection.
8155 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008156 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8157 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008158 * @param requestorUid the uid to set on the copied collection.
8159 * @param requestorPackageName the package name to set on the copied collection.
8160 * @return the copied NetworkRequest collection.
8161 */
8162 @NonNull
8163 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008164 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8165 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008166 final List<NetworkRequest> requests = new ArrayList<>();
8167 for (final NetworkRequest nr : requestsToCopy) {
8168 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008169 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008170 nr.legacyType, nextNetworkRequestId(), nr.type));
8171 }
8172 return requests;
8173 }
8174
8175 @NonNull
8176 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008177 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8178 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008179 // These capabilities are for a TRACK_DEFAULT callback, so:
8180 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8181 // mDefaultRequest and a per-UID default request.
8182 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008183 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008184 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008185 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8186 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008187 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008188 restrictRequestUidsForCallerAndSetRequestorInfo(
8189 netCap, requestorUid, requestorPackageName);
8190 return netCap;
8191 }
8192
8193 /**
8194 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8195 * @param nr the network request to check for equality against.
8196 * @return the nri if one exists, null otherwise.
8197 */
8198 @Nullable
8199 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8200 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8201 if (nri.getNetworkRequestForCallback().equals(nr)) {
8202 return nri;
8203 }
8204 }
8205 return null;
8206 }
8207
8208 /**
8209 * Check if an nri is currently being managed by per-app default networking.
8210 * @param nri the nri to check.
8211 * @return true if this nri is currently being managed by per-app default networking.
8212 */
8213 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8214 // nri.mRequests.get(0) is only different from the original request filed in
8215 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8216 // functionality therefore if these two don't match, it means this particular nri is
8217 // currently being managed by a per-app default.
8218 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8219 }
8220
8221 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008222 * Determine if an nri is a managed default request that disallows default networking.
8223 * @param nri the request to evaluate
8224 * @return true if device-default networking is disallowed
8225 */
8226 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8227 // Check if this nri is a managed default that supports the default network at its
8228 // lowest priority request.
8229 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8230 final NetworkCapabilities lowestPriorityNetCap =
8231 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8232 return isPerAppDefaultRequest(nri)
8233 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8234 lowestPriorityNetCap));
8235 }
8236
Erik Kline05f2b402015-04-30 12:58:40 +09008237 // Request used to optionally keep mobile data active even when higher
8238 // priority networks like Wi-Fi are active.
8239 private final NetworkRequest mDefaultMobileDataRequest;
8240
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008241 // Request used to optionally keep wifi data active even when higher
8242 // priority networks like ethernet are active.
8243 private final NetworkRequest mDefaultWifiRequest;
8244
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008245 // Request used to optionally keep vehicle internal network always active
8246 private final NetworkRequest mDefaultVehicleRequest;
8247
James Mattisd31bdfa2020-12-23 16:37:26 -08008248 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8249 // network with no service. This NAI should never be matched against, nor should any public API
8250 // ever return the associated network. For this reason, this NAI is not in the list of available
8251 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8252 // default requests that don't support using the device default network which will ultimately
8253 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8254 @VisibleForTesting
8255 final NetworkAgentInfo mNoServiceNetwork;
8256
Chalard Jean5b409c72021-02-04 13:12:59 +09008257 // The NetworkAgentInfo currently satisfying the default request, if any.
8258 private NetworkAgentInfo getDefaultNetwork() {
8259 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008260 }
8261
James Mattis2516da32021-01-31 17:06:19 -08008262 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008263 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008264 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8265 // Currently, all network requests will have the same uids therefore checking the first
8266 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008267 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008268 if (null == uids) {
8269 continue;
8270 }
8271 for (final UidRange range : uids) {
8272 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008273 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008274 highestPriorityNri = nri;
8275 }
James Mattis2516da32021-01-31 17:06:19 -08008276 }
8277 }
8278 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008279 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008280 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008281 }
8282
Varun Ananddf569952019-02-06 10:13:38 -08008283 @Nullable
8284 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8285 return nai != null ? nai.network : null;
8286 }
8287
8288 private void ensureRunningOnConnectivityServiceThread() {
8289 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8290 throw new IllegalStateException(
8291 "Not running on ConnectivityService thread: "
8292 + Thread.currentThread().getName());
8293 }
8294 }
8295
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008296 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008297 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8298 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008299 }
8300
Chalard Jean29d06db2018-05-02 21:14:54 +09008301 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008302 * Returns whether local agents are supported on this device.
8303 *
8304 * Local agents are supported from U on TVs, and from V on all devices.
8305 */
8306 @VisibleForTesting
8307 public boolean areLocalAgentsSupported() {
8308 final PackageManager pm = mContext.getPackageManager();
8309 // Local agents are supported starting on U on TVs and on V on everything else.
8310 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8311 }
8312
8313 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008314 * Register a new agent with ConnectivityService to handle a network.
8315 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008316 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008317 * @param networkInfo the initial info associated with this network. It can be updated later :
8318 * see {@link #updateNetworkInfo}.
8319 * @param linkProperties the initial link properties of this network. They can be updated
8320 * later : see {@link #updateLinkProperties}.
8321 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008322 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008323 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008324 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008325 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008326 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008327 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008328 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008329 public Network registerNetworkAgent(INetworkAgent na,
8330 NetworkInfo networkInfo,
8331 LinkProperties linkProperties,
8332 NetworkCapabilities networkCapabilities,
8333 @NonNull NetworkScore initialScore,
8334 @Nullable LocalNetworkConfig localNetworkConfig,
8335 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008336 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008337 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8338 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8339 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008340 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008341 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008342 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008343 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008344 } else {
8345 enforceNetworkFactoryPermission();
8346 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008347 final boolean hasLocalCap =
8348 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8349 if (hasLocalCap && !areLocalAgentsSupported()) {
8350 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8351 throw new IllegalArgumentException("Local agents are not supported in this version");
8352 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008353 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8354 if (hasLocalCap != hasLocalNetworkConfig) {
8355 throw new IllegalArgumentException(null != localNetworkConfig
8356 ? "Only local network agents can have a LocalNetworkConfig"
8357 : "Local network agents must have a LocalNetworkConfig"
8358 );
8359 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008360
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008361 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008362 final long token = Binder.clearCallingIdentity();
8363 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008364 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008365 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8366 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008367 } finally {
8368 Binder.restoreCallingIdentity(token);
8369 }
8370 }
8371
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008372 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008373 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008374 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8375 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008376 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008377
Chalard Jeandbc46952022-02-02 00:14:18 +09008378 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8379 // and mutate them at any time.
8380 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8381 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8382 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008383 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008384
Chalard Jean366c5252022-01-25 18:27:53 +09008385 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008386 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008387 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8388 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008389 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008390 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008391 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8392 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8393 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008394
Chalard Jeandbc46952022-02-02 00:14:18 +09008395 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008396 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008397 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008398 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008399 mDeps.getNetworkStack().makeNetworkMonitor(
8400 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008401 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8402 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008403 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008404 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008405 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008406 }
8407
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008408 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008409 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008410 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008411 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008412 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008413 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8414 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8415 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008416
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008417 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008418
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008419 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008420 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008421 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008422 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008423
8424 try {
8425 networkMonitor.start();
8426 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008427 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008428 }
Chalard Jean366c5252022-01-25 18:27:53 +09008429
Chalard Jean1e4c2182023-10-06 18:45:53 +09008430 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008431 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008432 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008433 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008434 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008435 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008436 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008437 }
8438
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008439 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8440 @NonNull public final NetworkOffer offer;
8441
8442 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8443 this.offer = offer;
8444 }
8445
8446 @Override
8447 public void binderDied() {
8448 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8449 }
8450 }
8451
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008452 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8453 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8454 if (npi.providerId == providerId) return true;
8455 }
8456 return false;
8457 }
8458
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008459 /**
8460 * Register or update a network offer.
8461 * @param newOffer The new offer. If the callback member is the same as an existing
8462 * offer, it is an update of that offer.
8463 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008464 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008465 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8466 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008467 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008468 // This may actually happen if a provider updates its score or registers and then
8469 // immediately unregisters. The offer would still be in the handler queue, but the
8470 // provider would have been removed.
8471 if (DBG) log("Received offer from an unregistered provider");
8472 return;
8473 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008474 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8475 if (null != existingOffer) {
8476 handleUnregisterNetworkOffer(existingOffer);
8477 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008478 if (DBG) {
8479 // handleUnregisterNetworkOffer has already logged the old offer
8480 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8481 }
8482 } else {
8483 if (DBG) {
8484 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8485 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008486 }
8487 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8488 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008489 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008490 } catch (RemoteException e) {
8491 noi.binderDied();
8492 return;
8493 }
8494 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008495 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008496 }
8497
8498 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8499 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008500 if (DBG) {
8501 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8502 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008503
8504 // If the provider removes the offer and dies immediately afterwards this
8505 // function may be called twice in a row, but the array will no longer contain
8506 // the offer.
8507 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008508 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008509 }
8510
8511 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8512 @NonNull final INetworkOfferCallback callback) {
8513 ensureRunningOnConnectivityServiceThread();
8514 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008515 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008516 }
8517 return null;
8518 }
8519
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008520 /**
8521 * Called when receiving LinkProperties directly from a NetworkAgent.
8522 * Stores into |nai| any data coming from the agent that might also be written to the network's
8523 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8524 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008525 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008526 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008527 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8528 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008529 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008530 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008531 }
8532
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008533 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008534 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008535 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008536
Lorenzo Colittid523d142020-04-01 20:16:30 +09008537 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8538 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8539 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008540 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008541
Suprabh Shukla1e312032023-01-24 03:36:37 -08008542 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008543
8544 // update filtering rules, need to happen after the interface update so netd knows about the
8545 // new interface (the interface name -> index map becomes initialized)
8546 updateVpnFiltering(newLp, oldLp, networkAgent);
8547
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008548 updateMtu(newLp, oldLp);
8549 // TODO - figure out what to do for clat
8550// for (LinkProperties lp : newLp.getStackedLinks()) {
8551// updateMtu(lp, null);
8552// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008553 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008554 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008555 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8556 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008557
Erik Klineb9888902016-04-05 13:30:49 +09008558 updateRoutes(newLp, oldLp, netId);
8559 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008560 // Make sure LinkProperties represents the latest private DNS status.
8561 // This does not need to be done before updateDnses because the
8562 // LinkProperties are not the source of the private DNS configuration.
8563 // updateDnses will fetch the private DNS configuration from DnsManager.
8564 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008565
Chalard Jean5b409c72021-02-04 13:12:59 +09008566 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008567 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008568 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008569 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008570 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008571
8572 updateWakeOnLan(newLp);
8573
Hai Shalome58bdc62021-01-11 18:45:34 -08008574 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8575 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8576 // does, it needs to be merged here.
8577 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8578 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008579
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008580 // TODO - move this check to cover the whole function
8581 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008582 synchronized (networkAgent) {
8583 networkAgent.linkProperties = newLp;
8584 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008585 // Start or stop DNS64 detection and 464xlat according to network state.
8586 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008587 // Notify NSS when relevant events happened. Currently, NSS only cares about
8588 // interface changed to update clat interfaces accounting.
8589 final boolean interfacesChanged = oldLp == null
8590 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8591 if (interfacesChanged) {
8592 notifyIfacesChangedForNetworkStats();
8593 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008594 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8595 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008596 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008597 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008598
8599 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008600 }
8601
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008602 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8603 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8604 }
8605
Hai Shalome58bdc62021-01-11 18:45:34 -08008606 /**
8607 * @param naData captive portal data from NetworkAgent
8608 * @param apiData captive portal data from capport API
8609 */
8610 @Nullable
8611 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8612 CaptivePortalData apiData) {
8613 if (naData == null || apiData == null) {
8614 return naData == null ? apiData : naData;
8615 }
8616 final CaptivePortalData.Builder captivePortalBuilder =
8617 new CaptivePortalData.Builder(naData);
8618
8619 if (apiData.isCaptive()) {
8620 captivePortalBuilder.setCaptive(true);
8621 }
8622 if (apiData.isSessionExtendable()) {
8623 captivePortalBuilder.setSessionExtendable(true);
8624 }
8625 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8626 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8627 // otherwise data would be inconsistent. Prefer the capport API info if present,
8628 // as it can generally be refreshed more often.
8629 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8630 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8631 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8632 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8633 // No source has time / bytes remaining information: surface the newest refresh time
8634 // for other fields
8635 captivePortalBuilder.setRefreshTime(
8636 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8637 }
8638
Hai Shalom7c6ab402021-02-04 19:34:06 -08008639 // Prioritize the user portal URL from the network agent if the source is authenticated.
8640 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8641 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8642 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8643 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008644 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008645 // Prioritize the venue information URL from the network agent if the source is
8646 // authenticated.
8647 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8648 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8649 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8650 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008651 }
8652 return captivePortalBuilder.build();
8653 }
8654
Suprabh Shukla53e16392023-04-26 18:47:36 -07008655 @VisibleForTesting
8656 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008657 // This needs to be kept in sync and backwards compatible with the decoding logic in
8658 // NetdEventListenerService, which is non-mainline code.
8659 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8660 }
8661
Suprabh Shukla75642282023-04-25 23:15:43 -07008662 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8663 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8664 return true;
8665 }
8666 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8667 return true;
8668 }
8669 return false;
8670 }
8671
Suprabh Shukla1e312032023-01-24 03:36:37 -08008672 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008673 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008674 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008675 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008676 return;
8677 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008678
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008679 // Mask/mark of zero will not detect anything interesting.
8680 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008681 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008682 return;
8683 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008684
Suprabh Shukla1e312032023-01-24 03:36:37 -08008685 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008686 try {
8687 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008688 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008689 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008690 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008691 }
8692 } catch (Exception e) {
8693 loge("Exception modifying wakeup packet monitoring: " + e);
8694 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008695 }
8696
Junyu Lai970963e2022-10-25 15:46:47 +08008697 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008698 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008699 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008700 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008701 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008702 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008703 for (final String iface : interfaceDiff.added) {
8704 try {
8705 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008706 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008707 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008708 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008709 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008710 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008711 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008712 }
Paul Jensenbff73492014-04-28 10:33:11 -04008713 }
8714 }
Chalard Jean9589e722019-11-19 19:03:53 +09008715 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008716 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008717 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008718 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008719 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008720 } catch (Exception e) {
8721 loge("Exception removing interface: " + e);
8722 }
8723 }
8724 }
8725
Paul Jensene0fd4a82014-08-06 15:51:33 -04008726 /**
8727 * Have netd update routes from oldLp to newLp.
8728 * @return true if routes changed between oldLp and newLp
8729 */
Junyu Lai970963e2022-10-25 15:46:47 +08008730 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8731 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008732 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008733 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8734 new CompareOrUpdateResult<>(
8735 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008736 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008737 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008738
8739 // add routes before removing old in case it helps with continuous connectivity
8740
Chalard Jean9dd11612018-06-04 16:52:49 +09008741 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008742 for (RouteInfo route : routeDiff.added) {
8743 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008744 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008745 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008746 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008747 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008748 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008749 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008750 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008751 }
8752 }
8753 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008754 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008755 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008756 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008757 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008758 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008759 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008760 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008761 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008762 }
8763 }
8764
8765 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008766 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008767 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008768 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008769 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008770 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008771 }
8772 }
Tyler Weare4314862019-12-05 14:55:30 -08008773
8774 for (RouteInfo route : routeDiff.updated) {
8775 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8776 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008777 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008778 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008779 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008780 }
8781 }
8782 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8783 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008784 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008785
Junyu Lai970963e2022-10-25 15:46:47 +08008786 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8787 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008788 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8789 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008790 }
Erik Klineb9888902016-04-05 13:30:49 +09008791
Erik Kline31b4a9e2018-01-11 21:07:29 +09008792 if (DBG) {
8793 final Collection<InetAddress> dnses = newLp.getDnsServers();
8794 log("Setting DNS servers for network " + netId + " to " + dnses);
8795 }
Erik Klineb9888902016-04-05 13:30:49 +09008796 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008797 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008798 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008799 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008800 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008801 }
Erik Kline54e35c02017-04-07 15:29:29 +09008802 }
8803
Junyu Lai970963e2022-10-25 15:46:47 +08008804 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8805 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008806 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8807 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008808 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8809 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008810
8811 if (!wasFiltering && !needsFiltering) {
8812 // Nothing to do.
8813 return;
8814 }
8815
8816 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8817 // Nothing changed.
8818 return;
8819 }
8820
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008821 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008822 if (ranges == null || ranges.isEmpty()) {
8823 return;
8824 }
8825
Qingxi Libb8da982020-01-17 17:54:27 -08008826 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008827 // TODO: this create a window of opportunity for apps to receive traffic between the time
8828 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008829 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008830 // old rules are being removed.
8831 if (wasFiltering) {
8832 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8833 }
8834 if (needsFiltering) {
8835 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8836 }
8837 }
8838
Valentin Iftime9fa35092019-09-24 13:32:13 +02008839 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008840 if (mWolSupportedInterfaces == null) {
8841 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008842 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008843 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008844 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8845 }
8846
Luke Huangb913c812018-08-24 20:33:16 +08008847 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008848 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008849 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008850 }
8851 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008852 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008853 }
Luke Huangb913c812018-08-24 20:33:16 +08008854 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008855 }
8856
Chalard Jean62edfd82019-12-02 18:39:29 +09008857 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8858 @NonNull final NetworkCapabilities newNc) {
8859 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8860 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008861 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008862 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008863 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008864 } catch (RemoteException | ServiceSpecificException e) {
8865 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008866 }
8867 }
8868 }
8869
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008870 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008871 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008872 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008873 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008874 underlyingNetworks = underlyingNetworksOrDefault(
8875 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008876 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008877 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8878 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008879 // metered if any underlying is metered, or originally declared metered by the agent.
8880 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008881 boolean roaming = false; // roaming if any underlying is roaming
8882 boolean congested = false; // congested if any underlying is congested
8883 boolean suspended = true; // suspended if all underlying are suspended
8884
8885 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008886 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008887 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008888 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008889 for (Network underlyingNetwork : underlyingNetworks) {
8890 final NetworkAgentInfo underlying =
8891 getNetworkAgentInfoForNetwork(underlyingNetwork);
8892 if (underlying == null) continue;
8893
8894 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8895 hadUnderlyingNetworks = true;
8896 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008897 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008898 }
8899
8900 // Merge capabilities of this underlying network. For bandwidth, assume the
8901 // worst case.
8902 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8903 underlyingCaps.getLinkDownstreamBandwidthKbps());
8904 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8905 underlyingCaps.getLinkUpstreamBandwidthKbps());
8906 // If this underlying network is metered, the VPN is metered (it may cost money
8907 // to send packets on this network).
8908 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8909 // If this underlying network is roaming, the VPN is roaming (the billing structure
8910 // is different than the usual, local one).
8911 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8912 // If this underlying network is congested, the VPN is congested (the current
8913 // condition of the network affects the performance of this network).
8914 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8915 // If this network is not suspended, the VPN is not suspended (the VPN
8916 // is able to transfer some data).
8917 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008918 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008919 }
8920 }
8921 if (!hadUnderlyingNetworks) {
8922 // No idea what the underlying networks are; assume reasonable defaults
8923 metered = true;
8924 roaming = false;
8925 congested = false;
8926 suspended = false;
8927 }
8928
Chalard Jean1d420b32022-10-12 16:39:37 +09008929 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008930 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8931 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8932 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8933 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8934 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8935 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008936 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008937 }
8938
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008939 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008940 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8941 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8942 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008943 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008944 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008945 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008946 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008947 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8948 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008949 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008950 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008951 if (nai.everConnected()
8952 && !nai.isVPN()
8953 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008954 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008955 // does not cause any request (that is not a listen) currently matching that agent to
8956 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008957 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008958 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008959 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008960 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008961 }
8962
Paul Jensen53f08952015-06-16 14:27:36 -04008963 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008964 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008965 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008966 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008967 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008968 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008969 }
Chalard Jean254bd162022-08-25 13:04:51 +09008970 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008971 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008972 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008973 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008974 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008975 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008976 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008977 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008978 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008979 }
Chalard Jean254bd162022-08-25 13:04:51 +09008980 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008981 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8982 } else {
8983 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8984 }
lucasline117e2e2019-10-22 18:27:33 +08008985 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008986
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008987 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008988 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8989 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008990 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008991 }
8992
Lorenzo Colittibd079452021-07-02 11:47:57 +09008993 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008994 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008995 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008996 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008997 }
8998
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008999 return newNc;
9000 }
9001
Lorenzo Colitti44840702021-01-11 22:27:57 +09009002 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
9003 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
9004 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9005 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9006 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9007 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9008 if (prevSuspended != suspended) {
9009 // TODO (b/73132094) : remove this call once the few users of onSuspended and
9010 // onResumed have been removed.
9011 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
9012 : ConnectivityManager.CALLBACK_RESUMED);
9013 }
9014 if (prevSuspended != suspended || prevRoaming != roaming) {
9015 // updateNetworkInfo will mix in the suspended info from the capabilities and
9016 // take appropriate action for the network having possibly changed state.
9017 updateNetworkInfo(nai, nai.networkInfo);
9018 }
9019 }
9020
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009021 /**
9022 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
9023 *
9024 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
9025 * capabilities we manage and store in {@code nai}, such as validated status and captive
9026 * portal status)
9027 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
9028 * potentially triggers rematches.
9029 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
9030 * change.)
9031 *
9032 * @param oldScore score of the network before any of the changes that prompted us
9033 * to call this function.
9034 * @param nai the network having its capabilities updated.
9035 * @param nc the new network capabilities.
9036 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009037 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09009038 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009039 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009040 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09009041 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
9042 if (null != differences) {
9043 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
9044 }
Chalard Jean62edfd82019-12-02 18:39:29 +09009045 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09009046 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009047
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009048 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09009049 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09009050 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009051
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009052 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009053 // If the requestable capabilities haven't changed, and the score hasn't changed, then
9054 // the change we're processing can't affect any requests, it can only affect the listens
9055 // on this network. We might have been called by rematchNetworkAndRequests when a
9056 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09009057 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009058 } else {
9059 // If the requestable capabilities have changed or the score changed, we can't have been
9060 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009061 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009062 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009063 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009064 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009065
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009066 final boolean oldMetered = prevNc.isMetered();
9067 final boolean newMetered = newNc.isMetered();
9068 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009069
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009070 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009071 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9072 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009073 }
junyulaif2c67e42018-08-07 19:50:45 +08009074
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009075 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9076 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009077
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009078 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009079 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009080 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009081 }
9082
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009083 // This network might have been underlying another network. Propagate its capabilities.
9084 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009085
Ken Chen5a35cf92023-10-07 07:54:22 +08009086 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009087 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009088 }
lucaslin53e8a262021-06-08 01:43:59 +08009089
9090 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009091 }
9092
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009093 /** Convenience method to update the capabilities for a given network. */
9094 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009095 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009096 }
9097
Chalard Jean1e4c2182023-10-06 18:45:53 +09009098 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009099 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009100 @Nullable final LocalNetworkConfig oldConfig,
9101 @NonNull final LocalNetworkConfig newConfig) {
9102 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009103 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9104 return;
9105 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009106
Chalard Jean4fe23392023-10-17 23:02:27 +09009107 if (VDBG) {
9108 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9109 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009110 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
9111 // TODO : apply the diff for multicast routing.
9112 configBuilder.setUpstreamMulticastRoutingConfig(
9113 newConfig.getUpstreamMulticastRoutingConfig());
9114 configBuilder.setDownstreamMulticastRoutingConfig(
9115 newConfig.getDownstreamMulticastRoutingConfig());
9116
9117 final NetworkRequest oldRequest =
9118 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9119 final NetworkCapabilities oldCaps =
9120 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9121 final NetworkRequestInfo oldNri =
9122 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9123 final NetworkAgentInfo oldSatisfier =
9124 null == oldNri ? null : oldNri.getSatisfier();
9125 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9126 final NetworkCapabilities newCaps =
9127 (null == newRequest) ? null : newRequest.networkCapabilities;
9128 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9129 if (null != oldRequest && requestUpdated) {
9130 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9131 if (null == newRequest && null != oldSatisfier) {
9132 // If there is an old satisfier, but no new request, then remove the old upstream.
9133 removeLocalNetworkUpstream(nai, oldSatisfier);
9134 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009135 // When there is a new request, the rematch sees the new request and sends the
9136 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9137 // But here there is no new request, so the rematch won't see anything. Send
9138 // callbacks to apps now to tell them about the loss of upstream.
9139 notifyNetworkCallbacks(nai,
9140 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009141 return;
9142 }
9143 }
9144 if (null != newRequest && requestUpdated) {
9145 // File the new request if :
9146 // - it has changed (requestUpdated), or
9147 // - it's the first time this local info (null == oldConfig)
9148 // is updated and the request has not been filed yet.
9149 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9150 // upstream (the best) but never request it to be brought up.
9151 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9152 nextNetworkRequestId(), LISTEN_FOR_BEST);
9153 configBuilder.setUpstreamSelector(nr);
9154 final NetworkRequestInfo nri = new NetworkRequestInfo(
9155 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9156 0 /* callbackFlags */, null /* attributionTag */);
9157 if (null != oldSatisfier) {
9158 // Set the old satisfier in the new NRI so that the rematch will see any changes
9159 nri.setSatisfier(oldSatisfier, nr);
9160 }
9161 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009162 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9163 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9164 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009165 handleRegisterNetworkRequest(nri);
9166 } else {
9167 configBuilder.setUpstreamSelector(oldRequest);
9168 nai.localNetworkConfig = configBuilder.build();
9169 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009170 }
9171
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009172 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009173 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009174 *
9175 * Ingress interface filtering enforces that all apps under the given network can only receive
9176 * packets from the network's interface (and loopback). This is important for VPNs because
9177 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9178 * non-VPN interfaces.
9179 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009180 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009181 * 1. the network is an app VPN (not legacy VPN)
9182 * 2. the VPN does not allow bypass
9183 * 3. the VPN is fully-routed
9184 * 4. the VPN interface is non-null
9185 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009186 * @see INetd#firewallAddUidInterfaceRules
9187 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009188 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009189 @Nullable
9190 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009191 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009192 if (nc == null || lp == null) return null;
9193 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009194 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009195 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009196 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009197 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009198 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009199 && !lp.hasExcludeRoute()) {
9200 return lp.getInterfaceName();
9201 }
9202 return null;
9203 }
9204
9205 /**
9206 * Returns whether we need to set interface filtering rule or not
9207 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009208 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009209 String isolationIface) {
9210 // Allow rules are always needed if VPN isolation is enabled.
9211 if (isolationIface != null) return true;
9212
9213 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9214 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9215 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009216 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009217 }
9218
Chiachang Wang28afaff2020-12-10 22:24:47 +08009219 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9220 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9221 int index = 0;
9222 for (UidRange range : ranges) {
9223 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9224 index++;
9225 }
9226 return stableRanges;
9227 }
9228
Chalard Jeane6c95272022-01-25 21:04:21 +09009229 private static UidRangeParcel[] intsToUidRangeStableParcels(
9230 final @NonNull ArraySet<Integer> uids) {
9231 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9232 int index = 0;
9233 for (int uid : uids) {
9234 stableRanges[index] = new UidRangeParcel(uid, uid);
9235 index++;
9236 }
9237 return stableRanges;
9238 }
9239
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009240 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9241 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9242 for (int i = 0; i < ranges.length; i++) {
9243 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9244 }
9245 return stableRanges;
9246 }
9247
Motomu Utsumi93a22182023-03-16 17:04:21 +09009248 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009249 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009250 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9251 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009252 if (mDeps.isAtLeastU()) {
9253 final Set<Integer> exemptUidSet = new ArraySet<>();
9254 for (final int uid: exemptUids) {
9255 exemptUidSet.add(uid);
9256 }
9257 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9258 } else {
9259 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9260 }
Ken Chen5e65a852020-12-24 12:59:10 +08009261 } catch (Exception e) {
9262 loge("Exception in socket destroy: ", e);
9263 }
9264 }
9265 }
9266
paulhuaa0743d2021-05-26 21:56:03 +08009267 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009268 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009269 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9270 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9271 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009272 exemptUids[0] = VPN_UID;
9273 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009274 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9275
Motomu Utsumi6345e462023-03-13 13:24:50 +09009276 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009277 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009278 try {
9279 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009280 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009281 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009282 } else {
paulhu0e79d952021-06-09 16:11:35 +08009283 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009284 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009285 }
9286 } catch (Exception e) {
9287 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9288 " on netId " + nai.network.netId + ". " + e);
9289 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009290 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009291 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009292 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009293
lucaslin53e8a262021-06-08 01:43:59 +08009294 private boolean isProxySetOnAnyDefaultNetwork() {
9295 ensureRunningOnConnectivityServiceThread();
9296 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9297 final NetworkAgentInfo nai = nri.getSatisfier();
9298 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9299 return true;
9300 }
9301 }
9302 return false;
9303 }
9304
9305 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9306 NetworkCapabilities newNc) {
9307 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9308 // the proxy might be changed since the default network satisfied by the apps might also
9309 // changed.
9310 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9311 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009312 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9313 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009314 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009315 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9316 mProxyTracker.sendProxyBroadcast();
9317 }
9318 }
9319
Chalard Jeane6c95272022-01-25 21:04:21 +09009320 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9321 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009322 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9323 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009324 if (null == prevRanges) prevRanges = new ArraySet<>();
9325 if (null == newRanges) newRanges = new ArraySet<>();
9326 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9327
9328 prevRanges.removeAll(newRanges);
9329 newRanges.removeAll(prevRangesCopy);
9330
9331 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009332 // When updating the VPN uid routing rules, add the new range first then remove the old
9333 // range. If old range were removed first, there would be a window between the old
9334 // range being removed and the new range being added, during which UIDs contained
9335 // in both ranges are not subject to any VPN routing rules. Adding new range before
9336 // removing old range works because, unlike the filtering rules below, it's possible to
9337 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009338 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9339 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9340 // [1-5] & [1-2],[4-5] == [3]
9341 // Then we can do:
9342 // maybeCloseSockets([3])
9343 // mNetd.networkAddUidRanges([1-2],[4-5])
9344 // mNetd.networkRemoveUidRanges([1-5])
9345 // maybeCloseSockets([3])
9346 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9347 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009348 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009349 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009350 }
9351 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009352 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009353 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009354 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9355 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009356 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9357 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009358 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009359 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009360 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9361 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9362 // were added first and then newRanges got removed later, there would be only one uid
9363 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9364 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9365 // Note that this is in contrast with the (more robust) update of VPN routing rules
9366 // above, where the addition of new ranges happens before the removal of old ranges.
9367 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9368 // to be removed will never overlap with the new range to be added.
9369 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009370 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9371 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009372 }
9373 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009374 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009375 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009376 } catch (Exception e) {
9377 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009378 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009379 }
9380 }
9381
Chalard Jeande665262022-02-25 16:12:12 +09009382 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009383 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9384 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009385 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9386 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009387 if (prevEmpty && newEmpty) return;
9388
9389 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009390 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009391 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009392 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009393
9394 if (prevUids.equals(newUids)) return;
9395
9396 // This implementation is very simple and vastly faster for sets of Integers than
9397 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9398 // a key computed from the value and has storage for that.
9399 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9400 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9401 toRemove.removeAll(newUids);
9402 toAdd.removeAll(prevUids);
9403
9404 try {
9405 if (!toAdd.isEmpty()) {
9406 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9407 nai.network.netId,
9408 intsToUidRangeStableParcels(toAdd),
9409 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9410 }
9411 if (!toRemove.isEmpty()) {
9412 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9413 nai.network.netId,
9414 intsToUidRangeStableParcels(toRemove),
9415 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9416 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009417 } catch (ServiceSpecificException e) {
9418 // Has the interface disappeared since the network was built ?
9419 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009420 } catch (RemoteException e) {
9421 // Netd died. This usually causes a runtime restart anyway.
9422 }
9423 }
9424
Junyu Lai2ed7d412022-10-07 16:52:21 +08009425 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9426 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009427 ensureRunningOnConnectivityServiceThread();
9428
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009429 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009430 // Ignore updates for disconnected networks
9431 return;
9432 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009433 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009434 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009435 + "; created=" + nai.getCreatedTime()
9436 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009437 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009438 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9439 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009440 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009441 }
9442
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009443 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9444 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009445 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009446 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009447 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009448 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9449 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9450 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009451 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9452 // need to be sent as a separate extra.
9453 final NetworkRequest req = nri.isMultilayerRequest()
9454 ? nri.getActiveRequest()
9455 // Non-multilayer listen requests do not have an active request
9456 : nri.mRequests.get(0);
9457 if (req == null) {
9458 Log.wtf(TAG, "No request in NRI " + nri);
9459 }
9460 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009461 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009462 sendIntent(nri.mPendingIntent, intent);
9463 }
9464 // else not handled
9465 }
9466
Michael Groover73f69482023-01-27 11:01:25 -06009467 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9468 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009469 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9470 mPendingIntentWakeLock.acquire();
9471 try {
9472 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009473 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009474 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009475 // Explicitly disallow the receiver from starting activities, to prevent apps from
9476 // utilizing the PendingIntent as a backdoor to do this.
9477 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9478 }
9479 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9480 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009481 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009482 } catch (PendingIntent.CanceledException e) {
9483 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9484 mPendingIntentWakeLock.release();
9485 releasePendingNetworkRequest(pendingIntent);
9486 }
9487 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9488 }
9489
9490 @Override
9491 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9492 String resultData, Bundle resultExtras) {
9493 if (DBG) log("Finished sending " + pendingIntent);
9494 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009495 // Release with a delay so the receiving client has an opportunity to put in its
9496 // own request.
9497 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009498 }
9499
Chalard Jean22350c92023-10-07 19:21:45 +09009500 @Nullable
9501 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9502 if (!nai.isLocalNetwork()) return null;
9503 final Network upstream;
9504 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9505 if (null == selector) {
9506 upstream = null;
9507 } else {
9508 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9509 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9510 upstream = (null == satisfier) ? null : satisfier.network;
9511 }
9512 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9513 }
9514
Chalard Jean46bfbf02022-02-02 00:56:25 +09009515 // networkAgent is only allowed to be null if notificationType is
9516 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9517 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009518 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009519 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009520 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009521 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009522 // Default request has no msgr. Also prevents callbacks from being invoked for
9523 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9524 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9525 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009526 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009527 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009528 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009529 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009530 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009531 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009532 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009533 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9534 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009535 }
Roshan Pius951c0032020-12-22 15:10:42 -08009536 final boolean includeLocationSensitiveInfo =
9537 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009538 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009539 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009540 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009541 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009542 networkCapabilitiesRestrictedForCallerPermissions(
9543 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9544 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009545 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009546 nri.mCallingAttributionTag);
9547 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009548 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9549 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009550 // The local network info is often null, so can't use the static putParcelable
9551 // method here.
9552 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9553 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009554 // For this notification, arg1 contains the blocked status.
9555 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009556 break;
9557 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009558 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009559 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009560 break;
9561 }
9562 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009563 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009564 final NetworkCapabilities netCap =
9565 networkCapabilitiesRestrictedForCallerPermissions(
9566 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9567 putParcelable(
9568 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009569 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009570 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009571 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009572 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009573 break;
9574 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009575 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009576 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9577 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009578 break;
9579 }
junyulaif2c67e42018-08-07 19:50:45 +08009580 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009581 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009582 msg.arg1 = arg1;
9583 break;
9584 }
Chalard Jean22350c92023-10-07 19:21:45 +09009585 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9586 if (!networkAgent.isLocalNetwork()) {
9587 Log.wtf(TAG, "Callback for local info for a non-local network");
9588 return;
9589 }
9590 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9591 break;
9592 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009593 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009594 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009595 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009596 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009597 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009598 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009599 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009600 }
James Mattis45d81842021-01-10 14:24:24 -08009601 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009602 } catch (RemoteException e) {
9603 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009604 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009605 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009606 }
9607
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009608 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9609 bundle.putParcelable(t.getClass().getSimpleName(), t);
9610 }
9611
Chalard Jean0702f982021-09-16 21:50:07 +09009612 /**
9613 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9614 *
9615 * When a request should be assigned to a new network, it is normally lingered to give
9616 * time for apps to gracefully migrate their connections. When both networks are on the same
9617 * radio, but that radio can't do time-sharing efficiently, this may end up being
9618 * counter-productive because any traffic on the old network may drastically reduce the
9619 * performance of the new network.
9620 * The stack supports a configuration to let modem vendors state that their radio can't
9621 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9622 * from one cell network to another can't be done gracefully.
9623 *
9624 * @param oldNai the old network serving the request
9625 * @param newNai the new network serving the request
9626 * @return whether the switch can be graceful
9627 */
9628 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9629 @NonNull final NetworkAgentInfo newSatisfier) {
9630 if (mCellularRadioTimesharingCapable) return true;
9631 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9632 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9633 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9634 }
9635
Paul Jensenaf94b982014-09-30 15:37:41 -04009636 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009637 if (nai.numRequestNetworkRequests() != 0) {
9638 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9639 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009640 // Ignore listening and track default requests.
9641 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009642 loge("Dead network still had at least " + nr);
9643 break;
9644 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009645 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009646 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009647 }
9648
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009649 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9650 if (oldNetwork == null) {
9651 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9652 return;
9653 }
Chalard Jean49707572019-12-10 21:07:02 +09009654 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009655
9656 // If we get here it means that the last linger timeout for this network expired. So there
9657 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009658 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009659
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009660 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009661 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009662 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009663 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009664 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009665 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009666 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009667 }
9668
James Mattise3ef1912020-12-20 11:09:58 -08009669 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9670 boolean isDefaultChanged = false;
9671 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9672 final NetworkReassignment.RequestReassignment reassignment =
9673 changes.getReassignment(defaultRequestInfo);
9674 if (null == reassignment) {
9675 continue;
9676 }
9677 // reassignment only contains those instances where the satisfying network changed.
9678 isDefaultChanged = true;
9679 // Notify system services of the new default.
9680 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9681 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009682
James Mattise3ef1912020-12-20 11:09:58 -08009683 if (isDefaultChanged) {
9684 // Hold a wakelock for a short time to help apps in migrating to a new default.
9685 scheduleReleaseNetworkTransitionWakelock();
9686 }
9687 }
9688
Aaron Huang9fe47be2021-06-08 13:11:45 +08009689 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9690 if (null == oldDefaultNetwork) return;
9691 // The network stopped being the default. If it was using a PAC proxy, then the
9692 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9693 // to the local proxy server, which would forward them over the newly default network.
9694 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9695 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9696 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9697 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9698 }
9699
James Mattise3ef1912020-12-20 11:09:58 -08009700 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9701 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9702 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9703 if (DBG) {
9704 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9705 }
Chalard Jean8e382112019-12-03 20:45:30 +09009706
James Mattisd31bdfa2020-12-23 16:37:26 -08009707 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9708 if (newDefaultNetwork != null) {
9709 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009710 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009711
James Mattisd31bdfa2020-12-23 16:37:26 -08009712 // Set an app level managed default and return since further processing only applies to the
9713 // default network.
9714 if (mDefaultRequest != nri) {
9715 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9716 return;
9717 }
9718
9719 makeDefaultNetwork(newDefaultNetwork);
9720
James Mattise3ef1912020-12-20 11:09:58 -08009721 if (oldDefaultNetwork != null) {
9722 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9723 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09009724 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009725 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009726 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009727 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009728 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009729 updateTcpBufferSizes(null != newDefaultNetwork
9730 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009731 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009732 }
9733
James Mattisd31bdfa2020-12-23 16:37:26 -08009734 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9735 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9736 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9737 try {
9738 if (VDBG) {
9739 log("Setting default network for " + nri
9740 + " using UIDs " + nri.getUids()
9741 + " with old network " + (oldDefaultNetwork != null
9742 ? oldDefaultNetwork.network().getNetId() : "null")
9743 + " and new network " + (newDefaultNetwork != null
9744 ? newDefaultNetwork.network().getNetId() : "null"));
9745 }
9746 if (nri.getUids().isEmpty()) {
9747 throw new IllegalStateException("makeDefaultForApps called without specifying"
9748 + " any applications to set as the default." + nri);
9749 }
9750 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009751 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009752 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009753 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009754 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009755 }
9756 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009757 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009758 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009759 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009760 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009761 }
9762 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009763 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009764 }
9765 }
9766
Junyu Lai35665cc2022-12-19 17:37:48 +08009767 /**
9768 * Collect restricted uid ranges for the given network and UserHandle, these uids
9769 * are not restricted for matched enterprise networks but being restricted for non-matched
9770 * enterprise networks and non-enterprise networks.
9771 */
9772 @NonNull
9773 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9774 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9775 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9776 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9777 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9778
9779 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9780 // The NC is built from a `ProfileNetworkPreference` which has only one
9781 // enterprise ID, so it's guaranteed to have exactly one.
9782 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9783 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9784 continue;
9785 }
9786 }
9787
9788 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9789 pref.capabilities.getUidRanges())) {
9790 throw new IllegalArgumentException(
9791 "Overlapping uid range in preference: " + pref);
9792 }
9793 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9794 }
9795 return restrictedUidRanges;
9796 }
9797
9798 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009799 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009800 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009801
Junyu Lai35665cc2022-12-19 17:37:48 +08009802 ensureRunningOnConnectivityServiceThread();
9803 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9804 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9805 .getUserHandles(true /* excludeDying */);
9806 if (users.isEmpty()) {
9807 throw new IllegalStateException("No user is available");
9808 }
9809
9810 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9811 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9812 for (final UserHandle user : users) {
9813 final ArraySet<UidRange> restrictedUidRanges =
9814 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9815 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9816 UidRange.createForUser(user), restrictedUidRanges));
9817 }
9818
9819 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9820 configs.add(new NativeUidRangeConfig(
9821 nai.network.netId, rangesParcel, 0 /* subPriority */));
9822 }
9823
9824 // The netd API replaces the previous configs with the current configs.
9825 // Thus, for network disconnection or preference removal, no need to
9826 // unset previous config. Instead, collecting all currently needed
9827 // configs and issue to netd.
9828 try {
9829 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9830 } catch (ServiceSpecificException e) {
9831 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009832 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009833 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009834 // Netd died. This will cause a runtime restart anyway.
9835 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009836 }
9837 }
9838
James Mattisd31bdfa2020-12-23 16:37:26 -08009839 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9840 try {
9841 if (null != newDefaultNetwork) {
9842 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9843 } else {
9844 mNetd.networkClearDefault();
9845 }
9846 } catch (RemoteException | ServiceSpecificException e) {
9847 loge("Exception setting default network :" + e);
9848 }
9849 }
9850
Chalard Jean05cbe972019-12-09 11:50:38 +09009851 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009852 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009853 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009854 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009855 processNewlySatisfiedListenRequests(nai);
9856 }
9857
9858 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009859 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9860 if (nri.isMultilayerRequest()) {
9861 continue;
9862 }
9863 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009864 if (!nr.isListen()) continue;
9865 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009866 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009867 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9868 }
9869 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009870 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009871
Chalard Jeancd397a22019-11-22 22:33:33 +09009872 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009873 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9874 if (nri.isMultilayerRequest()) {
9875 continue;
9876 }
9877 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009878 if (!nr.isListen()) continue;
9879 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9880 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009881 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009882 }
9883 }
9884 }
9885
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009886 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009887 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009888 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009889 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009890 @Nullable public final NetworkRequest mOldNetworkRequest;
9891 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009892 @Nullable public final NetworkAgentInfo mOldNetwork;
9893 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009894 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009895 @Nullable final NetworkRequest oldNetworkRequest,
9896 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009897 @Nullable final NetworkAgentInfo oldNetwork,
9898 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009899 mNetworkRequestInfo = networkRequestInfo;
9900 mOldNetworkRequest = oldNetworkRequest;
9901 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009902 mOldNetwork = oldNetwork;
9903 mNewNetwork = newNetwork;
9904 }
Chalard Jean49707572019-12-10 21:07:02 +09009905
9906 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009907 final NetworkRequest requestToShow = null != mNewNetworkRequest
9908 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9909 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009910 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9911 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009912 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009913 }
9914
Chalard Jean46a62372019-12-10 21:25:24 +09009915 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009916
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009917 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009918 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009919 }
9920
9921 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009922 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009923 // The code is never supposed to add two reassignments of the same request. Make
9924 // sure this stays true, but without imposing this expensive check on all
9925 // reassignments on all user devices.
9926 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009927 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009928 throw new IllegalStateException("Trying to reassign ["
9929 + reassignment + "] but already have ["
9930 + existing + "]");
9931 }
9932 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009933 }
Chalard Jean46a62372019-12-10 21:25:24 +09009934 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009935 }
9936
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009937 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009938 // the passed request.
9939 @Nullable
9940 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009941 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009942 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009943 }
9944 return null;
9945 }
Chalard Jean49707572019-12-10 21:07:02 +09009946
9947 public String toString() {
9948 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9949 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009950 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009951 for (final RequestReassignment rr : getRequestReassignments()) {
9952 sj.add(rr.toString());
9953 }
9954 return sj.toString();
9955 }
9956
9957 public String debugString() {
9958 final StringBuilder sb = new StringBuilder();
9959 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009960 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009961 for (final RequestReassignment rr : getRequestReassignments()) {
9962 sb.append("\n ").append(rr);
9963 }
9964 return sb.append("\n").toString();
9965 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009966 }
9967
Chalard Jean24344d72019-12-04 13:32:31 +09009968 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009969 @Nullable final NetworkRequest previousRequest,
9970 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009971 @Nullable final NetworkAgentInfo previousSatisfier,
9972 @Nullable final NetworkAgentInfo newSatisfier,
9973 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009974 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009975 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009976 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009977 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009978 log(" accepting network in place of " + previousSatisfier.toShortString()
9979 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009980 }
James Mattisa076c532020-12-02 14:12:41 -08009981 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009982 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009983 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009984 // If this network switch can't be supported gracefully, the request is not
9985 // lingered. This allows letting go of the network sooner to reclaim some
9986 // performance on the new network, since the radio can't do both at the same
9987 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009988 //
9989 // Also don't linger the request if the old network has been destroyed.
9990 // A destroyed network does not provide actual network connectivity, so
9991 // lingering it is not useful. In particular this ensures that a destroyed
9992 // network is outscored by its replacement,
9993 // then it is torn down immediately instead of being lingered, and any apps that
9994 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009995 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9996 }
Chalard Jean24344d72019-12-04 13:32:31 +09009997 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009998 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009999 }
junyulai0ac374f2020-12-14 18:41:52 +080010000
10001 // To prevent constantly CPU wake up for nascent timer, if a network comes up
10002 // and immediately satisfies a request then remove the timer. This will happen for
10003 // all networks except in the case of an underlying network for a VCN.
10004 if (newSatisfier.isNascent()) {
10005 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +080010006 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010007 }
10008
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010009 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -080010010 newSatisfier.unlingerRequest(newRequest.requestId);
10011 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +080010012 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -080010013 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010014 }
Chalard Jeana8ac2302021-03-01 22:16:08 +090010015 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010016 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010017 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -080010018 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010019 }
James Mattisa076c532020-12-02 14:12:41 -080010020 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010021 }
James Mattisa076c532020-12-02 14:12:41 -080010022 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010023 }
10024
James Mattisa076c532020-12-02 14:12:41 -080010025 /**
10026 * This function is triggered when something can affect what network should satisfy what
10027 * request, and it computes the network reassignment from the passed collection of requests to
10028 * network match to the one that the system should now have. That data is encoded in an
10029 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
10030 * satisfier.
10031 *
10032 * After the reassignment is computed, it is applied to the state objects.
10033 *
10034 * @param networkRequests the nri objects to evaluate for possible network reassignment
10035 * @return NetworkReassignment listing of proposed network assignment changes
10036 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010037 @NonNull
James Mattisa076c532020-12-02 14:12:41 -080010038 private NetworkReassignment computeNetworkReassignment(
10039 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090010040 final NetworkReassignment changes = new NetworkReassignment();
10041
Chalard Jeanc81d4c32021-04-07 17:06:19 +090010042 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090010043 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010044 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +090010045 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +090010046 }
Chalard Jean857a1712019-12-10 21:08:07 +090010047
James Mattisa076c532020-12-02 14:12:41 -080010048 for (final NetworkRequestInfo nri : networkRequests) {
10049 // Non-multilayer listen requests can be ignored.
10050 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
10051 continue;
10052 }
10053 NetworkAgentInfo bestNetwork = null;
10054 NetworkRequest bestRequest = null;
10055 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090010056 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080010057 // Stop evaluating as the highest possible priority request is satisfied.
10058 if (null != bestNetwork) {
10059 bestRequest = req;
10060 break;
10061 }
10062 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010063 if (null == bestNetwork && isDefaultBlocked(nri)) {
10064 // Remove default networking if disallowed for managed default requests.
10065 bestNetwork = mNoServiceNetwork;
10066 }
10067 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010068 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010069 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010070 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010071 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010072 }
10073 return changes;
10074 }
10075
James Mattisa076c532020-12-02 14:12:41 -080010076 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10077 return new HashSet<>(mNetworkRequests.values());
10078 }
10079
Paul Jensenc88b39b2015-06-16 14:27:36 -040010080 /**
James Mattisa076c532020-12-02 14:12:41 -080010081 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010082 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010083 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010084 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010085 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10086 }
10087
10088 /**
10089 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10090 * being disconnected.
10091 */
10092 private void rematchNetworksAndRequests(
10093 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10094 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010095 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010096 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010097 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010098 final long computed = SystemClock.elapsedRealtime();
10099 applyNetworkReassignment(changes, start);
10100 final long applied = SystemClock.elapsedRealtime();
10101 issueNetworkNeeds();
10102 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010103 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010104 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10105 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010106 log(changes.debugString());
10107 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010108 // Shorter form, only one line of log
10109 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10110 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010111 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010112 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010113
Chalard Jean1e4c2182023-10-06 18:45:53 +090010114 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10115 @Nullable final NetworkAgentInfo nai2) {
10116 if (null == nai1) return null == nai2;
10117 if (null == nai2) return false;
10118 return nai1.linkProperties.getInterfaceName()
10119 .equals(nai2.linkProperties.getInterfaceName());
10120 }
10121
Chalard Jeand7f762d2019-12-10 19:01:29 +090010122 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010123 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010124 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010125
10126 // Since most of the time there are only 0 or 1 background networks, it would probably
10127 // be more efficient to just use an ArrayList here. TODO : measure performance
10128 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10129 for (final NetworkAgentInfo nai : nais) {
10130 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10131 }
10132
Chalard Jeand7f762d2019-12-10 19:01:29 +090010133 // First, update the lists of satisfied requests in the network agents. This is necessary
10134 // because some code later depends on this state to be correct, most prominently computing
10135 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010136 for (final NetworkReassignment.RequestReassignment event :
10137 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010138 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10139 event.mOldNetworkRequest, event.mNewNetworkRequest,
10140 event.mOldNetwork, event.mNewNetwork,
10141 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010142 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010143
James Mattise3ef1912020-12-20 11:09:58 -080010144 // Process default network changes if applicable.
10145 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010146
Chalard Jean68eab722023-11-16 17:00:04 +090010147 // Update forwarding rules for the upstreams of local networks. Do this before sending
10148 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10149 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10150 // onAvailable so clients know what network the change is about. Store such changes in
10151 // an array that's only allocated if necessary (because it's almost never necessary).
10152 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10153 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10154 if (!nai.isLocalNetwork()) continue;
10155 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10156 if (null == nr) continue; // No upstream for this local network
10157 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10158 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10159 if (null == change) continue; // No change in upstreams for this network
10160 final String fromIface = nai.linkProperties.getInterfaceName();
10161 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10162 || change.mOldNetwork.isDestroyed()) {
10163 // There can be a change with the same interface name if the new network is the
10164 // replacement for the old network that was unregisteredAfterReplacement.
10165 try {
10166 if (null != change.mOldNetwork) {
10167 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10168 change.mOldNetwork.linkProperties.getInterfaceName());
10169 }
10170 // If the new upstream is already destroyed, there is no point in setting up
10171 // a forward (in fact, it might forward to the interface for some new network !)
10172 // Later when the upstream disconnects CS will try to remove the forward, which
10173 // is ignored with a benign log by RoutingCoordinatorService.
10174 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10175 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10176 change.mNewNetwork.linkProperties.getInterfaceName());
10177 }
10178 } catch (final RemoteException e) {
10179 loge("Can't update forwarding rules", e);
10180 }
10181 }
10182 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10183 localInfoChangedAgents.add(nai);
10184 }
10185
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010186 // Notify requested networks are available after the default net is switched, but
10187 // before LegacyTypeTracker sends legacy broadcasts
10188 for (final NetworkReassignment.RequestReassignment event :
10189 changes.getRequestReassignments()) {
10190 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010191 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010192 } else {
James Mattisa076c532020-12-02 14:12:41 -080010193 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010194 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010195 }
10196 }
10197
junyulai0ac374f2020-12-14 18:41:52 +080010198 // Update the inactivity state before processing listen callbacks, because the background
10199 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010200 // just yet though, because they have to be sent after the listens are processed to keep
10201 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010202 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010203 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010204 // Rematching may have altered the inactivity state of some networks, so update all
10205 // inactivity timers. updateInactivityState reads the state from the network agent
10206 // and does nothing if the state has not changed : the source of truth is controlled
10207 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10208 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010209 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010210 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010211 }
10212 }
10213
Chalard Jeanb10ab412019-12-11 14:12:30 +090010214 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010215 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010216 // Process listen requests and update capabilities if the background state has
10217 // changed for this network. For consistency with previous behavior, send onLost
10218 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010219 processNewlyLostListenRequests(nai);
10220 if (oldBackground != nai.isBackgroundNetwork()) {
10221 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010222 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010223 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010224 }
10225
junyulai0ac374f2020-12-14 18:41:52 +080010226 for (final NetworkAgentInfo nai : inactiveNetworks) {
10227 // For nascent networks, if connecting with no foreground request, skip broadcasting
10228 // LOSING for backward compatibility. This is typical when mobile data connected while
10229 // wifi connected with mobile data always-on enabled.
10230 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010231 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010232 }
10233
Chalard Jean68eab722023-11-16 17:00:04 +090010234 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10235 if (null != localInfoChangedAgents) {
10236 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10237 notifyNetworkCallbacks(nai,
10238 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010239 }
10240 }
10241
James Mattise3ef1912020-12-20 11:09:58 -080010242 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010243
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010244 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010245 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010246 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010247 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010248 // This network has active linger timers and no requests, but is not
10249 // lingering. Linger it.
10250 //
10251 // One way (the only way?) this can happen if this network is unvalidated
10252 // and became unneeded due to another network improving its score to the
10253 // point where this network will no longer be able to satisfy any requests
10254 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010255 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010256 notifyNetworkLosing(nai, now);
10257 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010258 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010259 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010260 teardownUnneededNetwork(nai);
10261 }
10262 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010263 }
10264 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010265
Chalard Jean62edfd82019-12-02 18:39:29 +090010266 /**
10267 * Apply a change in background state resulting from rematching networks with requests.
10268 *
10269 * During rematch, a network may change background states by starting to satisfy or stopping
10270 * to satisfy a foreground request. Listens don't count for this. When a network changes
10271 * background states, its capabilities need to be updated and callbacks fired for the
10272 * capability change.
10273 *
10274 * @param nai The network that changed background states
10275 */
10276 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10277 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10278 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10279 updateNetworkPermissions(nai, newNc);
10280 nai.getAndSetNetworkCapabilities(newNc);
10281 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10282 }
10283
Chalard Jeanf0344532019-11-19 19:23:38 +090010284 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010285 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010286 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010287 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10288 changes.getReassignment(mDefaultRequest);
10289 final NetworkAgentInfo oldDefaultNetwork =
10290 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10291 final NetworkAgentInfo newDefaultNetwork =
10292 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010293
Chalard Jean5b409c72021-02-04 13:12:59 +090010294 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010295 // Maintain the illusion : since the legacy API only understands one network at a time,
10296 // if the default network changed, apps should see a disconnected broadcast for the
10297 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010298 if (oldDefaultNetwork != null) {
10299 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10300 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010301 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010302 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010303 // The new default network can be newly null if and only if the old default
10304 // network doesn't satisfy the default request any more because it lost a
10305 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010306 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010307 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010308 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010309 }
10310 }
10311
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010312 // Now that all the callbacks have been sent, send the legacy network broadcasts
10313 // as needed. This is necessary so that legacy requests correctly bind dns
10314 // requests to this network. The legacy users are listening for this broadcast
10315 // and will generally do a dns request so they can ensureRouteToHost and if
10316 // they do that before the callbacks happen they'll use the default network.
10317 //
10318 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10319 // callbacks, but if apps can receive the broadcast before the callback, they still might
10320 // have an inconsistent view of networking.
10321 //
10322 // This *does* introduce a race where if the user uses the new api
10323 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10324 // they may get old info. Reverse this after the old startUsing api is removed.
10325 // This is on top of the multiple intent sequencing referenced in the todo above.
10326 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010327 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010328 addNetworkToLegacyTypeTracker(nai);
10329 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010330 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010331 }
10332
Chalard Jean0354d8c2021-01-12 10:58:56 +090010333 private void issueNetworkNeeds() {
10334 ensureRunningOnConnectivityServiceThread();
10335 for (final NetworkOfferInfo noi : mNetworkOffers) {
10336 issueNetworkNeeds(noi);
10337 }
10338 }
10339
10340 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10341 ensureRunningOnConnectivityServiceThread();
10342 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10343 informOffer(nri, noi.offer, mNetworkRanker);
10344 }
10345 }
10346
10347 /**
10348 * Inform a NetworkOffer about any new situation of a request.
10349 *
10350 * This function handles updates to offers. A number of events may happen that require
10351 * updating the registrant for this offer about the situation :
10352 * • The offer itself was updated. This may lead the offer to no longer being able
10353 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10354 * or conversely being strengthened enough to beat the satisfier (and therefore
10355 * start being needed)
10356 * • The network satisfying a request changed (including cases where the request
10357 * starts or stops being satisfied). The new network may be a stronger or weaker
10358 * match than the old one, possibly affecting whether the offer is needed.
10359 * • The network satisfying a request updated their score. This may lead the offer
10360 * to no longer be able to beat it if the current satisfier got better, or
10361 * conversely start being a good choice if the current satisfier got weaker.
10362 *
10363 * @param nri The request
10364 * @param offer The offer. This may be an updated offer.
10365 */
10366 private static void informOffer(@NonNull NetworkRequestInfo nri,
10367 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10368 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10369 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010370
10371 // Multi-layer requests have a currently active request, the one being satisfied.
10372 // Since the system will try to bring up a better network than is currently satisfying
10373 // the request, NetworkProviders need to be told the offers matching the requests *above*
10374 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10375 // not needed, and the offer is needed for the active request iff the offer can beat
10376 // the satisfier.
10377 // For non-multilayer requests, the logic above gracefully degenerates to only the
10378 // last case.
10379 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10380 // providers that the offer is needed for this request, until the active request is found.
10381 // In a second phase, deal with the currently active request. In a third phase, inform
10382 // the providers that offer is unneeded for the remaining requests.
10383
10384 // First phase : inform providers of all requests above the active request.
10385 int i;
10386 for (i = 0; nri.mRequests.size() > i; ++i) {
10387 final NetworkRequest request = nri.mRequests.get(i);
10388 if (activeRequest == request) break; // Found the active request : go to phase 2
10389 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10390 // Since this request is higher-priority than the one currently satisfied, if the
10391 // offer can satisfy it, the provider should try and bring up the network for sure ;
10392 // no need to even ask the ranker – an offer that can satisfy is always better than
10393 // no network. Hence tell the provider so unless it already knew.
10394 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10395 offer.onNetworkNeeded(request);
10396 }
10397 }
10398
10399 // Second phase : deal with the active request (if any)
10400 if (null != activeRequest && activeRequest.isRequest()) {
10401 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010402 // If an offer can satisfy the request, it is considered needed if it is currently
10403 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010404 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010405 && satisfier.factorySerialNumber == offer.providerId
10406 && activeRequest.canBeSatisfiedBy(offer.caps);
10407 final boolean newNeeded = currentlyServing
10408 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010409 if (newNeeded != oldNeeded) {
10410 if (newNeeded) {
10411 offer.onNetworkNeeded(activeRequest);
10412 } else {
10413 // The offer used to be able to beat the satisfier. Now it can't.
10414 offer.onNetworkUnneeded(activeRequest);
10415 }
10416 }
10417 }
10418
10419 // Third phase : inform the providers that the offer isn't needed for any request
10420 // below the active one.
10421 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10422 final NetworkRequest request = nri.mRequests.get(i);
10423 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10424 // Since this request is lower-priority than the one currently satisfied, if the
10425 // offer can satisfy it, the provider should not try and bring up the network.
10426 // Hence tell the provider so unless it already knew.
10427 if (offer.neededFor(request)) {
10428 offer.onNetworkUnneeded(request);
10429 }
10430 }
10431 }
10432
Chalard Jean61c79252019-11-07 23:07:32 +090010433 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10434 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10435 NetworkRequest nr = nai.requestAt(i);
10436 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10437 // legacy type tracker filters out repeat adds
10438 mLegacyTypeTracker.add(nr.legacyType, nai);
10439 }
10440 }
10441
10442 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010443 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010444 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10445 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10446 if (nai.isVPN()) {
10447 mLegacyTypeTracker.add(TYPE_VPN, nai);
10448 }
10449 }
10450
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010451 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010452 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010453 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010454 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010455 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010456 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010457
Chalard Jean254bd162022-08-25 13:04:51 +090010458 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010459 // Don't repeat publish.
10460 if (newInetCondition == mDefaultInetConditionPublished) return;
10461
10462 mDefaultInetConditionPublished = newInetCondition;
10463 sendInetConditionBroadcast(nai.networkInfo);
10464 }
10465
Chalard Jeand61375d2020-01-14 22:46:36 +090010466 @NonNull
10467 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10468 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010469 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010470 final boolean suspended =
10471 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10472 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10473 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10474 // state. This is because the network could have been suspended before connecting,
10475 // or it could be disconnecting while being suspended, and in both these cases
10476 // the state should not be overridden. Note that the only detailed state that
10477 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10478 // worry about multiple different substates of CONNECTED.
10479 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10480 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010481 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10482 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10483 // network agent is created, then goes to suspended, then goes out of suspended without
10484 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010485 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010486 ? NetworkInfo.DetailedState.CONNECTED
10487 : NetworkInfo.DetailedState.CONNECTING,
10488 info.getReason(),
10489 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010490 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010491 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010492 return newInfo;
10493 }
10494
10495 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10496 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10497
Erik Kline99f301b2017-02-15 19:59:17 +090010498 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010499 NetworkInfo oldInfo = null;
10500 synchronized (networkAgent) {
10501 oldInfo = networkAgent.networkInfo;
10502 networkAgent.networkInfo = newInfo;
10503 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010504
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010505 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010506 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10507 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010508 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010509
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010510 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010511 // A network that has just connected has zero requests and is thus a foreground network.
10512 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10513
Luke Huangfdd11f82019-04-09 18:41:49 +080010514 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010515
10516 networkAgent.setCreated();
10517
10518 // If the network is created immediately on register, then apply the LinkProperties now.
10519 // Otherwise, this is done further down when the network goes into connected state.
10520 // Applying the LinkProperties means that the network is ready to carry traffic -
10521 // interfaces and routing rules have been added, DNS servers programmed, etc.
10522 // For VPNs, this must be done before the capabilities are updated, because as soon as
10523 // that happens, UIDs are routed to the network.
10524 if (shouldCreateNetworksImmediately()) {
10525 applyInitialLinkProperties(networkAgent);
10526 }
10527
10528 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10529 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010530 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010531 // Initialize the network's capabilities to their starting values according to the
10532 // underlying networks. This ensures that the capabilities are correct before
10533 // anything happens to the network.
10534 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010535 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010536 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010537 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010538 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010539 }
10540
Chalard Jean254bd162022-08-25 13:04:51 +090010541 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10542 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010543
lucaslin45e639b2019-04-03 17:09:28 +080010544 // NetworkCapabilities need to be set before sending the private DNS config to
10545 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010546 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10547
Erik Kline9a62f012018-03-21 07:18:33 -070010548 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010549 if (!shouldCreateNetworksImmediately()) {
10550 applyInitialLinkProperties(networkAgent);
10551 } else {
10552 // The network was created when the agent registered, and the LinkProperties are
10553 // already up-to-date. However, updateLinkProperties also makes some changes only
10554 // when the network connects. Apply those changes here. On T and below these are
10555 // handled by the applyInitialLinkProperties call just above.
10556 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10557 // If something depends on both LinkProperties and connected state, it should be in
10558 // this method as well.
10559 networkAgent.clatd.update();
10560 updateProxy(networkAgent.linkProperties, null);
10561 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010562
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010563 // If a rate limit has been configured and is applicable to this network (network
10564 // provides internet connectivity), apply it. The tc police filter cannot be attached
10565 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010566 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010567 // Note: in case of a system server crash, the NetworkController constructor in netd
10568 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10569 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10570 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10571 mIngressRateLimit);
10572 }
10573
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010574 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10575 // command must be sent after updating LinkProperties to maximize chances of
10576 // NetworkMonitor seeing the correct LinkProperties when starting.
10577 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010578 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010579 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010580 }
Chalard Jeand4900722022-02-06 12:25:38 +090010581 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10582 params.networkAgentConfig = networkAgent.networkAgentConfig;
10583 params.networkCapabilities = networkAgent.networkCapabilities;
10584 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10585 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010586 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10587 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10588 // call that would cause a Log.wtf to be emitted from the system_server process, and
10589 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10590 // process to check the interface version, just use an SDK check. NetworkStack will
10591 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010592 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010593 networkAgent.networkMonitor().notifyNetworkConnected(params);
10594 } else {
10595 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10596 params.networkCapabilities);
10597 }
Chalard Jean0f141332023-06-05 19:26:17 +090010598 final long evaluationDelay;
10599 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10600 // If the network is anything other than pure wifi, use the default timeout.
10601 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10602 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10603 // If the network is explicitly selected, use the default timeout because it's
10604 // shorter and the user is likely staring at the screen expecting it to validate
10605 // right away.
10606 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10607 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10608 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10609 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10610 } else {
10611 // It's wifi, automatically connected, and bad wifi is preferred : use the
10612 // longer timeout to avoid the device switching to captive portals with bad
10613 // signal or very slow response.
10614 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10615 }
10616 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010617
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010618 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10619 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10620 // capabilities, so it only needs to be done once on initial connect, not every time the
10621 // network's capabilities change. Note that we do this before rematching the network,
10622 // so we could decide to tear it down immediately afterwards. That's fine though - on
10623 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10624 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010625 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010626
junyulai0ac374f2020-12-14 18:41:52 +080010627 // Before first rematching networks, put an inactivity timer without any request, this
10628 // allows {@code updateInactivityState} to update the state accordingly and prevent
10629 // tearing down for any {@code unneeded} evaluation in this period.
10630 // Note that the timer will not be rescheduled since the expiry time is
10631 // fixed after connection regardless of the network satisfying other requests or not.
10632 // But it will be removed as soon as the network satisfies a request for the first time.
10633 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10634 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010635 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010636
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010637 if (mTrackMultiNetworkActivities) {
10638 // Start tracking activity of this network.
10639 // This must be called before rematchAllNetworksAndRequests since the network
10640 // should be tracked when the network becomes the default network.
10641 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
10642 // can be triggered later if this network becomes the default network.
10643 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
10644 }
10645
Paul Jensen05e85ee2014-09-11 11:00:39 -040010646 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010647 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010648
10649 // This has to happen after matching the requests, because callbacks are just requests.
10650 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010651 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010652 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010653 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010654 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010655 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010656 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010657 if (networkAgent.isVPN()) {
10658 // As the active or bound network changes for apps, broadcast the default proxy, as
10659 // apps may need to update their proxy data. This is called after disconnecting from
10660 // VPN to make sure we do not broadcast the old proxy data.
10661 // TODO(b/122649188): send the broadcast only to VPN users.
10662 mProxyTracker.sendProxyBroadcast();
10663 }
Chalard Jean254bd162022-08-25 13:04:51 +090010664 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10665 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010666 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010667 }
10668 }
10669
Chalard Jean28018572020-12-21 18:36:52 +090010670 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010671 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10672 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010673 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010674 }
10675
Erik Kline99f301b2017-02-15 19:59:17 +090010676 // Notify only this one new request of the current state. Transfer all the
10677 // current state by calling NetworkCapabilities and LinkProperties callbacks
10678 // so that callers can be guaranteed to have as close to atomicity in state
10679 // transfer as can be supported by this current API.
10680 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010681 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010682 if (nri.mPendingIntent != null) {
10683 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10684 // Attempt no subsequent state pushes where intents are involved.
10685 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010686 }
Erik Kline99f301b2017-02-15 19:59:17 +090010687
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010688 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010689 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010690 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10691 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10692 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010693 }
10694
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010695 // Notify the requests on this NAI that the network is now lingered.
10696 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010697 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010698 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10699 }
10700
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010701 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10702 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10703 return vpnBlocked
10704 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10705 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10706 }
10707
10708 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10709 if (blockedReasons == BLOCKED_REASON_NONE) {
10710 mUidBlockedReasons.delete(uid);
10711 } else {
10712 mUidBlockedReasons.put(uid, blockedReasons);
10713 }
10714 }
10715
junyulaif2c67e42018-08-07 19:50:45 +080010716 /**
10717 * Notify of the blocked state apps with a registered callback matching a given NAI.
10718 *
10719 * Unlike other callbacks, blocked status is different between each individual uid. So for
10720 * any given nai, all requests need to be considered according to the uid who filed it.
10721 *
10722 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010723 * @param oldMetered True if the previous network capabilities were metered.
10724 * @param newMetered True if the current network capabilities are metered.
10725 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10726 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010727 */
10728 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010729 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10730 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010731
10732 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10733 NetworkRequest nr = nai.requestAt(i);
10734 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010735
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010736 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10737 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10738 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010739 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010740 : oldVpnBlocked;
10741
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010742 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10743 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10744 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010745 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010746 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010747 }
10748 }
10749 }
10750
10751 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010752 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010753 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010754 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010755 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010756 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010757 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010758 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010759 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010760
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010761 final int oldBlockedState = getBlockedState(
10762 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10763 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10764 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010765 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010766 }
junyulaif2c67e42018-08-07 19:50:45 +080010767 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10768 NetworkRequest nr = nai.requestAt(i);
10769 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010770 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010771 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10772 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010773 }
10774 }
10775 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010776 }
10777
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010778 @VisibleForTesting
10779 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010780 // The NetworkInfo we actually send out has no bearing on the real
10781 // state of affairs. For example, if the default connection is mobile,
10782 // and a request for HIPRI has just gone away, we need to pretend that
10783 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10784 // the state to DISCONNECTED, even though the network is of type MOBILE
10785 // and is still connected.
10786 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10787 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010788 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010789 if (state != DetailedState.DISCONNECTED) {
10790 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010791 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010792 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010793 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010794 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10795 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10796 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10797 if (info.isFailover()) {
10798 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10799 nai.networkInfo.setFailover(false);
10800 }
10801 if (info.getReason() != null) {
10802 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10803 }
10804 if (info.getExtraInfo() != null) {
10805 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10806 }
10807 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010808 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010809 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010810 if (newDefaultAgent != null) {
10811 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10812 newDefaultAgent.networkInfo);
10813 } else {
10814 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10815 }
10816 }
10817 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10818 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010819 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010820 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010821 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010822 }
10823 }
10824 }
10825
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010826 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010827 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010828 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010829 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010830 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010831 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10832 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010833 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10834 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010835 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010836 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010837 } else {
10838 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10839 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010840 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010841 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010842
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010843 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10844 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10845 }
10846
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010847 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010848 * Returns the list of all interfaces that could be used by network traffic that does not
10849 * explicitly specify a network. This includes the default network, but also all VPNs that are
10850 * currently connected.
10851 *
10852 * Must be called on the handler thread.
10853 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010854 @NonNull
10855 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010856 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010857 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010858 final Set<Integer> activeNetIds = new ArraySet<>();
10859 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10860 if (nri.isBeingSatisfied()) {
10861 activeNetIds.add(nri.getSatisfier().network().netId);
10862 }
10863 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010864 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010865 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010866 defaultNetworks.add(nai.network);
10867 }
10868 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010869 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010870 }
10871
10872 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010873 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10874 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010875 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010876 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010877 ensureRunningOnConnectivityServiceThread();
10878 String activeIface = null;
10879 LinkProperties activeLinkProperties = getActiveLinkProperties();
10880 if (activeLinkProperties != null) {
10881 activeIface = activeLinkProperties.getInterfaceName();
10882 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010883
junyulai2050bed2021-01-23 09:46:34 +080010884 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010885 try {
junyulaide41fc22021-01-22 22:46:01 +080010886 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010887 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010888 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10889 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010890 } catch (Exception ignored) {
10891 }
10892 }
10893
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010894 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010895 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010896 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010897 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010898 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010899
10900 if (!TextUtils.isEmpty(settingUrl)) {
10901 return settingUrl;
10902 }
10903
10904 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010905 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010906 if (!TextUtils.isEmpty(settingUrl)) {
10907 return settingUrl;
10908 }
10909
10910 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010911 }
10912
10913 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010914 public void startNattKeepalive(Network network, int intervalSeconds,
10915 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010916 enforceKeepalivePermission();
10917 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010918 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010919 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10920 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010921 // false and set the underpinned network to null because there is no way and no
10922 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10923 // deprecated method.
10924 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010925 }
10926
10927 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010928 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010929 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010930 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010931 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010932 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010933 mKeepaliveTracker.startNattKeepalive(
10934 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010935 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10936 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010937 } finally {
10938 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10939 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010940 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10941 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010942 }
10943 }
junyulaid05a1922019-01-15 11:32:44 +080010944 }
10945
10946 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010947 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010948 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010949 try {
10950 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010951 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010952 mKeepaliveTracker.startTcpKeepalive(
10953 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10954 } finally {
10955 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10956 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010957 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10958 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010959 }
10960 }
junyulai0835a1e2019-01-08 20:04:33 +080010961 }
10962
10963 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010964 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010965 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010966 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10967 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010968 }
10969
10970 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010971 public int[] getSupportedKeepalives() {
10972 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10973 // Backwards compatibility with CTS 13
10974 android.Manifest.permission.QUERY_ALL_PACKAGES);
10975
10976 return BinderUtils.withCleanCallingIdentity(() ->
10977 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10978 }
10979
10980 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010981 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010982 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010983
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010984 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010985 final long token = Binder.clearCallingIdentity();
10986 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010987 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10988 UserHandle.getUserHandleForUid(uid))) {
10989 return;
10990 }
10991
Heemin Seogdb8489d2019-06-12 09:21:44 -070010992 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10993 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010994
10995 // Turn airplane mode off
10996 setAirplaneMode(false);
10997
10998 // restore private DNS settings to default mode (opportunistic)
10999 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
11000 UserHandle.getUserHandleForUid(uid))) {
11001 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
11002 PRIVATE_DNS_MODE_OPPORTUNISTIC);
11003 }
11004
11005 Settings.Global.putString(mContext.getContentResolver(),
11006 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080011007 } finally {
11008 Binder.restoreCallingIdentity(token);
11009 }
Stuart Scottd5463642015-04-02 18:00:02 -070011010 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040011011
Ricky Wai7097cc92018-01-23 04:09:45 +000011012 @Override
11013 public byte[] getNetworkWatchlistConfigHash() {
11014 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
11015 if (nwm == null) {
11016 loge("Unable to get NetworkWatchlistManager");
11017 return null;
11018 }
11019 // Redirect it to network watchlist service to access watchlist file and calculate hash.
11020 return nwm.getWatchlistConfigHash();
11021 }
11022
Hugo Benichibe0c7652016-05-31 16:28:06 +090011023 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090011024 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080011025 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090011026 }
Hugo Benichif4210292017-04-21 15:07:12 +090011027
11028 private static boolean toBool(int encodedBoolean) {
11029 return encodedBoolean != 0; // Only 0 means false.
11030 }
11031
11032 private static int encodeBool(boolean b) {
11033 return b ? 1 : 0;
11034 }
mswest4632928412018-03-12 10:34:34 -070011035
11036 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011037 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
11038 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
11039 @NonNull String[] args) {
11040 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
11041 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070011042 }
11043
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011044 private Boolean parseBooleanArgument(final String arg) {
11045 if ("true".equals(arg)) {
11046 return true;
11047 } else if ("false".equals(arg)) {
11048 return false;
11049 } else {
11050 return null;
11051 }
11052 }
11053
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011054 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070011055 @Override
11056 public int onCommand(String cmd) {
11057 if (cmd == null) {
11058 return handleDefaultCommands(cmd);
11059 }
11060 final PrintWriter pw = getOutPrintWriter();
11061 try {
11062 switch (cmd) {
11063 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011064 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11065 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011066 final String action = getNextArg();
11067 if ("enable".equals(action)) {
11068 setAirplaneMode(true);
11069 return 0;
11070 } else if ("disable".equals(action)) {
11071 setAirplaneMode(false);
11072 return 0;
11073 } else if (action == null) {
11074 final ContentResolver cr = mContext.getContentResolver();
11075 final int enabled = Settings.Global.getInt(cr,
11076 Settings.Global.AIRPLANE_MODE_ON);
11077 pw.println(enabled == 0 ? "disabled" : "enabled");
11078 return 0;
11079 } else {
11080 onHelp();
11081 return -1;
11082 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011083 case "set-chain3-enabled": {
11084 final Boolean enabled = parseBooleanArgument(getNextArg());
11085 if (null == enabled) {
11086 onHelp();
11087 return -1;
11088 }
11089 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11090 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11091 enabled);
11092 return 0;
11093 }
11094 case "get-chain3-enabled": {
11095 final boolean chainEnabled = getFirewallChainEnabled(
11096 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11097 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11098 return 0;
11099 }
11100 case "set-package-networking-enabled": {
11101 final Boolean enabled = parseBooleanArgument(getNextArg());
11102 final String packageName = getNextArg();
11103 if (null == enabled || null == packageName) {
11104 onHelp();
11105 return -1;
11106 }
11107 // Throws NameNotFound if the package doesn't exist.
11108 final int appId = setPackageFirewallRule(
11109 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11110 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11111 final String msg = (enabled ? "Enabled" : "Disabled")
11112 + " networking for " + packageName + ", appId " + appId;
11113 Log.i(TAG, msg);
11114 pw.println(msg);
11115 return 0;
11116 }
11117 case "get-package-networking-enabled": {
11118 final String packageName = getNextArg();
11119 final int rule = getPackageFirewallRule(
11120 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11121 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11122 pw.println(packageName + ":" + "allow");
11123 } else if (FIREWALL_RULE_DENY == rule) {
11124 pw.println(packageName + ":" + "deny");
11125 } else {
11126 throw new IllegalStateException("Unknown rule " + rule + " for package "
11127 + packageName);
11128 }
11129 return 0;
11130 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011131 case "reevaluate":
11132 // Usage : adb shell cmd connectivity reevaluate <netId>
11133 // If netId is omitted, then reevaluate the default network
11134 final String netId = getNextArg();
11135 final NetworkAgentInfo nai;
11136 if (null == netId) {
11137 // Note that the command is running on the wrong thread to call this,
11138 // so this could in principle return stale data. But it can't crash.
11139 nai = getDefaultNetwork();
11140 } else {
11141 // If netId can't be parsed, this throws NumberFormatException, which
11142 // is passed back to adb who prints it.
11143 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11144 }
11145 if (null == nai) {
11146 pw.println("Unknown network (net ID not found or no default network)");
11147 return 0;
11148 }
11149 Log.d(TAG, "Reevaluating network " + nai.network);
11150 reportNetworkConnectivity(nai.network, !nai.isValidated());
11151 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011152 case "bpf-get-cgroup-program-id": {
11153 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11154 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11155 // for more detail.
11156 // If type can't be parsed, this throws NumberFormatException, which
11157 // is passed back to adb who prints it.
11158 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011159 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011160 pw.println(ret);
11161 return 0;
11162 }
mswest4632928412018-03-12 10:34:34 -070011163 default:
11164 return handleDefaultCommands(cmd);
11165 }
11166 } catch (Exception e) {
11167 pw.println(e);
11168 }
11169 return -1;
11170 }
11171
11172 @Override
11173 public void onHelp() {
11174 PrintWriter pw = getOutPrintWriter();
11175 pw.println("Connectivity service commands:");
11176 pw.println(" help");
11177 pw.println(" Print this help text.");
11178 pw.println(" airplane-mode [enable|disable]");
11179 pw.println(" Turn airplane mode on or off.");
11180 pw.println(" airplane-mode");
11181 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011182 pw.println(" set-chain3-enabled [true|false]");
11183 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11184 pw.println(" get-chain3-enabled");
11185 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11186 pw.println(" set-package-networking-enabled [true|false] [package name]");
11187 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11188 + " no effect if the chain is disabled.");
11189 pw.println(" get-package-networking-enabled [package name]");
11190 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011191 }
11192 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011193
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011194 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011195 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11196 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11197 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011198 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011199 }
11200
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011201 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11202 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011203 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11204 final TransportInfo newInfo = nc.getTransportInfo();
11205 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11206 return;
11207 }
11208 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011209 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011210 }
11211 }
11212
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011213 /**
11214 * @param connectionInfo the connection to resolve.
11215 * @return {@code uid} if the connection is found and the app has permission to observe it
11216 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11217 * connection is not found.
11218 */
11219 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011220 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11221 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11222 }
11223
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011224 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011225 connectionInfo.local, connectionInfo.remote);
11226
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011227 if (uid == INVALID_UID) return uid; // Not found.
11228
11229 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11230 // VPN, if any, that applies to the UID that owns the connection.
11231 if (checkNetworkStackPermission()) return uid;
11232
11233 final NetworkAgentInfo vpn = getVpnForUid(uid);
11234 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011235 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011236 return INVALID_UID;
11237 }
11238
11239 return uid;
11240 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011241
Benedict Wong493e04b2018-11-09 14:45:34 -080011242 /**
11243 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11244 *
11245 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11246 */
11247 @Override
11248 public IBinder startOrGetTestNetworkService() {
11249 synchronized (mTNSLock) {
11250 TestNetworkService.enforceTestNetworkPermissions(mContext);
11251
11252 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011253 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011254 }
11255
11256 return mTNS;
11257 }
11258 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011259
Cody Kesting73708bf2019-12-18 10:57:50 -080011260 /**
11261 * Handler used for managing all Connectivity Diagnostics related functions.
11262 *
11263 * @see android.net.ConnectivityDiagnosticsManager
11264 *
11265 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11266 */
11267 @VisibleForTesting
11268 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011269 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11270
Cody Kesting73708bf2019-12-18 10:57:50 -080011271 /**
11272 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11273 * android.net.ConnectivityDiagnosticsManager}.
11274 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11275 * NetworkRequestInfo to be registered
11276 */
11277 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11278
11279 /**
11280 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11281 * android.net.ConnectivityDiagnosticsManager}.
11282 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11283 * arg1 = the uid of the caller
11284 */
11285 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11286
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011287 /**
11288 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011289 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011290 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11291 * NetworkMonitor.
11292 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011293 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011294 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011295
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011296 /**
11297 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11298 * been detected on the network.
11299 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11300 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11301 * arg2 = NetID.
11302 * data = PersistableBundle of extras passed from NetworkMonitor.
11303 */
11304 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11305
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011306 /**
11307 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11308 * the platform. This event will invoke {@link
11309 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11310 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011311 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011312 */
11313 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11314
Cody Kesting73708bf2019-12-18 10:57:50 -080011315 private ConnectivityDiagnosticsHandler(Looper looper) {
11316 super(looper);
11317 }
11318
11319 @Override
11320 public void handleMessage(Message msg) {
11321 switch (msg.what) {
11322 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11323 handleRegisterConnectivityDiagnosticsCallback(
11324 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11325 break;
11326 }
11327 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11328 handleUnregisterConnectivityDiagnosticsCallback(
11329 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11330 break;
11331 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011332 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011333 final ConnectivityReportEvent reportEvent =
11334 (ConnectivityReportEvent) msg.obj;
11335
Aaron Huang959d3642021-01-21 15:47:41 +080011336 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011337 break;
11338 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011339 case EVENT_DATA_STALL_SUSPECTED: {
11340 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011341 final Pair<Long, PersistableBundle> arg =
11342 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011343 if (nai == null) break;
11344
Aaron Huang959d3642021-01-21 15:47:41 +080011345 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011346 break;
11347 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011348 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011349 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011350 break;
11351 }
11352 default: {
11353 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11354 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011355 }
11356 }
11357 }
11358
11359 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11360 @VisibleForTesting
11361 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11362 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11363 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011364 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011365
11366 @VisibleForTesting
11367 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011368 @NonNull IConnectivityDiagnosticsCallback cb,
11369 @NonNull NetworkRequestInfo nri,
11370 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011371 mCb = cb;
11372 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011373 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011374 }
11375
11376 @Override
11377 public void binderDied() {
11378 log("ConnectivityDiagnosticsCallback IBinder died.");
11379 unregisterConnectivityDiagnosticsCallback(mCb);
11380 }
11381 }
11382
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011383 /**
11384 * Class used for sending information from {@link
11385 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11386 */
11387 private static class NetworkTestedResults {
11388 private final int mNetId;
11389 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011390 @Nullable private final String mRedirectUrl;
11391
11392 private NetworkTestedResults(
11393 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11394 mNetId = netId;
11395 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011396 mRedirectUrl = redirectUrl;
11397 }
11398 }
11399
11400 /**
11401 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11402 * ConnectivityDiagnosticsHandler}.
11403 */
11404 private static class ConnectivityReportEvent {
11405 private final long mTimestampMillis;
11406 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011407 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011408
Aaron Huang959d3642021-01-21 15:47:41 +080011409 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11410 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011411 mTimestampMillis = timestampMillis;
11412 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011413 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011414 }
11415 }
11416
Cody Kestingf1120be2020-08-03 18:01:40 -070011417 /**
11418 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11419 * ConnectivityDiagnosticsHandler}.
11420 */
11421 private static class ReportedNetworkConnectivityInfo {
11422 public final boolean hasConnectivity;
11423 public final boolean isNetworkRevalidating;
11424 public final int reporterUid;
11425 @NonNull public final NetworkAgentInfo nai;
11426
11427 private ReportedNetworkConnectivityInfo(
11428 boolean hasConnectivity,
11429 boolean isNetworkRevalidating,
11430 int reporterUid,
11431 @NonNull NetworkAgentInfo nai) {
11432 this.hasConnectivity = hasConnectivity;
11433 this.isNetworkRevalidating = isNetworkRevalidating;
11434 this.reporterUid = reporterUid;
11435 this.nai = nai;
11436 }
11437 }
11438
Cody Kesting73708bf2019-12-18 10:57:50 -080011439 private void handleRegisterConnectivityDiagnosticsCallback(
11440 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11441 ensureRunningOnConnectivityServiceThread();
11442
11443 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011444 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011445 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11446
James Mattis64b8b0f2020-11-24 17:40:49 -080011447 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11448 // confusing for these networks to change when an NRI is satisfied in another layer.
11449 if (nri.isMultilayerRequest()) {
11450 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11451 + "network requests.");
11452 }
11453
Cody Kesting73708bf2019-12-18 10:57:50 -080011454 // This means that the client registered the same callback multiple times. Do
11455 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011456 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011457 if (VDBG) log("Diagnostics callback is already registered");
11458
11459 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11460 // incremented when the NetworkRequestInfo is created as part of
11461 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011462 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011463 return;
11464 }
11465
Cody Kesting31f1ff62020-03-05 10:46:02 -080011466 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011467
11468 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011469 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011470 } catch (RemoteException e) {
11471 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011472 return;
11473 }
11474
11475 // Once registered, provide ConnectivityReports for matching Networks
11476 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11477 synchronized (mNetworkForNetId) {
11478 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11479 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011480 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11481 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011482 matchingNetworks.add(nai);
11483 }
11484 }
11485 }
11486 for (final NetworkAgentInfo nai : matchingNetworks) {
11487 final ConnectivityReport report = nai.getConnectivityReport();
11488 if (report == null) {
11489 continue;
11490 }
11491 if (!checkConnectivityDiagnosticsPermissions(
11492 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11493 continue;
11494 }
11495
11496 try {
11497 cb.onConnectivityReportAvailable(report);
11498 } catch (RemoteException e) {
11499 // Exception while sending the ConnectivityReport. Move on to the next network.
11500 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011501 }
11502 }
11503
11504 private void handleUnregisterConnectivityDiagnosticsCallback(
11505 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11506 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011507 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011508
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011509 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11510 mConnectivityDiagnosticsCallbacks.remove(iCb);
11511 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011512 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11513 return;
11514 }
11515
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011516 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011517
Cody Kesting70fa2b22020-12-02 12:16:56 -080011518 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11519 // (if the Binder died)
11520 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11521 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011522 return;
11523 }
11524
Cody Kesting46cb1672020-03-04 13:35:20 -080011525 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11526 // incremented when the NetworkRequestInfo is created as part of
11527 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011528 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011529
Cody Kesting31f1ff62020-03-05 10:46:02 -080011530 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011531 }
11532
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011533 private void handleNetworkTestedWithExtras(
11534 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11535 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011536 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011537 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011538 final ConnectivityReport report =
11539 new ConnectivityReport(
11540 reportEvent.mNai.network,
11541 reportEvent.mTimestampMillis,
11542 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011543 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011544 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011545 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011546
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011547 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011548 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011549 for (final IConnectivityDiagnosticsCallback cb : results) {
11550 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011551 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011552 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011553 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011554 }
11555 }
11556 }
11557
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011558 private void handleDataStallSuspected(
11559 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11560 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011561 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011562 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011563 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011564 new DataStallReport(
11565 nai.network,
11566 timestampMillis,
11567 detectionMethod,
11568 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011569 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011570 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011571 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011572 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011573 for (final IConnectivityDiagnosticsCallback cb : results) {
11574 try {
11575 cb.onDataStallSuspected(report);
11576 } catch (RemoteException ex) {
11577 loge("Error invoking onDataStallSuspected", ex);
11578 }
11579 }
11580 }
11581
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011582 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011583 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11584 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11585 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11586
11587 // If the Network is being re-validated as a result of this call to
11588 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11589 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011590 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011591 getMatchingPermissionedCallbacks(
11592 nai,
11593 reportedNetworkConnectivityInfo.isNetworkRevalidating
11594 ? Process.INVALID_UID
11595 : reportedNetworkConnectivityInfo.reporterUid);
11596
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011597 for (final IConnectivityDiagnosticsCallback cb : results) {
11598 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011599 cb.onNetworkConnectivityReported(
11600 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011601 } catch (RemoteException ex) {
11602 loge("Error invoking onNetworkConnectivityReported", ex);
11603 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011604
11605 // If the Network isn't re-validating, also provide the cached report. If there is no
11606 // cached report, the Network is still being validated and a report will be sent once
11607 // validation is complete. Note that networks which never undergo validation will still
11608 // have a cached ConnectivityReport with RESULT_SKIPPED.
11609 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11610 try {
11611 cb.onConnectivityReportAvailable(cachedReport);
11612 } catch (RemoteException ex) {
11613 loge("Error invoking onConnectivityReportAvailable", ex);
11614 }
11615 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011616 }
11617 }
11618
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011619 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011620 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11621 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011622 sanitized.setUids(null);
11623 sanitized.setAdministratorUids(new int[0]);
11624 sanitized.setOwnerUid(Process.INVALID_UID);
11625 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011626 }
11627
Cody Kestingf1120be2020-08-03 18:01:40 -070011628 /**
11629 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11630 *
11631 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11632 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011633 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011634 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011635 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011636 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011637 mConnectivityDiagnosticsCallbacks.entrySet()) {
11638 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11639 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011640
James Mattis64b8b0f2020-11-24 17:40:49 -080011641 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011642 if (!nai.satisfies(nri.mRequests.get(0))) {
11643 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011644 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011645
11646 // UID for this callback must either be:
11647 // - INVALID_UID (which sends callbacks to all UIDs), or
11648 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11649 // notified as a result)
11650 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11651 continue;
11652 }
11653
11654 if (!checkConnectivityDiagnosticsPermissions(
11655 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11656 continue;
11657 }
11658
11659 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011660 }
11661 return results;
11662 }
11663
Cody Kesting7474f672021-05-11 14:22:40 -070011664 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11665 @NonNull NetworkAgentInfo nai) {
11666 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11667 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11668 }
11669
Cody Kesting160ef392021-05-05 13:17:22 -070011670 private boolean hasLocationPermission(String packageName, int uid) {
11671 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11672 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11673 // call in a try-catch.
11674 try {
11675 if (!mLocationPermissionChecker.checkLocationPermission(
11676 packageName, null /* featureId */, uid, null /* message */)) {
11677 return false;
11678 }
11679 } catch (SecurityException e) {
11680 return false;
11681 }
11682
11683 return true;
11684 }
11685
11686 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11687 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011688 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011689 && virtual.networkCapabilities.getOwnerUid() == uid
11690 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11691 return true;
11692 }
11693 }
11694
11695 return false;
11696 }
11697
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011698 @VisibleForTesting
11699 boolean checkConnectivityDiagnosticsPermissions(
11700 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11701 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11702 return true;
11703 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011704 if (mAllowSysUiConnectivityReports
11705 && checkSystemBarServicePermission(callbackPid, callbackUid)) {
11706 return true;
11707 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011708
Cody Kesting160ef392021-05-05 13:17:22 -070011709 // Administrator UIDs also contains the Owner UID
11710 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11711 if (!CollectionUtils.contains(administratorUids, callbackUid)
11712 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011713 return false;
11714 }
11715
Cody Kesting7474f672021-05-11 14:22:40 -070011716 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11717 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011718 }
11719
Cody Kestingd199a9d2019-12-17 12:55:28 -080011720 @Override
11721 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011722 @NonNull IConnectivityDiagnosticsCallback callback,
11723 @NonNull NetworkRequest request,
11724 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011725 Objects.requireNonNull(callback, "callback must not be null");
11726 Objects.requireNonNull(request, "request must not be null");
11727 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11728
Cody Kesting73708bf2019-12-18 10:57:50 -080011729 if (request.legacyType != TYPE_NONE) {
11730 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11731 + " Please use NetworkCapabilities instead.");
11732 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011733 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011734 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011735
11736 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11737 // and administrator uids to be safe.
11738 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011739 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011740
11741 final NetworkRequest requestWithId =
11742 new NetworkRequest(
11743 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11744
11745 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11746 //
11747 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11748 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11749 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011750 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011751 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011752 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011753
11754 mConnectivityDiagnosticsHandler.sendMessage(
11755 mConnectivityDiagnosticsHandler.obtainMessage(
11756 ConnectivityDiagnosticsHandler
11757 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11758 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011759 }
11760
11761 @Override
11762 public void unregisterConnectivityDiagnosticsCallback(
11763 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011764 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011765 mConnectivityDiagnosticsHandler.sendMessage(
11766 mConnectivityDiagnosticsHandler.obtainMessage(
11767 ConnectivityDiagnosticsHandler
11768 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011769 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011770 0,
11771 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011772 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011773
Yan Yanfe96dde2022-12-05 23:00:01 +000011774 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11775 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11776 if (underlyingNetworks == null) return false;
11777
11778 for (Network network : underlyingNetworks) {
11779 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11780 return true;
11781 }
11782 }
11783 return false;
11784 }
11785
Cody Kestingf53a0752020-04-15 12:33:28 -070011786 @Override
11787 public void simulateDataStall(int detectionMethod, long timestampMillis,
11788 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011789 Objects.requireNonNull(network, "network must not be null");
11790 Objects.requireNonNull(extras, "extras must not be null");
11791
paulhu3ffffe72021-09-16 10:15:22 +080011792 enforceAnyPermissionOf(mContext,
11793 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011794 android.Manifest.permission.NETWORK_STACK);
11795 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011796 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11797 throw new SecurityException(
11798 "Data Stall simulation is only possible for test networks or networks built on"
11799 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011800 }
11801
11802 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011803 if (nai == null
11804 || (nai.creatorUid != mDeps.getCallingUid()
11805 && nai.creatorUid != Process.SYSTEM_UID)) {
11806 throw new SecurityException(
11807 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011808 }
11809
Cody Kesting652e3ec2020-05-21 12:08:21 -070011810 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11811 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11812 // Data Stall information as a DataStallReportParcelable and passing to
11813 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11814 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011815 final DataStallReportParcelable p = new DataStallReportParcelable();
11816 p.timestampMillis = timestampMillis;
11817 p.detectionMethod = detectionMethod;
11818
11819 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11820 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11821 }
11822 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11823 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11824 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11825 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11826 }
11827
Serik Beketayevec8ad212020-12-07 22:43:07 -080011828 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011829 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011830
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011831 /**
11832 * Class to hold the information for network activity change event from idle timers
11833 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11834 */
11835 private static final class NetworkActivityParams {
11836 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011837 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
11838 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011839 public final int label;
11840 public final long timestampNs;
11841 // Uid represents the uid that was responsible for waking the radio.
11842 // -1 for no uid and uid is -1 if isActive is false.
11843 public final int uid;
11844
11845 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11846 this.isActive = isActive;
11847 this.label = label;
11848 this.timestampNs = timestampNs;
11849 this.uid = uid;
11850 }
11851 }
11852
lucaslin66f44212021-02-23 01:12:55 +080011853 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11854 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011855 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011856 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011857 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11858 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011859 }
lucaslin37a16d92021-01-21 19:48:09 +080011860
11861 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011862 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011863 mHandler.post(() -> {
11864 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011865 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011866 }
11867 });
lucaslin37a16d92021-01-21 19:48:09 +080011868 }
11869
11870 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011871 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011872 mHandler.post(() -> {
11873 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011874 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011875 }
11876 });
lucaslin66f44212021-02-23 01:12:55 +080011877 }
11878 }
11879
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011880 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080011881 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11882
11883 /**
11884 * Class used for updating network activity tracking with netd and notify network activity
11885 * changes.
11886 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011887 @VisibleForTesting
11888 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011889 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011890 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011891 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011892 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011893 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11894 new RemoteCallbackList<>();
11895 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011896 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011897 // If there is no default network, default network is considered active to keep the existing
11898 // behavior. Initial value is used until first connect to the default network.
11899 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011900 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011901 // Key is netId. Value is configured idle timer information.
11902 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011903 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011904 // Store netIds of Wi-Fi networks whose idletimers report that they are active
11905 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
11906 // Store netIds of cellular networks whose idletimers report that they are active
11907 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011908
Chalard Jean46bfbf02022-02-02 00:56:25 +090011909 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011910 public final int timeout;
11911 public final int transportType;
11912
11913 IdleTimerParams(int timeout, int transport) {
11914 this.timeout = timeout;
11915 this.transportType = transport;
11916 }
11917 }
11918
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011919 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011920 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011921 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011922 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011923 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011924 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011925 }
11926
11927 private void ensureRunningOnConnectivityServiceThread() {
11928 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11929 throw new IllegalStateException("Not running on ConnectivityService thread: "
11930 + Thread.currentThread().getName());
11931 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011932 }
11933
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011934 /**
11935 * Update network activity and call BatteryStats to update radio power state if the
11936 * mobile or Wi-Fi activity is changed.
11937 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
11938 * mobile network is active since BatteryStatsService only maintains a single power state
11939 * for the mobile network.
11940 * The Wi-Fi network is also the same.
11941 *
11942 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
11943 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
11944 * transports.
11945 */
11946 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
11947 final boolean isActive, final int uid) {
11948 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
11949 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
11950 + transportType);
11951 return;
11952 }
11953 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
11954 ? mActiveWifiNetworks : mActiveCellularNetworks;
11955
11956 final boolean wasEmpty = activeNetworks.isEmpty();
11957 if (isActive) {
11958 activeNetworks.add(netId);
11959 } else {
11960 activeNetworks.remove(netId);
11961 }
11962
11963 if (wasEmpty != activeNetworks.isEmpty()) {
11964 updateRadioPowerState(isActive, transportType, uid);
11965 }
11966 }
11967
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011968 private void handleDefaultNetworkActivity(final int transportType,
11969 final boolean isActive, final long timestampNs) {
11970 mIsDefaultNetworkActive = isActive;
11971 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
11972 isActive, timestampNs);
11973 if (isActive) {
11974 reportNetworkActive();
11975 }
11976 }
11977
11978 private void handleReportNetworkActivityWithNetIdLabel(
11979 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011980 final int netId = activityParams.label;
11981 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011982 if (idleTimerParams == null) {
11983 // This network activity change is not tracked anymore
11984 // This can happen if netd callback post activity change event message but idle
11985 // timer is removed before processing this message.
11986 return;
11987 }
11988 // TODO: if a network changes transports, storing the transport type in the
11989 // IdleTimerParams is not correct. Consider getting it from the network's
11990 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011991 final int transportType = idleTimerParams.transportType;
11992 maybeUpdateRadioPowerState(netId, transportType,
11993 activityParams.isActive, activityParams.uid);
11994
11995 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
11996 // This activity change is not for the default network.
11997 return;
11998 }
11999
12000 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012001 activityParams.timestampNs);
12002 }
12003
12004 private void handleReportNetworkActivityWithTransportTypeLabel(
12005 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012006 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012007 // This activity change is not for the current default network.
12008 // This can happen if netd callback post activity change event message but
12009 // the default network is lost before processing this message.
12010 return;
12011 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012012 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
12013 activityParams.timestampNs);
12014 }
12015
12016 /**
12017 * Handle network activity change
12018 */
12019 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
12020 ensureRunningOnConnectivityServiceThread();
12021 if (mTrackMultiNetworkActivities) {
12022 handleReportNetworkActivityWithNetIdLabel(activityParams);
12023 } else {
12024 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080012025 }
12026 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012027
lucaslin1193a5d2021-01-21 02:04:15 +080012028 private void reportNetworkActive() {
12029 final int length = mNetworkActivityListeners.beginBroadcast();
12030 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
12031 try {
12032 for (int i = 0; i < length; i++) {
12033 try {
12034 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
12035 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012036 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080012037 }
12038 }
12039 } finally {
12040 mNetworkActivityListeners.finishBroadcast();
12041 }
12042 }
12043
lucaslin1a8b4c62021-01-21 02:02:55 +080012044 // This is deprecated and only to support legacy use cases.
12045 private int transportTypeToLegacyType(int type) {
12046 switch (type) {
12047 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012048 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080012049 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012050 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080012051 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012052 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080012053 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012054 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080012055 default:
12056 loge("Unexpected transport in transportTypeToLegacyType: " + type);
12057 }
12058 return ConnectivityManager.TYPE_NONE;
12059 }
12060
12061 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12062 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12063 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12064 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12065 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12066 final long ident = Binder.clearCallingIdentity();
12067 try {
12068 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12069 RECEIVE_DATA_ACTIVITY_CHANGE,
12070 null /* resultReceiver */,
12071 null /* scheduler */,
12072 0 /* initialCode */,
12073 null /* initialData */,
12074 null /* initialExtra */);
12075 } finally {
12076 Binder.restoreCallingIdentity(ident);
12077 }
12078 }
12079
12080 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012081 * Get idle timer label
12082 */
12083 @VisibleForTesting
12084 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12085 final int netId, final int transportType) {
12086 return trackMultiNetworkActivities ? netId : transportType;
12087 }
12088
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012089 private boolean maybeCreateIdleTimer(
12090 String iface, int netId, int timeout, int transportType) {
12091 if (timeout <= 0 || iface == null) return false;
12092 try {
12093 final String label = Integer.toString(getIdleTimerLabel(
12094 mTrackMultiNetworkActivities, netId, transportType));
12095 mNetd.idletimerAddInterface(iface, timeout, label);
12096 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12097 return true;
12098 } catch (Exception e) {
12099 loge("Exception in createIdleTimer", e);
12100 return false;
12101 }
12102 }
12103
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012104 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012105 * Setup data activity tracking for the given network.
12106 *
12107 * Every {@code setupDataActivityTracking} should be paired with a
12108 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012109 *
12110 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012111 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012112 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012113 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012114 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012115 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012116
12117 final int timeout;
12118 final int type;
12119
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012120 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12121 // Do not track VPN network.
12122 return false;
12123 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012124 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12125 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012126 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012127 10);
12128 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12129 } else if (networkAgent.networkCapabilities.hasTransport(
12130 NetworkCapabilities.TRANSPORT_WIFI)) {
12131 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012132 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012133 15);
12134 type = NetworkCapabilities.TRANSPORT_WIFI;
12135 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012136 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012137 }
12138
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012139 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12140 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12141 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12142 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12143 // state only about a network that has an idletimer.
12144 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012145 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012146 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012147 }
12148
12149 /**
12150 * Remove data activity tracking when network disconnects.
12151 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012152 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12153 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012154 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012155 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012156 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12157
lucaslinb961efc2021-01-21 02:03:17 +080012158 if (iface == null) return;
12159
12160 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012161 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12162 // Do not track VPN network.
12163 return;
12164 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012165 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12166 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12167 type = NetworkCapabilities.TRANSPORT_WIFI;
12168 } else {
12169 return; // do not track any other networks
12170 }
12171
12172 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012173 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012174 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012175 if (params == null) {
12176 // IdleTimer is not added if the configured timeout is 0 or negative value
12177 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012178 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012179 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012180 final String label = Integer.toString(getIdleTimerLabel(
12181 mTrackMultiNetworkActivities, netId, params.transportType));
12182 // The call fails silently if no idle timer setup for this interface
12183 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012184 } catch (Exception e) {
12185 // You shall not crash!
12186 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012187 }
12188 }
12189
Motomu Utsumi6225d572023-05-29 15:08:57 +090012190 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12191 boolean hasIdleTimer) {
12192 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012193 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012194 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012195 // If only the default network is tracked, callbacks are called only when the
12196 // network has the idle timer.
12197 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012198 reportNetworkActive();
12199 }
12200 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012201 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012202 // If there is no default network, default network is considered active to keep the
12203 // existing behavior.
12204 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090012205 }
12206 }
12207
lucaslin1a8b4c62021-01-21 02:02:55 +080012208 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012209 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012210 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012211 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012212 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012213 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012214 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12215 // first connected and remove when the network is disconnected.
12216 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12217 // becomes the default network and remove when the network becomes no longer the default
12218 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012219 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012220 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012221 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012222 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012223 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012224 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012225 removeDataActivityTracking(oldNetwork);
12226 }
12227 }
lucaslinb961efc2021-01-21 02:03:17 +080012228
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012229 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012230 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12231 switch (transportType) {
12232 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012233 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012234 break;
12235 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012236 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012237 break;
12238 default:
12239 logw("Untracked transport type:" + transportType);
12240 }
12241 }
lucaslin1193a5d2021-01-21 02:04:15 +080012242
12243 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012244 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012245 }
12246
12247 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12248 mNetworkActivityListeners.register(l);
12249 }
12250
12251 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12252 mNetworkActivityListeners.unregister(l);
12253 }
lucaslin012f7a12021-01-21 02:04:35 +080012254
12255 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012256 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012257 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012258 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012259 pw.println("Idle timers:");
12260 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012261 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12262 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12263 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012264 pw.print(" timeout="); pw.print(params.timeout);
12265 pw.print(" type="); pw.println(params.transportType);
12266 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012267 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12268 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012269 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012270 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12271 // be accessed from handler thread, except dump(). As dump() is never called in
12272 // normal usage, it would be needlessly expensive to lock the collection only for
12273 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012274 // So catching the exception and logging.
12275 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012276 }
12277 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012278 }
James Mattis47db0582021-01-01 14:13:35 -080012279
Daniel Brightf9e945b2020-06-15 16:10:01 -070012280 /**
12281 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12282 *
12283 * @param socketInfo the socket information
12284 * @param callback the callback to register
12285 */
12286 @Override
12287 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12288 @NonNull final IQosCallback callback) {
12289 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12290 if (nai == null || nai.networkCapabilities == null) {
12291 try {
12292 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12293 } catch (final RemoteException ex) {
12294 loge("registerQosCallbackInternal: RemoteException", ex);
12295 }
12296 return;
12297 }
12298 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12299 }
12300
12301 /**
12302 * Register a {@link IQosCallback} with base {@link QosFilter}.
12303 *
12304 * @param filter the filter to register
12305 * @param callback the callback to register
12306 * @param nai the agent information related to the filter's network
12307 */
12308 @VisibleForTesting
12309 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12310 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012311 Objects.requireNonNull(filter, "filter must be non-null");
12312 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012313
12314 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012315 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12316 // on this network is unregistered when the app loses permission or b) no QoS
12317 // callbacks are sent for restricted networks unless the app currently has permission
12318 // to access restricted networks.
12319 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012320 }
12321 mQosCallbackTracker.registerCallback(callback, filter, nai);
12322 }
12323
12324 /**
12325 * Unregisters the given callback.
12326 *
12327 * @param callback the callback to unregister
12328 */
12329 @Override
12330 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012331 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012332 mQosCallbackTracker.unregisterCallback(callback);
12333 }
James Mattis47db0582021-01-01 14:13:35 -080012334
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012335 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12336 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12337 // Enterprise device can be fully managed like device owner and such use case
12338 // also should be supported. Calling app check for work profile and fully managed device
12339 // is already done in DevicePolicyManager.
12340 // This check is an extra caution to be sure device is fully managed or not.
12341 final UserManager um = mContext.getSystemService(UserManager.class);
12342 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12343 if (um.isManagedProfile(profile.getIdentifier())) {
12344 return true;
12345 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012346 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012347 return false;
12348 }
12349
James Mattis45d81842021-01-10 14:24:24 -080012350 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012351 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012352 *
12353 * See the documentation for the individual preferences for a description of the supported
12354 * behaviors.
12355 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012356 * @param profile If the device owner is set, any profile is allowed.
12357 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012358 * @param preferences the list of profile network preferences for the
12359 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012360 * @param listener an optional listener to listen for completion of the operation.
12361 */
12362 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012363 public void setProfileNetworkPreferences(
12364 @NonNull final UserHandle profile,
12365 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012366 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012367 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012368 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012369
12370 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012371 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12372 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12373 .build();
12374 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012375 }
12376
paulhu3ffffe72021-09-16 10:15:22 +080012377 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012378 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012379 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012380 }
12381 if (profile.getIdentifier() < 0) {
12382 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12383 + "UserHandle.CURRENT not supported)");
12384 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012385 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12386 throw new IllegalArgumentException("Profile must be a managed profile "
12387 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012388 }
paulhuaa0743d2021-05-26 21:56:03 +080012389
Chalard Jean0606fc82022-12-14 20:34:43 +090012390 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012391 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012392 for (final ProfileNetworkPreference preference : preferences) {
12393 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012394 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012395 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012396 switch (preference.getPreference()) {
12397 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12398 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012399 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012400 if (preference.getPreferenceEnterpriseId() != 0) {
12401 throw new IllegalArgumentException(
12402 "Invalid enterprise identifier in setProfileNetworkPreferences");
12403 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012404 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012405 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12406 blockingNonEnterprise = true;
12407 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012408 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12409 allowFallback = false;
12410 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012411 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012412 // This code is needed even though there is a check later on,
12413 // because isRangeAlreadyInPreferenceList assumes that every preference
12414 // has a UID list.
12415 if (hasDefaultPreference) {
12416 throw new IllegalArgumentException(
12417 "Default profile preference should not be set along with other "
12418 + "preference");
12419 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012420 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12421 throw new IllegalArgumentException(
12422 "Invalid enterprise identifier in setProfileNetworkPreferences");
12423 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012424 final Set<UidRange> uidRangeSet =
12425 getUidListToBeAppliedForNetworkPreference(profile, preference);
12426 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12427 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12428 } else {
12429 throw new IllegalArgumentException(
12430 "Overlapping uid range in setProfileNetworkPreferences");
12431 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012432 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012433 nc.addEnterpriseId(
12434 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012435 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12436 break;
12437 default:
12438 throw new IllegalArgumentException(
12439 "Invalid preference in setProfileNetworkPreferences");
12440 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012441 preferenceList.add(new ProfileNetworkPreferenceInfo(
12442 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012443 if (hasDefaultPreference && preferenceList.size() > 1) {
12444 throw new IllegalArgumentException(
12445 "Default profile preference should not be set along with other preference");
12446 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012447 }
12448 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012449 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012450 }
12451
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012452 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12453 @NonNull final UserHandle profile,
12454 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12455 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012456 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12457 profileNetworkPreference.getIncludedUids());
12458
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012459 if (uidRangeSet.size() > 0) {
12460 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12461 throw new IllegalArgumentException(
12462 "Allow uid range is outside the uid range of profile.");
12463 }
12464 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012465 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012466 profileNetworkPreference.getExcludedUids());
12467 if (disallowUidRangeSet.size() > 0) {
12468 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12469 throw new IllegalArgumentException(
12470 "disallow uid range is outside the uid range of profile.");
12471 }
12472 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12473 disallowUidRangeSet);
12474 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012475 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012476 uidRangeSet.add(profileUids);
12477 }
12478 }
12479 return uidRangeSet;
12480 }
12481
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012482 private boolean isEnterpriseIdentifierValid(
12483 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012484 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012485 return true;
12486 }
12487 return false;
12488 }
12489
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012490 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012491 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012492 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012493 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012494 // The NRI for a user should contain the request for capabilities.
12495 // If fallback to default network is needed then NRI should include
12496 // the request for the default network. Create an image of it to
12497 // have the correct UIDs in it (also a request can only be part of one NRI, because
12498 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012499 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12500 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012501 if (pref.allowFallback) {
12502 nrs.add(createDefaultInternetRequestForTransport(
12503 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12504 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012505 if (VDBG) {
12506 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12507 pref.capabilities.getUids()));
12508 }
12509
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012510 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012511 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012512 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012513 result.add(nri);
12514 }
12515 return result;
12516 }
12517
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012518 /**
12519 * Compare if the given UID range sets have the same UIDs.
12520 *
12521 */
12522 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012523 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012524 @NonNull Set<UidRange> uidRangeSet) {
12525 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12526 return false;
12527 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012528 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012529 if (UidRangeUtils.doesRangeSetOverlap(
12530 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12531 return true;
12532 }
12533 }
12534 return false;
12535 }
12536
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012537 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012538 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012539 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012540 /*
12541 * handleSetProfileNetworkPreference is always called for single user.
12542 * preferenceList only contains preferences for different uids within the same user
12543 * (enforced by getUidListToBeAppliedForNetworkPreference).
12544 * Clear all the existing preferences for the user before applying new preferences.
12545 *
12546 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012547 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12548 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012549 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12550 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012551
paulhu74128522021-09-28 02:29:03 +000012552 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12553 addPerAppDefaultNetworkRequests(
12554 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012555 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012556
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012557 // Finally, rematch.
12558 rematchAllNetworksAndRequests();
12559
12560 if (null != listener) {
12561 try {
12562 listener.onComplete();
12563 } catch (RemoteException e) {
12564 loge("Listener for setProfileNetworkPreference has died");
12565 }
12566 }
12567 }
12568
paulhu51f77dc2021-06-07 02:34:20 +000012569 @VisibleForTesting
12570 @NonNull
12571 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12572 @NonNull final Set<Integer> uids) {
12573 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12574 if (uids.size() == 0) {
12575 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12576 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12577 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12578 return nris;
12579 }
12580
12581 final List<NetworkRequest> requests = new ArrayList<>();
12582 // The NRI should be comprised of two layers:
12583 // - The request for the mobile network preferred.
12584 // - The request for the default network, for fallback.
12585 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012586 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012587 requests.add(createDefaultInternetRequestForTransport(
12588 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12589 final Set<UidRange> ranges = new ArraySet<>();
12590 for (final int uid : uids) {
12591 ranges.add(new UidRange(uid, uid));
12592 }
12593 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012594 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012595 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012596 return nris;
12597 }
12598
12599 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012600 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012601 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12602 addPerAppDefaultNetworkRequests(
12603 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012604 // Finally, rematch.
12605 rematchAllNetworksAndRequests();
12606 }
12607
Patrick Rohr2857ac42022-01-21 14:58:16 +010012608 private void handleIngressRateLimitChanged() {
12609 final long oldIngressRateLimit = mIngressRateLimit;
12610 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12611 mContext);
12612 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12613 if (canNetworkBeRateLimited(networkAgent)) {
12614 // If rate limit has previously been enabled, remove the old limit first.
12615 if (oldIngressRateLimit >= 0) {
12616 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12617 }
12618 if (mIngressRateLimit >= 0) {
12619 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12620 mIngressRateLimit);
12621 }
12622 }
12623 }
12624 }
12625
12626 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012627 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012628 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012629
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012630 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12631 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12632 // internet connectivity can be rate limited.
12633 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12634 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012635 return false;
12636 }
12637
12638 final String iface = networkAgent.linkProperties.getInterfaceName();
12639 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012640 // This may happen in tests, but if there is no interface then there is nothing that
12641 // can be rate limited.
12642 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012643 return false;
12644 }
12645 return true;
12646 }
12647
James Mattis45d81842021-01-10 14:24:24 -080012648 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012649 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12650 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012651 }
12652
12653 /**
12654 * Used by automotive devices to set the network preferences used to direct traffic at an
12655 * application level as per the given OemNetworkPreferences. An example use-case would be an
12656 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12657 * vehicle via a particular network.
12658 *
12659 * Calling this will overwrite the existing preference.
12660 *
James Mattisda32cfe2021-01-26 16:23:52 -080012661 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012662 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012663 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012664 */
James Mattis47db0582021-01-01 14:13:35 -080012665 @Override
James Mattis45d81842021-01-10 14:24:24 -080012666 public void setOemNetworkPreference(
12667 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012668 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012669
James Mattisfa270db2021-05-31 17:11:10 -070012670 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12671 // Only bypass the permission/device checks if this is a valid test request.
12672 if (isValidTestOemNetworkPreference(preference)) {
12673 enforceManageTestNetworksPermission();
12674 } else {
12675 enforceAutomotiveDevice();
12676 enforceOemNetworkPreferencesPermission();
12677 validateOemNetworkPreferences(preference);
12678 }
James Mattis45d81842021-01-10 14:24:24 -080012679
James Mattis45d81842021-01-10 14:24:24 -080012680 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12681 new Pair<>(preference, listener)));
12682 }
12683
James Mattisfa270db2021-05-31 17:11:10 -070012684 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012685 * Sets the specified UIDs to get/receive the VPN as the only default network.
12686 *
12687 * Calling this will overwrite the existing network preference for this session, and the
12688 * specified UIDs won't get any default network when no VPN is connected.
12689 *
12690 * @param session The VPN session which manages the passed UIDs.
12691 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12692 * setting for this session if the array is empty. Null is not allowed, the
12693 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12694 * @hide
12695 */
12696 @Override
12697 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12698 Objects.requireNonNull(ranges);
12699 enforceNetworkStackOrSettingsPermission();
12700 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12701 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12702 throw new IllegalArgumentException(
12703 "setVpnNetworkPreference: Passed UID ranges overlap");
12704 }
12705
12706 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12707 new VpnNetworkPreferenceInfo(session,
12708 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12709 }
12710
12711 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12712 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12713
12714 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12715 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12716
12717 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12718 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12719 // Finally, rematch.
12720 rematchAllNetworksAndRequests();
12721 }
12722
12723 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12724 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12725 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12726 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12727 final List<NetworkRequest> requests = new ArrayList<>();
12728 // Request VPN only, so other networks won't be the fallback options when VPN is not
12729 // connected temporarily.
12730 requests.add(createVpnRequest());
12731 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12732 setNetworkRequestUids(requests, uidRanges);
12733 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12734 }
12735 return nris;
12736 }
12737
12738 /**
James Mattisfa270db2021-05-31 17:11:10 -070012739 * Check the validity of an OEM network preference to be used for testing purposes.
12740 * @param preference the preference to validate
12741 * @return true if this is a valid OEM network preference test request.
12742 */
12743 private boolean isValidTestOemNetworkPreference(
12744 @NonNull final OemNetworkPreferences preference) {
12745 // Allow for clearing of an existing OemNetworkPreference used for testing.
12746 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12747 // changes after this check is complete. This is an unlikely scenario as calling of this API
12748 // is controlled by the OEM therefore the added complexity is not worth adding given those
12749 // circumstances. That said, it is an edge case to be aware of hence this comment.
12750 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12751 && isTestOemNetworkPreference(mOemNetworkPreferences);
12752 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12753 }
12754
12755 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12756 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12757 return prefMap.size() == 1
12758 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12759 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12760 }
12761
James Mattis45d81842021-01-10 14:24:24 -080012762 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12763 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12764 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012765 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12766 throw new IllegalArgumentException(
12767 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12768 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012769 }
12770 }
12771 }
12772
12773 private void handleSetOemNetworkPreference(
12774 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012775 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012776 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12777 if (DBG) {
12778 log("set OEM network preferences :" + preference.toString());
12779 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012780
James Mattiscb1e0362021-04-06 17:07:42 -070012781 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012782 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12783 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12784 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012785 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012786
12787 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012788 try {
12789 listener.onComplete();
12790 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012791 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012792 }
James Mattis45d81842021-01-10 14:24:24 -080012793 }
12794 }
12795
paulhu74128522021-09-28 02:29:03 +000012796 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012797 // Skip the requests which are set by other network preference. Because the uid range rules
12798 // should stay in netd.
12799 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012800 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012801 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012802 }
12803
James Mattis3ce3d3c2021-02-09 18:18:28 -080012804 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12805 ensureRunningOnConnectivityServiceThread();
12806 mDefaultNetworkRequests.addAll(nris);
12807 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12808 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012809 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012810 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12811 nrisToRegister.addAll(
12812 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12813 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012814 }
12815
12816 /**
12817 * All current requests that are tracking the default network need to be assessed as to whether
12818 * or not the current set of per-application default requests will be changing their default
12819 * network. If so, those requests will need to be updated so that they will send callbacks for
12820 * default network changes at the appropriate time. Additionally, those requests tracking the
12821 * default that were previously updated by this flow will need to be reassessed.
12822 * @return the nris which will need to be updated.
12823 */
12824 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12825 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12826 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12827 // same nri in the map's values for each of its NetworkRequest objects.
12828 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012829 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012830 // Include this nri if it is currently being tracked.
12831 if (isPerAppTrackedNri(nri)) {
12832 defaultCallbackRequests.add(nri);
12833 continue;
12834 }
12835 // We only track callbacks for requests tracking the default.
12836 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12837 continue;
12838 }
12839 // Include this nri if it will be tracked by the new per-app default requests.
12840 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012841 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012842 if (isNriGoingToBeTracked) {
12843 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012844 }
12845 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012846 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012847 }
12848
James Mattis3ce3d3c2021-02-09 18:18:28 -080012849 /**
12850 * Create nris for those network requests that are currently tracking the default network that
12851 * are being controlled by a per-application default.
12852 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12853 * foundation when creating the nri. Important items include the calling uid's original
12854 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12855 * requests are assumed to have already been validated as needing to be updated.
12856 * @return the Set of nris to use when registering network requests.
12857 */
12858 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12859 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12860 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12861 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12862 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012863 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012864
Chalard Jean9473c982021-07-29 20:03:04 +090012865 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012866 if (trackingNri == mDefaultRequest) {
12867 callbackRequestsToRegister.add(new NetworkRequestInfo(
12868 callbackRequest,
12869 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12870 continue;
12871 }
12872
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012873 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012874 callbackRequestsToRegister.add(new NetworkRequestInfo(
12875 callbackRequest,
12876 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012877 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012878 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012879 }
12880 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012881 }
12882
Chalard Jean17215832021-03-01 14:06:28 +090012883 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12884 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012885 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012886 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012887 }
12888 }
12889
James Mattis45d81842021-01-10 14:24:24 -080012890 /**
12891 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12892 */
12893 @VisibleForTesting
12894 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012895 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012896 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012897 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012898 final SparseArray<Set<Integer>> uids =
12899 createUidsFromOemNetworkPreferences(preference);
12900 for (int i = 0; i < uids.size(); i++) {
12901 final int key = uids.keyAt(i);
12902 final Set<Integer> value = uids.valueAt(i);
12903 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12904 // No need to add an nri without any requests.
12905 if (0 == nri.mRequests.size()) {
12906 continue;
12907 }
12908 nris.add(nri);
12909 }
12910
12911 return nris;
12912 }
12913
12914 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12915 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012916 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012917 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012918 final List<UserHandle> users =
12919 mContext.getSystemService(UserManager.class).getUserHandles(true);
12920 if (null == users || users.size() == 0) {
12921 if (VDBG || DDBG) {
12922 log("No users currently available for setting the OEM network preference.");
12923 }
James Mattisb6b6a432021-06-01 22:30:36 -070012924 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012925 }
James Mattis45d81842021-01-10 14:24:24 -080012926 for (final Map.Entry<String, Integer> entry :
12927 preference.getNetworkPreferences().entrySet()) {
12928 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012929 // Add the rules for all users as this policy is device wide.
12930 for (final UserHandle user : users) {
12931 try {
12932 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12933 if (!prefToUids.contains(pref)) {
12934 prefToUids.put(pref, new ArraySet<>());
12935 }
12936 prefToUids.get(pref).add(uid);
12937 } catch (PackageManager.NameNotFoundException e) {
12938 // Although this may seem like an error scenario, it is ok that uninstalled
12939 // packages are sent on a network preference as the system will watch for
12940 // package installations associated with this network preference and update
12941 // accordingly. This is done to minimize race conditions on app install.
12942 continue;
James Mattis45d81842021-01-10 14:24:24 -080012943 }
James Mattis45d81842021-01-10 14:24:24 -080012944 }
12945 }
James Mattisb6b6a432021-06-01 22:30:36 -070012946 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012947 }
12948
12949 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12950 @OemNetworkPreferences.OemNetworkPreference final int preference,
12951 @NonNull final Set<Integer> uids) {
12952 final List<NetworkRequest> requests = new ArrayList<>();
12953 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12954 switch (preference) {
12955 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12956 requests.add(createUnmeteredNetworkRequest());
12957 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012958 requests.add(createDefaultInternetRequestForTransport(
12959 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012960 break;
12961 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12962 requests.add(createUnmeteredNetworkRequest());
12963 requests.add(createOemPaidNetworkRequest());
12964 break;
12965 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12966 requests.add(createOemPaidNetworkRequest());
12967 break;
12968 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12969 requests.add(createOemPrivateNetworkRequest());
12970 break;
James Mattisfa270db2021-05-31 17:11:10 -070012971 case OEM_NETWORK_PREFERENCE_TEST:
12972 requests.add(createUnmeteredNetworkRequest());
12973 requests.add(createTestNetworkRequest());
12974 requests.add(createDefaultRequest());
12975 break;
12976 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12977 requests.add(createTestNetworkRequest());
12978 break;
James Mattis45d81842021-01-10 14:24:24 -080012979 default:
12980 // This should never happen.
12981 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12982 + " called with invalid preference of " + preference);
12983 }
12984
James Mattisfa270db2021-05-31 17:11:10 -070012985 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012986 for (final int uid : uids) {
12987 ranges.add(new UidRange(uid, uid));
12988 }
12989 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012990 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012991 }
12992
12993 private NetworkRequest createUnmeteredNetworkRequest() {
12994 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12995 .addCapability(NET_CAPABILITY_NOT_METERED)
12996 .addCapability(NET_CAPABILITY_VALIDATED);
12997 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12998 }
12999
13000 private NetworkRequest createOemPaidNetworkRequest() {
13001 // NET_CAPABILITY_OEM_PAID is a restricted capability.
13002 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13003 .addCapability(NET_CAPABILITY_OEM_PAID)
13004 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13005 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13006 }
13007
13008 private NetworkRequest createOemPrivateNetworkRequest() {
13009 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
13010 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13011 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
13012 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13013 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13014 }
13015
13016 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070013017 final NetworkCapabilities netcap = new NetworkCapabilities();
13018 netcap.addCapability(NET_CAPABILITY_INTERNET);
13019 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
13020 return netcap;
13021 }
13022
13023 private NetworkRequest createTestNetworkRequest() {
13024 final NetworkCapabilities netcap = new NetworkCapabilities();
13025 netcap.clearAll();
13026 netcap.addTransportType(TRANSPORT_TEST);
13027 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080013028 }
James Mattis47db0582021-01-01 14:13:35 -080013029 }
markchien738ad912021-12-09 18:15:45 +080013030
Junyu Lai38c75032023-12-04 07:52:19 +000013031 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080013032 @Override
Junyu Laidf210362023-10-24 02:47:50 +000013033 public void setDataSaverEnabled(final boolean enable) {
13034 enforceNetworkStackOrSettingsPermission();
13035 try {
13036 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
13037 if (!ret) {
13038 throw new IllegalStateException("Error when changing iptables: " + enable);
13039 }
13040 } catch (RemoteException e) {
13041 // Lack of permission or binder errors.
13042 throw new IllegalStateException(e);
13043 }
Ken Chen24330172023-10-20 13:02:14 +080013044
13045 try {
13046 mBpfNetMaps.setDataSaverEnabled(enable);
13047 } catch (ServiceSpecificException | UnsupportedOperationException e) {
13048 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
13049 }
Junyu Laidf210362023-10-24 02:47:50 +000013050 }
13051
13052 @Override
markchien738ad912021-12-09 18:15:45 +080013053 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
13054 enforceNetworkStackOrSettingsPermission();
13055
13056 try {
13057 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013058 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013059 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013060 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013061 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013062 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013063 throw new IllegalStateException(e);
13064 }
13065 }
13066
13067 @Override
13068 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13069 enforceNetworkStackOrSettingsPermission();
13070
13071 try {
13072 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013073 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013074 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013075 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013076 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013077 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013078 throw new IllegalStateException(e);
13079 }
13080 }
markchiene1561fa2021-12-09 22:00:56 +080013081
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013082 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13083 throws PackageManager.NameNotFoundException {
13084 final PackageManager pm = mContext.getPackageManager();
13085 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13086 if (appId < Process.FIRST_APPLICATION_UID) {
13087 throw new RuntimeException("Can't set package firewall rule for system app "
13088 + packageName + " with appId " + appId);
13089 }
13090 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13091 final int uid = uh.getUid(appId);
13092 setUidFirewallRule(chain, uid, rule);
13093 }
13094 return appId;
13095 }
13096
markchiene1561fa2021-12-09 22:00:56 +080013097 @Override
markchien3c04e662022-03-22 16:29:56 +080013098 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013099 enforceNetworkStackOrSettingsPermission();
13100
markchien3c04e662022-03-22 16:29:56 +080013101 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13102 int firewallRule = getFirewallRuleType(chain, rule);
13103
13104 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13105 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13106 }
13107
markchiene1561fa2021-12-09 22:00:56 +080013108 try {
markchien3c04e662022-03-22 16:29:56 +080013109 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013110 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013111 throw new IllegalStateException(e);
13112 }
13113 }
markchien98a6f952022-01-13 23:43:53 +080013114
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013115 private int getPackageFirewallRule(final int chain, final String packageName)
13116 throws PackageManager.NameNotFoundException {
13117 final PackageManager pm = mContext.getPackageManager();
13118 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13119 return getUidFirewallRule(chain, appId);
13120 }
13121
Motomu Utsumi900b8062023-01-19 16:16:49 +090013122 @Override
13123 public int getUidFirewallRule(final int chain, final int uid) {
13124 enforceNetworkStackOrSettingsPermission();
13125 return mBpfNetMaps.getUidRule(chain, uid);
13126 }
13127
markchien3c04e662022-03-22 16:29:56 +080013128 private int getFirewallRuleType(int chain, int rule) {
13129 final int defaultRule;
13130 switch (chain) {
13131 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013132 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13133 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013134 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013135 defaultRule = FIREWALL_RULE_ALLOW;
13136 break;
13137 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13138 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13139 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13140 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013141 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013142 defaultRule = FIREWALL_RULE_DENY;
13143 break;
13144 default:
13145 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13146 }
13147 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13148
13149 return rule;
13150 }
13151
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013152 private void closeSocketsForFirewallChainLocked(final int chain)
13153 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013154 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013155 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13156 // So, close all non-system socket owned by uids that are not explicitly allowed
13157 Set<Range<Integer>> ranges = new ArraySet<>();
13158 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13159 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13160 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13161 } else {
13162 // Denylist means the firewall allows all by default, uids must be explicitly denied
13163 // So, close socket owned by uids that are explicitly denied
13164 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13165 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13166 }
13167 }
13168
markchien98a6f952022-01-13 23:43:53 +080013169 @Override
13170 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13171 enforceNetworkStackOrSettingsPermission();
13172
13173 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013174 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013175 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013176 throw new IllegalStateException(e);
13177 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013178
Chalard Jeandf29a852023-05-29 17:02:43 +090013179 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013180 try {
13181 closeSocketsForFirewallChainLocked(chain);
13182 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13183 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13184 }
13185 }
markchien98a6f952022-01-13 23:43:53 +080013186 }
13187
markchien00a0bed2022-01-13 23:46:13 +080013188 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013189 public boolean getFirewallChainEnabled(final int chain) {
13190 enforceNetworkStackOrSettingsPermission();
13191
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013192 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013193 }
13194
13195 @Override
markchien00a0bed2022-01-13 23:46:13 +080013196 public void replaceFirewallChain(final int chain, final int[] uids) {
13197 enforceNetworkStackOrSettingsPermission();
13198
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013199 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013200 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013201
13202 @Override
13203 public IBinder getCompanionDeviceManagerProxyService() {
13204 enforceNetworkStackPermission(mContext);
13205 return mCdmps;
13206 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013207
13208 @Override
13209 public IBinder getRoutingCoordinatorService() {
13210 enforceNetworkStackPermission(mContext);
13211 return mRoutingCoordinatorService;
13212 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013213}