blob: 22120e90694b89dad0fbebeff9909f187392d92b [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Mark Fasheh7c999d82023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
Chalard Jeane0aaca52023-10-17 13:23:07 +090022import static android.content.pm.PackageManager.FEATURE_LEANBACK;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090023import static android.content.pm.PackageManager.FEATURE_WATCH;
24import static android.content.pm.PackageManager.FEATURE_WIFI;
25import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090026import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090027import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
29import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
34import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090035import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
36import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000037import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang9fe47be2021-06-08 13:11:45 +080038import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070039import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080040import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
41import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
42import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090043import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090044import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090045import static android.net.ConnectivityManager.TYPE_MOBILE;
46import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
48import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
49import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
50import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
51import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
52import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
53import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
54import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070055import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090056import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070057import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090058import static android.net.ConnectivityManager.TYPE_WIFI;
59import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070060import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070061import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080062import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080063import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080066import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040067import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
74import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080077import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080079import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
80import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080081import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090082import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090083import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080084import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
85import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080086import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
87import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
88import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090089import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090090import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060091import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070092import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080093import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090094import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070095import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
96import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070097import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080098import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +010099import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700100import static android.system.OsConstants.IPPROTO_TCP;
101import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900102
Junyu Lai155760b2023-10-05 14:51:00 +0800103import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
104import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
105import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
106import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
107import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Xiao Ma60142372022-07-16 17:30:20 +0900108import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800109import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800110import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
111import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
112import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900113import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900114
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800115import static java.util.Map.Entry;
116
Chalard Jean5b639762020-03-09 21:25:37 +0900117import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000118import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800119import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600120import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800121import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000122import android.app.ActivityManager;
123import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800124import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800125import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700126import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700127import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900128import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800129import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700130import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800131import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132import android.content.ContentResolver;
133import android.content.Context;
134import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700135import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800136import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900137import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700138import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800139import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900140import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900141import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700142import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800143import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800144import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900146import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800147import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900148import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800149import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900150import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800151import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700152import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900153import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800154import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800155import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800156import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800157import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800158import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900159import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900160import android.net.INetworkMonitor;
161import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900162import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900163import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700164import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800165import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900166import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900167import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900168import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800169import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900170import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900171import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100172import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800173import android.net.NativeNetworkConfig;
174import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800175import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700176import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700177import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900178import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700179import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800180import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700181import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900182import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900183import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000184import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900185import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700186import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900187import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700188import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900189import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700190import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800191import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900192import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700193import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000194import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800195import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900196import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800197import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400198import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700199import android.net.QosCallbackException;
200import android.net.QosFilter;
201import android.net.QosSocketFilter;
202import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700203import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800204import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800205import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900206import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400207import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800208import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800209import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400210import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800211import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900212import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900213import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900214import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900215import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800216import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900217import android.net.networkstack.ModuleNetworkStackClient;
218import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900219import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800220import android.net.resolv.aidl.DnsHealthEventParcel;
221import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
222import android.net.resolv.aidl.Nat64PrefixEventParcel;
223import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900224import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900225import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800226import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800227import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800228import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700229import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000230import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700232import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700233import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800234import android.os.Looper;
235import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700236import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700237import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900238import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800239import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700240import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700241import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800242import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700243import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900244import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900245import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700246import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700247import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400248import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800249import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900250import android.stats.connectivity.MeteredState;
251import android.stats.connectivity.RequestType;
252import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900253import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700254import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700255import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700256import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800257import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900258import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000259import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600260import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900261import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900262import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700263import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700264import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900265import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800266
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800267import androidx.annotation.RequiresApi;
268
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900269import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400270import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400271import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700272import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900273import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900274import com.android.metrics.ConnectionDurationForTransports;
275import com.android.metrics.ConnectionDurationPerTransports;
276import com.android.metrics.ConnectivitySampleMetricsHelper;
277import com.android.metrics.ConnectivityStateSample;
278import com.android.metrics.NetworkCountForTransports;
279import com.android.metrics.NetworkCountPerTransports;
280import com.android.metrics.NetworkDescription;
281import com.android.metrics.NetworkList;
282import com.android.metrics.NetworkRequestCount;
283import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800284import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900285import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800286import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000287import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900288import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800289import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900290import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900291import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100292import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900293import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
294import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900295import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800296import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800297import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100298import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000299import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800300import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
301import com.android.networkstack.apishim.ConstantsShim;
302import com.android.networkstack.apishim.common.BroadcastOptionsShim;
303import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900304import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900305import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000306import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900307import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800308import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800309import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900310import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900311import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900312import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500313import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700314import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900315import com.android.server.connectivity.FullScore;
Junyu Laif8dba342023-10-12 17:01:03 +0800316import com.android.server.connectivity.HandlerUtils;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900317import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900318import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000319import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100320import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700321import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900322import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700323import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600324import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900325import com.android.server.connectivity.NetworkNotificationManager;
326import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900327import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900328import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900329import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700330import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900331import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900332import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700333import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900334import com.android.server.connectivity.RoutingCoordinatorService;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800335import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000336import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800337import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600338
Josh Gao461a1222020-06-16 15:58:11 -0700339import libcore.io.IoUtils;
340
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900341import org.xmlpull.v1.XmlPullParserException;
342
The Android Open Source Project28527d22009-03-03 19:31:44 -0800343import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100344import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900345import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800346import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900347import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700348import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700349import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900350import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900351import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700352import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700353import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700354import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700355import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800356import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900357import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800358import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700359import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700360import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700361import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700362import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900363import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700364import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900365import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600366import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900367import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600368import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900369import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900370import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800371
372/**
373 * @hide
374 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800375public class ConnectivityService extends IConnectivityManager.Stub
376 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900377 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800378
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900379 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900380 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900381 private static final String NETWORK_ARG = "networks";
382 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800383 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900384
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900385 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900386 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
387 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800388
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900389 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700390
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100391 /**
392 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
393 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800394 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100395 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
396 * (preferably via runtime resource overlays).
397 */
398 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
399 "http://connectivitycheck.gstatic.com/generate_204";
400
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700401 // TODO: create better separation between radio types and network types
402
Robert Greenwalt2034b912009-08-12 16:08:25 -0700403 // how long to wait before switching back to a radio's default network
404 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
405 // system property that can override the above value
406 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
407 "android.telephony.apn-restore";
408
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900409 // How long to wait before putting up a "This network doesn't have an Internet connection,
410 // connect anyway?" dialog after the user selects a network that doesn't validate.
411 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
412
Chalard Jean5fb43c72022-09-08 19:03:14 +0900413 // How long to wait before considering that a network is bad in the absence of any form
414 // of connectivity (valid, partial, captive portal). If none has been detected after this
415 // delay, the stack considers this network bad, which may affect how it's handled in ranking
416 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900417 // Timeout in case the "actively prefer bad wifi" feature is on
418 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
419 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900420 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900421
junyulai0ac374f2020-12-14 18:41:52 +0800422 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900423 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
424 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800425 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700426
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800427 // Delimiter used when creating the broadcast delivery group for sending
428 // CONNECTIVITY_ACTION broadcast.
429 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
430
he_won.hwang881307a2022-03-15 21:23:52 +0900431 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900432 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900433
Daniel Brightf9e945b2020-06-15 16:10:01 -0700434 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900435 @VisibleForTesting
436 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700437
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900438 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700439 @VisibleForTesting
440 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900441
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900442 @VisibleForTesting
443 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800444 @VisibleForTesting
445 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900446 // True if the cell radio of the device is capable of time-sharing.
447 @VisibleForTesting
448 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900449
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800450 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800451 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800452 private final int mReleasePendingIntentDelayMs;
453
Chalard Jean46bfbf02022-02-02 00:56:25 +0900454 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900455
Motomu Utsumif360aa62023-01-30 17:52:20 +0900456 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700457
Chalard Jean9473c982021-07-29 20:03:04 +0900458 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800459 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700460 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800461 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700462
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900463 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700464
junyulaif2c67e42018-08-07 19:50:45 +0800465 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000466 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
467 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800468 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900469 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800470
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900471 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900472 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000473 private final int mWakeUpMark;
474 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000475 // The Context is created for UserHandle.ALL.
476 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900477 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900478 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700479 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700480 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800481
Chenbo Feng15416292018-11-08 17:36:21 -0800482 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800483 protected IDnsResolver mDnsResolver;
484 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800485 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700486 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900487 private final NetworkStatsManager mStatsManager;
488 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800489 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700490
Benedict Wong493e04b2018-11-09 14:45:34 -0800491 /**
492 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
493 * instances.
494 */
495 @GuardedBy("mTNSLock")
496 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800497 private final CompanionDeviceManagerProxyService mCdmps;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900498 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800499
500 private final Object mTNSLock = new Object();
501
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700502 private String mCurrentTcpBufferSizes;
503
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900504 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000505 new Class[] {
506 ConnectivityService.class,
507 NetworkAgent.class,
508 NetworkAgentInfo.class,
509 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900510
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500511 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400512 // Tear down networks that have no chance (e.g. even if validated) of becoming
513 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500514 // all networks have been rematched against all NetworkRequests.
515 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400516 // Don't reap networks. This should be passed when some networks have not yet been
517 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500518 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900519 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500520
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900521 private enum UnneededFor {
522 LINGER, // Determine whether this network is unneeded and should be lingered.
523 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
524 }
525
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700526 /**
paulhuaa0743d2021-05-26 21:56:03 +0800527 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800528 * should have priority. The order is passed to netd which will use it together
529 * with UID ranges to generate the corresponding IP rule. This serves to
530 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800531 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800532 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000533 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800534 *
paulhu48291862021-07-14 14:53:57 +0800535 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
536 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800537 */
paulhu48291862021-07-14 14:53:57 +0800538 // Used when sending to netd to code for "no order".
539 static final int PREFERENCE_ORDER_NONE = 0;
540 // Order for requests that don't code for a per-app preference. As it is
541 // out of the valid range, the corresponding order should be
542 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800543 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800544 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800545 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800546 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
547 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800548 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800549 static final int PREFERENCE_ORDER_OEM = 10;
550 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800551 // See {@link #setProfileNetworkPreference}.
552 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800553 static final int PREFERENCE_ORDER_PROFILE = 20;
554 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800555 // better scores are connected.
556 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800557 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800558 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900559 // Preference order that signifies the network shouldn't be set as a default network for
560 // the UIDs, only give them access to it. TODO : replace this with a boolean
561 // in NativeUidRangeConfig
562 @VisibleForTesting
563 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
564 // Bound for the lowest valid preference order.
565 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800566
567 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700568 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700569 * from one net to another. Clear happens when we get a new
570 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
571 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700572 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700573 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700574
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700575 /**
576 * used internally to reload global proxy settings
577 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700578 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700579
Robert Greenwalt34848c02011-03-25 13:09:25 -0700580 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400581 * PAC manager has received new port.
582 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800583 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400584
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700585 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900586 * used internally when registering NetworkProviders
587 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700588 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900589 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700590
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700591 /**
592 * used internally when registering NetworkAgents
593 * obj = Messenger
594 */
595 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
596
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700597 /**
598 * used to add a network request
599 * includes a NetworkRequestInfo
600 */
601 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
602
603 /**
604 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900605 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700606 * cancel it.
607 * includes a NetworkRequestInfo
608 */
609 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
610
611 /**
612 * used to add a network listener - no request
613 * includes a NetworkRequestInfo
614 */
615 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
616
617 /**
618 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400619 * arg1 = UID of caller
620 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700621 */
622 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
623
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700624 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900625 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700626 * obj = Messenger
627 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900628 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700629
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700630 /**
631 * used internally to expire a wakelock when transitioning
632 * from one net to another. Expire happens when we fail to find
633 * a new network (typically after 1 minute) -
634 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
635 * a replacement network.
636 */
637 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
638
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700639 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800640 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400641 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800642 */
643 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
644
645 /**
646 * used to remove a pending intent and its associated network request.
647 * arg1 = UID of caller
648 * obj = PendingIntent
649 */
650 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
651
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900652 /**
653 * used to specify whether a network should be used even if unvalidated.
654 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
655 * arg2 = whether to remember this choice in the future (1 or 0)
656 * obj = network
657 */
658 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
659
660 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700661 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900662 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700663 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900664
Paul Jensenc8873fc2015-06-17 14:15:39 -0400665 /**
666 * used to add a network listener with a pending intent
667 * obj = NetworkRequestInfo
668 */
669 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
670
Hugo Benichid6b510a2017-04-06 17:22:18 +0900671 /**
672 * used to specify whether a network should not be penalized when it becomes unvalidated.
673 */
674 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
675
676 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700677 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900678 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700679 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900680
Erik Kline31b4a9e2018-01-11 21:07:29 +0900681 // Handle changes in Private DNS settings.
682 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
683
dalyk1720e542018-03-05 12:42:22 -0500684 // Handle private DNS validation status updates.
685 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
686
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900687 /**
688 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
689 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800690 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
691 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
692 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900693 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900694 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900695
696 /**
697 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
698 * config was resolved.
699 * obj = PrivateDnsConfig
700 * arg2 = netid
701 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900702 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900703
704 /**
705 * Request ConnectivityService display provisioning notification.
706 * arg1 = Whether to make the notification visible.
707 * arg2 = NetID.
708 * obj = Intent to be launched when notification selected by user, null if !arg1.
709 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900710 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900711
712 /**
lucaslin2240ef62019-03-12 13:08:03 +0800713 * Used to specify whether a network should be used even if connectivity is partial.
714 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
715 * false)
716 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
717 * obj = network
718 */
lucaslin444d43a2020-02-20 16:56:59 +0800719 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800720
721 /**
lucasline117e2e2019-10-22 18:27:33 +0800722 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
723 * Both of the arguments are bitmasks, and the value of bits come from
724 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900725 * arg1 = unused
726 * arg2 = netId
727 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800728 */
lucaslin444d43a2020-02-20 16:56:59 +0800729 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800730
731 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900732 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
733 * arg1 = unused
734 * arg2 = netId
735 * obj = captive portal data
736 */
lucaslin444d43a2020-02-20 16:56:59 +0800737 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900738
739 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900740 * Used by setRequireVpnForUids.
741 * arg1 = whether the specified UID ranges are required to use a VPN.
742 * obj = Array of UidRange objects.
743 */
744 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
745
746 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900747 * Used internally when setting the default networks for OemNetworkPreferences.
748 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800749 */
750 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
751
752 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800753 * Used to indicate the system default network becomes active.
754 */
755 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
756
757 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900758 * Used internally when setting a network preference for a user profile.
759 * obj = Pair<ProfileNetworkPreference, Listener>
760 */
761 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
762
763 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000764 * Event to specify that reasons for why an uid is blocked changed.
765 * arg1 = uid
766 * arg2 = blockedReasons
767 */
768 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
769
770 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900771 * Event to register a new network offer
772 * obj = NetworkOffer
773 */
774 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
775
776 /**
777 * Event to unregister an existing network offer
778 * obj = INetworkOfferCallback
779 */
780 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
781
782 /**
paulhu51f77dc2021-06-07 02:34:20 +0000783 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
784 */
785 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
786
787 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800788 * Event to set temporary allow bad wifi within a limited time to override
789 * {@code config_networkAvoidBadWifi}.
790 */
791 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
792
793 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100794 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
795 */
796 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
797
798 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900799 * The initial evaluation period is over for this network.
800 *
801 * If no form of connectivity has been found on this network (valid, partial, captive portal)
802 * then the stack will now consider it to have been determined bad.
803 */
804 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
805
806 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000807 * Used internally when the user does not want the network from captive portal app.
808 * obj = Network
809 */
810 private static final int EVENT_USER_DOES_NOT_WANT = 58;
811
812 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000813 * Event to set VPN as preferred network for specific apps.
814 * obj = VpnNetworkPreferenceInfo
815 */
816 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
817
818 /**
chiachangwange0192a72023-02-06 13:25:01 +0000819 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
820 */
821 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
822
823 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000824 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
825 */
826 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
827
828 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900829 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
830 * should be shown.
831 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900832 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900833
834 /**
835 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
836 * should be hidden.
837 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900838 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900839
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800840 /**
841 * The maximum alive time to allow bad wifi configuration for testing.
842 */
843 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
844
Patrick Rohr2857ac42022-01-21 14:58:16 +0100845 /**
chiachangwange0192a72023-02-06 13:25:01 +0000846 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
847 * testing.
848 */
849 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
850
851 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100852 * The priority of the tc police rate limiter -- smaller value is higher priority.
853 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
854 */
855 private static final short TC_PRIO_POLICE = 1;
856
857 /**
858 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
859 */
860 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700861 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100862
Hugo Benichi47011212017-03-30 10:46:05 +0900863 private static String eventName(int what) {
864 return sMagicDecoderRing.get(what, Integer.toString(what));
865 }
866
paulhua10d8212020-11-10 15:32:56 +0800867 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900868 final DnsResolverServiceManager dsm = context.getSystemService(
869 DnsResolverServiceManager.class);
870 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800871 }
872
Cody Kesting73708bf2019-12-18 10:57:50 -0800873 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900874 @VisibleForTesting
875 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700876 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700877 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700878 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700879 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800880 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
881 @VisibleForTesting
882 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
883
Erik Kline32120082017-12-13 19:40:49 +0900884 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900885 @VisibleForTesting
886 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700887
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400888 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800889 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400890
Chalard Jean46bfbf02022-02-02 00:56:25 +0900891 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800892 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700893
Chalard Jean5d70ba42018-06-07 16:44:04 +0900894 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
895 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800896 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400897
Erik Kline05f2b402015-04-30 12:58:40 +0900898 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700899
Chalard Jean46bfbf02022-02-02 00:56:25 +0900900 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400901
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700902 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900903 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700904
Valentin Iftime9fa35092019-09-24 13:32:13 +0200905 private Set<String> mWolSupportedInterfaces;
906
Roshan Pius08c94fb2020-01-16 12:17:17 -0800907 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800908 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800909 private final AppOpsManager mAppOpsManager;
910
911 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400912
chiachangwang3d60bac2023-01-17 14:38:08 +0000913 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900914 private final QosCallbackTracker mQosCallbackTracker;
915 private final NetworkNotificationManager mNotifier;
916 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900917
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700918 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800919 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700920
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900921 // Sequence number for NetworkProvider IDs.
922 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
923 NetworkProvider.FIRST_PROVIDER_ID);
924
Erik Klineedf878b2015-07-09 18:24:03 +0900925 // NetworkRequest activity String log entries.
926 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
927 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
928
Hugo Benichid159fdd2016-07-11 11:05:12 +0900929 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900930 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900931 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
932
Hugo Benichi47011212017-03-30 10:46:05 +0900933 private static final int MAX_WAKELOCK_LOGS = 20;
934 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900935 private int mTotalWakelockAcquisitions = 0;
936 private int mTotalWakelockReleases = 0;
937 private long mTotalWakelockDurationMs = 0;
938 private long mMaxWakelockDurationMs = 0;
939 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900940
Hugo Benichi208c0102016-07-28 17:53:06 +0900941 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900942
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700943 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900944 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700945
Erik Kline95ecfee2016-10-02 18:02:14 +0900946 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900947 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900948
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900949 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800950 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
951 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800952
Patrick Rohr2857ac42022-01-21 14:58:16 +0100953 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
954 // configured via {@link
955 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
956 // Only the handler thread is allowed to access this field.
957 private long mIngressRateLimit = -1;
958
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900959 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
960 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900961 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900962 @GuardedBy("mSelfCertifiedCapabilityCache")
963 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
964 mSelfCertifiedCapabilityCache = new HashMap<>();
965
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900966 // Flag to enable the feature of closing frozen app sockets.
967 private final boolean mDestroyFrozenSockets;
968
969 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
970 private final boolean mDelayDestroyFrozenSockets;
971
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900972 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
973 private final boolean mAllowSysUiConnectivityReports;
974
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900975 // Uids that ConnectivityService is pending to close sockets of.
976 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
977
Robert Greenwalt802c1102014-06-02 15:32:02 -0700978 /**
979 * Implements support for the legacy "one network per network type" model.
980 *
981 * We used to have a static array of NetworkStateTrackers, one for each
982 * network type, but that doesn't work any more now that we can have,
983 * for example, more that one wifi network. This class stores all the
984 * NetworkAgentInfo objects that support a given type, but the legacy
985 * API will only see the first one.
986 *
987 * It serves two main purposes:
988 *
989 * 1. Provide information about "the network for a given type" (since this
990 * API only supports one).
991 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
992 * the first network for a given type changes, or if the default network
993 * changes.
994 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900995 @VisibleForTesting
996 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900997
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900998 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900999 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001000
Robert Greenwalt802c1102014-06-02 15:32:02 -07001001 /**
1002 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1003 * Each list holds references to all NetworkAgentInfos that are used to
1004 * satisfy requests for that network type.
1005 *
1006 * This array is built out at startup such that an unsupported network
1007 * doesn't get an ArrayList instance, making this a tristate:
1008 * unsupported, supported but not active and active.
1009 *
1010 * The actual lists are populated when we scan the network types that
1011 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001012 *
1013 * Threading model:
1014 * - addSupportedType() is only called in the constructor
1015 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1016 * They are therefore not thread-safe with respect to each other.
1017 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1018 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001019 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001020 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001021 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001022 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001023 @NonNull
1024 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001025
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001026 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1027 // an entry have no timer (equivalent to -1). Lazily loaded.
1028 @NonNull
1029 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1030
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001031 LegacyTypeTracker(@NonNull ConnectivityService service) {
1032 mService = service;
1033 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001034 }
1035
Chiachang Wang3bc52762021-11-25 14:17:57 +08001036 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1037 // addressed.
1038 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001039 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1040 final PackageManager pm = ctx.getPackageManager();
1041 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1042 addSupportedType(TYPE_WIFI);
1043 }
1044 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1045 addSupportedType(TYPE_WIFI_P2P);
1046 }
1047 if (tm.isDataCapable()) {
1048 // Telephony does not have granular support for these types: they are either all
1049 // supported, or none is supported
1050 addSupportedType(TYPE_MOBILE);
1051 addSupportedType(TYPE_MOBILE_MMS);
1052 addSupportedType(TYPE_MOBILE_SUPL);
1053 addSupportedType(TYPE_MOBILE_DUN);
1054 addSupportedType(TYPE_MOBILE_HIPRI);
1055 addSupportedType(TYPE_MOBILE_FOTA);
1056 addSupportedType(TYPE_MOBILE_IMS);
1057 addSupportedType(TYPE_MOBILE_CBS);
1058 addSupportedType(TYPE_MOBILE_IA);
1059 addSupportedType(TYPE_MOBILE_EMERGENCY);
1060 }
1061 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1062 addSupportedType(TYPE_BLUETOOTH);
1063 }
1064 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1065 // TYPE_PROXY is only used on Wear
1066 addSupportedType(TYPE_PROXY);
1067 }
1068 // Ethernet is often not specified in the configs, although many devices can use it via
1069 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001070 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001071 addSupportedType(TYPE_ETHERNET);
1072 }
1073
1074 // Always add TYPE_VPN as a supported type
1075 addSupportedType(TYPE_VPN);
1076 }
1077
1078 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001079 if (mTypeLists[type] != null) {
1080 throw new IllegalStateException(
1081 "legacy list for type " + type + "already initialized");
1082 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001083 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001084 }
1085
Robert Greenwalt802c1102014-06-02 15:32:02 -07001086 public boolean isTypeSupported(int type) {
1087 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1088 }
1089
1090 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001091 synchronized (mTypeLists) {
1092 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1093 return mTypeLists[type].get(0);
1094 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001095 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001096 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001097 }
1098
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001099 public int getRestoreTimerForType(int type) {
1100 synchronized (mTypeLists) {
1101 if (mRestoreTimers == null) {
1102 mRestoreTimers = loadRestoreTimers();
1103 }
1104 return mRestoreTimers.getOrDefault(type, -1);
1105 }
1106 }
1107
1108 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1109 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001110 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001111 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1112 for (final String config : configs) {
1113 final String[] splits = TextUtils.split(config, ",");
1114 if (splits.length != 2) {
1115 logwtf("Invalid restore timer token count: " + config);
1116 continue;
1117 }
1118 try {
1119 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1120 } catch (NumberFormatException e) {
1121 logwtf("Invalid restore timer number format: " + config, e);
1122 }
1123 }
1124 return ret;
1125 }
1126
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001127 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001128 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001129 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001130 log("Sending " + state
1131 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001132 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001133 }
1134 }
1135
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001136 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1137 // network type, to preserve previous behaviour.
1138 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1139 if (vpnNai != mService.getLegacyLockdownNai()) return;
1140
1141 if (vpnNai.declaredUnderlyingNetworks == null
1142 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1143 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1144 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1145 return;
1146 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001147 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001148 vpnNai.declaredUnderlyingNetworks[0]);
1149 if (underlyingNai == null) return;
1150
1151 final int type = underlyingNai.networkInfo.getType();
1152 final DetailedState state = DetailedState.CONNECTED;
1153 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1154 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1155 }
1156
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001157 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001158 public void add(int type, NetworkAgentInfo nai) {
1159 if (!isTypeSupported(type)) {
1160 return; // Invalid network type.
1161 }
1162 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1163
1164 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1165 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001166 return;
1167 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001168 synchronized (mTypeLists) {
1169 list.add(nai);
1170 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001171
Chalard Jean5b409c72021-02-04 13:12:59 +09001172 // Send a broadcast if this is the first network of its type or if it's the default.
1173 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001174
1175 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1176 // to preserve previous behaviour.
1177 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001178 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001179 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1180 mService.sendLegacyNetworkBroadcast(nai, state, type);
1181 }
1182
1183 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1184 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001185 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001186 }
1187
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001188 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001189 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001190 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1191 if (list == null || list.isEmpty()) {
1192 return;
1193 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001194 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001195
Hugo Benichi389633f2016-06-21 09:48:07 +09001196 synchronized (mTypeLists) {
1197 if (!list.remove(nai)) {
1198 return;
1199 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001200 }
1201
Lorenzo Colitti49767722015-05-01 00:30:10 +09001202 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001203 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1204 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001205 }
1206
1207 if (!list.isEmpty() && wasFirstNetwork) {
1208 if (DBG) log("Other network available for type " + type +
1209 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001210 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001211 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001212 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001213 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001214 }
1215 }
1216
1217 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001218 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1219 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001220 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001221 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001222 }
1223 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001224
Chalard Jean46bfbf02022-02-02 00:56:25 +09001225 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001226 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001227 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001228 final DetailedState state = nai.networkInfo.getDetailedState();
1229 for (int type = 0; type < mTypeLists.length; type++) {
1230 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001231 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001232 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001233 if (isFirst || contains && isDefault) {
1234 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001235 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001236 }
1237 }
1238 }
1239
Robert Greenwalt94e22142014-07-30 16:31:24 -07001240 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001241 pw.println("mLegacyTypeTracker:");
1242 pw.increaseIndent();
1243 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001244 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001245 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001246 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001247 pw.println();
1248 pw.println("Current state:");
1249 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001250 synchronized (mTypeLists) {
1251 for (int type = 0; type < mTypeLists.length; type++) {
1252 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1253 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001254 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001255 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001256 }
1257 }
1258 pw.decreaseIndent();
1259 pw.decreaseIndent();
1260 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001261 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001262 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001263 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001264
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001265 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001266 /**
1267 * Helper class which parses out priority arguments and dumps sections according to their
1268 * priority. If priority arguments are omitted, function calls the legacy dump command.
1269 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001270 private class LocalPriorityDump {
1271 private static final String PRIORITY_ARG = "--dump-priority";
1272 private static final String PRIORITY_ARG_HIGH = "HIGH";
1273 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001274 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001275
1276 LocalPriorityDump() {}
1277
1278 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Laif8dba342023-10-12 17:01:03 +08001279 if (!HandlerUtils.runWithScissors(mHandler, () -> {
1280 doDump(fd, pw, new String[]{DIAG_ARG});
1281 doDump(fd, pw, new String[]{SHORT_ARG});
1282 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1283 pw.println("dumpHigh timeout");
1284 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001285 }
1286
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001287 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Laif8dba342023-10-12 17:01:03 +08001288 if (!HandlerUtils.runWithScissors(mHandler, () -> doDump(fd, pw, args),
1289 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1290 pw.println("dumpNormal timeout");
1291 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001292 }
1293
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001294 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1295 if (args == null) {
1296 dumpNormal(fd, pw, args);
1297 return;
1298 }
1299
1300 String priority = null;
1301 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1302 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1303 argIndex++;
1304 priority = args[argIndex];
1305 }
1306 }
1307
1308 if (PRIORITY_ARG_HIGH.equals(priority)) {
1309 dumpHigh(fd, pw);
1310 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1311 dumpNormal(fd, pw, args);
1312 } else {
1313 // ConnectivityService publishes binder service using publishBinderService() with
1314 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001315 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1316 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001317 // TODO: Integrate into signal dump.
1318 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001319 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001320 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001321 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001322
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001323 /**
1324 * Dependencies of ConnectivityService, for injection in tests.
1325 */
1326 @VisibleForTesting
1327 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001328 public int getCallingUid() {
1329 return Binder.getCallingUid();
1330 }
1331
Chalard Jeandf29a852023-05-29 17:02:43 +09001332 public boolean isAtLeastS() {
1333 return SdkLevel.isAtLeastS();
1334 }
1335
1336 public boolean isAtLeastT() {
1337 return SdkLevel.isAtLeastT();
1338 }
1339
1340 public boolean isAtLeastU() {
1341 return SdkLevel.isAtLeastU();
1342 }
1343
Chalard Jeaneb663892023-10-07 15:17:07 +09001344 public boolean isAtLeastV() {
1345 return SdkLevel.isAtLeastV();
1346 }
1347
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001348 /**
1349 * Get system properties to use in ConnectivityService.
1350 */
1351 public MockableSystemProperties getSystemProperties() {
1352 return new MockableSystemProperties();
1353 }
1354
1355 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001356 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1357 */
1358 public ConnectivityResources getResources(@NonNull Context ctx) {
1359 return new ConnectivityResources(ctx);
1360 }
1361
1362 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001363 * Create a HandlerThread to use in ConnectivityService.
1364 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001365 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1366 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001367 }
1368
1369 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001370 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001371 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001372 public NetworkStackClientBase getNetworkStack() {
1373 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001374 }
1375
1376 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001377 * @see ProxyTracker
1378 */
1379 public ProxyTracker makeProxyTracker(@NonNull Context context,
1380 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001381 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001382 }
1383
1384 /**
1385 * @see NetIdManager
1386 */
1387 public NetIdManager makeNetIdManager() {
1388 return new NetIdManager();
1389 }
1390
1391 /**
1392 * @see NetworkUtils#queryUserAccess(int, int)
1393 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001394 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1395 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001396 }
1397
1398 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001399 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1400 * requires CAP_NET_ADMIN, which the unit tests do not have.
1401 */
1402 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1403 InetSocketAddress remote) {
1404 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1405 }
1406
1407 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001408 * @see MultinetworkPolicyTracker
1409 */
1410 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1411 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1412 return new MultinetworkPolicyTracker(c, h, r);
1413 }
1414
Aaron Huang330a4c02020-10-27 03:36:19 +08001415 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001416 * @see AutomaticOnOffKeepaliveTracker
1417 */
1418 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1419 @NonNull Context c, @NonNull Handler h) {
1420 return new AutomaticOnOffKeepaliveTracker(c, h);
1421 }
1422
1423 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001424 * @see BatteryStatsManager
1425 */
1426 public void reportNetworkInterfaceForTransports(Context context, String iface,
1427 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001428 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001429 context.getSystemService(BatteryStatsManager.class);
1430 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1431 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001432
1433 public boolean getCellular464XlatEnabled() {
1434 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1435 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001436
1437 /**
1438 * @see PendingIntent#intentFilterEquals
1439 */
1440 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1441 return a.intentFilterEquals(b);
1442 }
1443
1444 /**
1445 * @see LocationPermissionChecker
1446 */
1447 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1448 return new LocationPermissionChecker(context);
1449 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001450
1451 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001452 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001453 *
1454 * This method returns null in versions before T, where carrier privilege
1455 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001456 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001457 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001458 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1459 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001460 if (isAtLeastT()) {
Chalard Jean96ff9542023-11-02 14:24:47 +09001461 return new CarrierPrivilegeAuthenticator(context, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001462 } else {
1463 return null;
1464 }
1465 }
1466
1467 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001468 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001469 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001470 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001471 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001472 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001473
1474 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001475 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1476 */
1477 public boolean isFeatureNotChickenedOut(Context context, String name) {
1478 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1479 }
1480
1481 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001482 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001483 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001484 * @return BpfNetMaps implementation.
1485 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001486 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1487 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001488 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001489
1490 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001491 * @see ClatCoordinator
1492 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001493 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001494 public ClatCoordinator getClatCoordinator(INetd netd) {
1495 return new ClatCoordinator(
1496 new ClatCoordinator.Dependencies() {
1497 @NonNull
1498 public INetd getNetd() {
1499 return netd;
1500 }
1501 });
1502 }
1503
1504 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001505 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1506 */
1507 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1508 final InterfaceParams params = InterfaceParams.getByName(iface);
1509 if (params == null) {
1510 // the interface might have disappeared.
1511 logw("Failed to get interface params for interface " + iface);
1512 return;
1513 }
1514 try {
1515 // converting rateInBytesPerSecond from long to int is safe here because the
1516 // setting's range is limited to INT_MAX.
1517 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001518 Log.i(TAG,
1519 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001520 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1521 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1522 } catch (IOException e) {
1523 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1524 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1525 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1526 + ") failure: ", e);
1527 }
1528 }
1529
1530 /**
1531 * Wraps {@link TcUtils#tcFilterDelDev}
1532 */
1533 public void disableIngressRateLimit(String iface) {
1534 final InterfaceParams params = InterfaceParams.getByName(iface);
1535 if (params == null) {
1536 // the interface might have disappeared.
1537 logw("Failed to get interface params for interface " + iface);
1538 return;
1539 }
1540 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001541 Log.i(TAG,
1542 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001543 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1544 } catch (IOException e) {
1545 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1546 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1547 }
1548 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001549
1550 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001551 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1552 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001553 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001554 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001555 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001556 }
1557
1558 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001559 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1560 */
1561 // TODO: when available in all active branches:
1562 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1563 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1564 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1565 return BroadcastOptionsShimImpl.newInstance(options);
1566 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001567
1568 /**
1569 * Wrapper method for
1570 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1571 *
1572 * @param changeId The ID of the compatibility change in question.
1573 * @param packageName The package name of the app in question.
1574 * @param user The user that the operation is done for.
1575 * @return {@code true} if the change is enabled for the specified package.
1576 */
1577 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1578 @NonNull final UserHandle user) {
1579 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1580 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001581
1582 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001583 * As above but with a UID.
1584 * @see CompatChanges#isChangeEnabled(long, int)
1585 */
1586 public boolean isChangeEnabled(final long changeId, final int uid) {
1587 return CompatChanges.isChangeEnabled(changeId, uid);
1588 }
1589
1590 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001591 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1592 *
1593 * @param ranges target uid ranges
1594 * @param exemptUids uids to skip close socket
1595 */
1596 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1597 @NonNull final Set<Integer> exemptUids)
1598 throws SocketException, InterruptedIOException, ErrnoException {
1599 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1600 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001601
1602 /**
1603 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1604 *
1605 * @param ownerUids target uids to close sockets
1606 */
1607 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1608 throws SocketException, InterruptedIOException, ErrnoException {
1609 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1610 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001611
1612 /**
1613 * Schedule the evaluation timeout.
1614 *
1615 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1616 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1617 * of these events happen, this time will run out, after which the network is considered
1618 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1619 * on this network and considers it won't provide connectivity. In particular, that means
1620 * it's when the system prefers it to cell if it's wifi and configuration says it should
1621 * prefer bad wifi to cell.
1622 */
1623 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1624 @NonNull final Network network, final long delayMs) {
1625 handler.sendMessageDelayed(
1626 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1627 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001628 }
1629
junyulaie7c7d2a2021-01-26 15:29:15 +08001630 public ConnectivityService(Context context) {
1631 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001632 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1633 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001634 }
1635
1636 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001637 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1638 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001639 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001640
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001641 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001642 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001643 mSystemProperties = mDeps.getSystemProperties();
1644 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001645 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001646 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001647 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1648 // Pass limit - 1 to maintain backward compatibility.
1649 // TODO: Remove the workaround.
1650 mNetworkRequestCounter =
1651 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1652 mSystemNetworkRequestCounter =
1653 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001654
Hugo Benichi208c0102016-07-28 17:53:06 +09001655 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001656 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1657 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001658 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001659 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001660 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001661 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1662 mDefaultNetworkRequests.add(mDefaultRequest);
1663 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001664
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001665 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001666 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001667
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001668 // The default WiFi request is a background request so that apps using WiFi are
1669 // migrated to a better network (typically ethernet) when one comes up, instead
1670 // of staying on WiFi forever.
1671 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1672 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1673
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001674 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1675 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1676 NetworkRequest.Type.BACKGROUND_REQUEST);
1677
Chalard Jean0702f982021-09-16 21:50:07 +09001678 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1679 // TODO: Consider making the timer customizable.
1680 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1681 mCellularRadioTimesharingCapable =
1682 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1683
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001684 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1685 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1686
1687 if (SdkLevel.isAtLeastU()) {
1688 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1689 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1690 final int defaultUMarkMask = 0x80000000; // u32
1691
1692 if ((mark == 0) || (mask == 0)) {
1693 // simply treat unset/disabled as the default U value
1694 mark = defaultUMarkMask;
1695 mask = defaultUMarkMask;
1696 }
1697 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1698 // invalid device overlay settings
1699 throw new IllegalArgumentException(
1700 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1701 }
1702 }
1703
1704 mWakeUpMark = mark;
1705 mWakeUpMask = mask;
1706
Paul Hu51f816b2022-08-11 14:43:47 +00001707 mNetd = netd;
1708 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Chalard Jean96ff9542023-11-02 14:24:47 +09001709 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Paul Hu51f816b2022-08-11 14:43:47 +00001710 mPermissionMonitor =
1711 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001712 mHandlerThread.start();
1713 mHandler = new InternalHandler(mHandlerThread.getLooper());
1714 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001715 mConnectivityDiagnosticsHandler =
1716 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001717
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001718 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001719 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001720
junyulaie7c7d2a2021-01-26 15:29:15 +08001721 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001722 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001723 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001724 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001725
Wink Saville32506bc2013-06-29 21:10:57 -07001726 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001727 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001728 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001729 mCarrierPrivilegeAuthenticator =
1730 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001731
Sudheer Shanka9967d462021-03-18 19:09:25 +00001732 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001733 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1734 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001735 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001736
1737 final PowerManager powerManager = (PowerManager) context.getSystemService(
1738 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001739 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001740 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001741
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001742 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1743 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001744 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001745 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001746 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001747 mProtectedNetworks.add(p);
1748 } else {
1749 if (DBG) loge("Ignoring protectedNetwork " + p);
1750 }
1751 }
1752
soma, kawata29444ae2019-05-23 09:30:40 +09001753 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1754
James Mattis02220e22021-03-13 19:27:21 -08001755 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001756 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001757 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001758 final IntentFilter userIntentFilter = new IntentFilter();
1759 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1760 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1761 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1762 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001763
James Mattis02220e22021-03-13 19:27:21 -08001764 // Listen to package add/removes for netd
1765 final IntentFilter packageIntentFilter = new IntentFilter();
1766 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1767 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1768 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1769 packageIntentFilter.addDataScheme("package");
1770 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001771 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001772
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09001773 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
1774 // But reading the trunk stable flags from mainline modules is not supported yet.
1775 // So enabling this feature on V+ release.
1776 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
1777 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
1778 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001779
Chalard Jean46bfbf02022-02-02 00:56:25 +09001780 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001781 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001782 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001783 } catch (RemoteException | ServiceSpecificException e) {
1784 loge("Error registering event listener :" + e);
1785 }
1786
Erik Kline05f2b402015-04-30 12:58:40 +09001787 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1788 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001789
chiachangwang7c17c282023-02-02 05:58:59 +00001790 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001791 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001792 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001793
1794 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001795 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001796 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1797 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001798 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001799 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1800 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001801
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001802 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001803 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001804 mNetworkRanker =
1805 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1806
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001807 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001808
Chiachang Wangc1215d32020-10-20 15:38:58 +08001809 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001810 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001811
Chalard Jean28018572020-12-21 18:36:52 +09001812 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1813 // request that doesn't allow fallback to the default network. It should never be visible
1814 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1815 // arguments like the handler or the DnsResolver.
1816 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001817 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001818 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001819 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001820 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001821 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001822 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1823 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001824
1825 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001826 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1827 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1828 // Even if it could, running on S would at least require mocking out the BPF map,
1829 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1830 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001831 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001832 mDscpPolicyTracker = new DscpPolicyTracker();
1833 }
Tyler Wear72388212021-09-09 14:49:02 -07001834 } catch (ErrnoException e) {
1835 loge("Unable to create DscpPolicyTracker");
1836 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001837
1838 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1839 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001840
Chalard Jeandf29a852023-05-29 17:02:43 +09001841 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001842 mCdmps = new CompanionDeviceManagerProxyService(context);
1843 } else {
1844 mCdmps = null;
1845 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001846
Chalard Jean2fb66f12023-08-25 12:50:37 +09001847 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
1848
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001849 mDestroyFrozenSockets = mDeps.isAtLeastU()
1850 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1851 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1852 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001853 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1854 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001855 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001856 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1857 new UidFrozenStateChangedCallback() {
1858 @Override
1859 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1860 if (uids.length != frozenStates.length) {
1861 Log.wtf(TAG, "uids has length " + uids.length
1862 + " but frozenStates has length " + frozenStates.length);
1863 return;
1864 }
1865
1866 final UidFrozenStateChangedArgs args =
1867 new UidFrozenStateChangedArgs(uids, frozenStates);
1868
1869 mHandler.sendMessage(
1870 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1871 }
1872 };
1873
1874 final ActivityManager activityManager =
1875 mContext.getSystemService(ActivityManager.class);
1876 activityManager.registerUidFrozenStateChangedCallback(
1877 (Runnable r) -> r.run(), frozenStateChangedCallback);
1878 }
Yuyang Huang41557552023-11-28 12:47:22 +09001879
1880 if (mDeps.isFeatureNotChickenedOut(mContext, LOG_BPF_RC)) {
1881 mHandler.post(BpfLoaderRcUtils::checkBpfLoaderRc);
1882 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001883 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001884
Xiao Ma0a171c02022-01-23 16:14:51 +00001885 /**
1886 * Check whether or not the device supports Ethernet transport.
1887 */
1888 public static boolean deviceSupportsEthernet(final Context context) {
1889 final PackageManager pm = context.getPackageManager();
1890 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1891 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1892 }
1893
Chalard Jean46adcf32018-04-18 20:18:38 +09001894 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001895 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1896 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001897 }
1898
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001899 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1900 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001901 final NetworkCapabilities netCap = new NetworkCapabilities();
1902 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001903 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001904 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001905 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001906 return netCap;
1907 }
1908
James Mattis45d81842021-01-10 14:24:24 -08001909 private NetworkRequest createDefaultRequest() {
1910 return createDefaultInternetRequestForTransport(
1911 TYPE_NONE, NetworkRequest.Type.REQUEST);
1912 }
1913
lucaslin3ba7cc22022-12-19 02:35:33 +00001914 private NetworkRequest createVpnRequest() {
1915 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1916 .withoutDefaultCapabilities()
1917 .addTransportType(TRANSPORT_VPN)
1918 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1919 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1920 .build();
1921 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1922 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1923 }
1924
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001925 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001926 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001927 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001928 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001929 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001930 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001931 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001932 netCap.addTransportType(transportType);
1933 }
James Mattis45d81842021-01-10 14:24:24 -08001934 return createNetworkRequest(type, netCap);
1935 }
1936
1937 private NetworkRequest createNetworkRequest(
1938 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001939 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001940 }
1941
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001942 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1943 NetworkRequest.Type type) {
1944 final NetworkCapabilities netCap = new NetworkCapabilities();
1945 netCap.clearAll();
1946 netCap.addCapability(capability);
1947 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1948 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1949 }
1950
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001951 // Used only for testing.
1952 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001953 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001954 // changing ContentResolver to make registerContentObserver non-final).
1955 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1956 // by subclassing SettingsObserver.
1957 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001958 void updateAlwaysOnNetworks() {
1959 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001960 }
1961
Erik Kline9a62f012018-03-21 07:18:33 -07001962 // See FakeSettingsProvider comment above.
1963 @VisibleForTesting
1964 void updatePrivateDnsSettings() {
1965 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1966 }
1967
paulhu51f77dc2021-06-07 02:34:20 +00001968 @VisibleForTesting
1969 void updateMobileDataPreferredUids() {
1970 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1971 }
1972
Patrick Rohr2857ac42022-01-21 14:58:16 +01001973 @VisibleForTesting
1974 void updateIngressRateLimit() {
1975 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1976 }
1977
Aaron Huang40b52442021-06-08 04:34:24 +08001978 @VisibleForTesting
1979 void simulateUpdateProxyInfo(@Nullable final Network network,
1980 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001981 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001982 new Pair<>(network, proxyInfo)).sendToTarget();
1983 }
1984
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001985 private void handleAlwaysOnNetworkRequest(
1986 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001987 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001988 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001989 handleAlwaysOnNetworkRequest(networkRequest, enable);
1990 }
1991
1992 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001993 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001994 if (enable == isEnabled) {
1995 return; // Nothing to do.
1996 }
1997
1998 if (enable) {
1999 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002000 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002001 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002002 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002003 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002004 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2005 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002006 }
2007 }
2008
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002009 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002010 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2011 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2012 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2013 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002014 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2015 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002016 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002017 }
2018
paulhu51f77dc2021-06-07 02:34:20 +00002019 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002020 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002021 private void registerSettingsCallbacks() {
2022 // Watch for global HTTP proxy changes.
2023 mSettingsObserver.observe(
2024 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2025 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2026
Chalard Jean46bfbf02022-02-02 00:56:25 +09002027 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002028 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002029 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002030 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2031
Chalard Jean46bfbf02022-02-02 00:56:25 +09002032 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002033 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002034 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002035 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002036
2037 // Watch for mobile data preferred uids changes.
2038 mSettingsObserver.observe(
2039 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2040 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002041
2042 // Watch for ingress rate limit changes.
2043 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002044 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002045 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2046 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002047 }
2048
Erik Kline31b4a9e2018-01-11 21:07:29 +09002049 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002050 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2051 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002052 }
2053 }
2054
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002055 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002056 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2057 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002058 return mNextNetworkRequestId++;
2059 }
2060
junyulai74f9a8b2018-06-13 15:00:37 +08002061 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002062 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002063 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002064 if (network == null) {
2065 return null;
2066 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002067 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002068 }
2069
2070 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002071 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002072 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002073 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002074 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002075
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002076 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002077 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002078 private NetworkAgentInfo getVpnForUid(int uid) {
2079 synchronized (mNetworkForNetId) {
2080 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2081 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002082 if (nai.isVPN() && nai.everConnected()
2083 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002084 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002085 }
2086 }
2087 }
2088 return null;
2089 }
2090
Chalard Jean46bfbf02022-02-02 00:56:25 +09002091 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002092 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002093 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002094 final NetworkAgentInfo nai = getVpnForUid(uid);
2095 if (nai != null) return nai.declaredUnderlyingNetworks;
2096 return null;
2097 }
2098
Lorenzo Colittia7574052021-01-19 01:33:05 +09002099 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002100 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002101
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002102 final Network[] networks = getVpnUnderlyingNetworks(uid);
2103 if (networks != null) {
2104 // getUnderlyingNetworks() returns:
2105 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2106 // empty array => the VPN explicitly said "no default network".
2107 // non-empty array => the VPN specified one or more default networks; we use the
2108 // first one.
2109 if (networks.length > 0) {
2110 nai = getNetworkAgentInfoForNetwork(networks[0]);
2111 } else {
2112 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002113 }
2114 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002115 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002116 }
2117
2118 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002119 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002120 */
paulhu7aeba372020-12-30 00:42:19 +08002121 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2122 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002123 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002124 if (ignoreBlocked) {
2125 return false;
2126 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002127 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002128 final long ident = Binder.clearCallingIdentity();
2129 try {
2130 final boolean metered = nc == null ? true : nc.isMetered();
2131 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2132 } finally {
2133 Binder.restoreCallingIdentity(ident);
2134 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002135 }
2136
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002137 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002138 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2139 return;
2140 }
Hugo Benichi47011212017-03-30 10:46:05 +09002141 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002142 synchronized (mBlockedAppUids) {
2143 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002144 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002145 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002146 blocked = false;
2147 } else {
2148 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002149 }
2150 }
Hugo Benichi47011212017-03-30 10:46:05 +09002151 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2152 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2153 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002154 }
2155
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002156 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002157 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2158 return;
2159 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002160 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002161 final int requestId = nri.getActiveRequest() != null
2162 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002163 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002164 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002165 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002166 }
2167
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002168 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002169 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002170 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002171 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002172 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002173 @NonNull
2174 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2175 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002176 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2177 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2178 // but only exists if an app asks about them or requests them. Ensure the requesting app
2179 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002180 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002181 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2182 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2183 null /* extraInfo */);
2184 }
2185 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002186 return filtered;
2187 }
2188
2189 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2190 boolean ignoreBlocked) {
2191 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2192 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002193 }
2194
2195 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002196 * Return NetworkInfo for the active (i.e., connected) network interface.
2197 * It is assumed that at most one network is active at a time. If more
2198 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002199 * @return the info for the active network, or {@code null} if none is
2200 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002201 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002202 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002203 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002204 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002205 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002206 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002207 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2208 if (nai == null) return null;
2209 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2210 maybeLogBlockedNetworkInfo(networkInfo, uid);
2211 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002212 }
2213
Paul Jensen1f567382015-02-13 14:18:39 -05002214 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002215 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002216 public Network getActiveNetwork() {
2217 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002218 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002219 }
2220
2221 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002222 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002223 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002224 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002225 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002226 }
2227
Chalard Jean46bfbf02022-02-02 00:56:25 +09002228 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002229 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002230 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2231 if (vpnNai != null) {
2232 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2233 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2234 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002235 }
Paul Jensen1f567382015-02-13 14:18:39 -05002236 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002237
James Mattis2516da32021-01-31 17:06:19 -08002238 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002239 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2240 ignoreBlocked)) {
2241 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002242 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002243 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002244 }
2245
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002246 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002247 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002248 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002249 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002250 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2251 if (nai == null) return null;
2252 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002253 }
2254
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002255 /** Returns a NetworkInfo object for a network that doesn't exist. */
2256 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2257 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2258 getNetworkTypeName(networkType), "" /* subtypeName */);
2259 info.setIsAvailable(true);
2260 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2261 // background data is restricted.
2262 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2263 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2264 ? DetailedState.BLOCKED
2265 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002266 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2267 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002268 return info;
2269 }
2270
Lorenzo Colittia7574052021-01-19 01:33:05 +09002271 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002272 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2273 return null;
2274 }
2275 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002276 if (nai == null) {
2277 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002278 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002279 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2280 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002281 }
2282
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002283 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002284 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002285 public NetworkInfo getNetworkInfo(int networkType) {
2286 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002287 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002288 if (getVpnUnderlyingNetworks(uid) != null) {
2289 // A VPN is active, so we may need to return one of its underlying networks. This
2290 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002291 // getNetworkAgentInfoForUid.
2292 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2293 if (nai == null) return null;
2294 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2295 if (networkInfo.getType() == networkType) {
2296 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002297 }
2298 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002299 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002300 }
2301
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002302 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002303 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002304 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002305 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002306 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002307 if (nai == null) return null;
2308 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002309 }
2310
2311 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002312 public NetworkInfo[] getAllNetworkInfo() {
2313 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002314 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002315 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2316 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002317 NetworkInfo info = getNetworkInfo(networkType);
2318 if (info != null) {
2319 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002320 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002321 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002322 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002323 }
2324
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002325 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002326 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002327 public Network getNetworkForType(int networkType) {
2328 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002329 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2330 return null;
2331 }
2332 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2333 if (nai == null) {
2334 return null;
2335 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002336 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002337 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2338 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002339 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002340 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002341 }
2342
2343 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002344 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002345 public Network[] getAllNetworks() {
2346 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002347 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002348 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002349 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002350 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002351 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002352 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002353 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002354 }
2355
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002356 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002357 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002358 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002359 // The basic principle is: if an app's traffic could possibly go over a
2360 // network, without the app doing anything multinetwork-specific,
2361 // (hence, by "default"), then include that network's capabilities in
2362 // the array.
2363 //
2364 // In the normal case, app traffic only goes over the system's default
2365 // network connection, so that's the only network returned.
2366 //
2367 // With a VPN in force, some app traffic may go into the VPN, and thus
2368 // over whatever underlying networks the VPN specifies, while other app
2369 // traffic may go over the system default network (e.g.: a split-tunnel
2370 // VPN, or an app disallowed by the VPN), so the set of networks
2371 // returned includes the VPN's underlying networks and the system
2372 // default.
2373 enforceAccessPermission();
2374
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002375 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002376
James Mattis2516da32021-01-31 17:06:19 -08002377 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2378 if (!nri.isBeingSatisfied()) {
2379 continue;
2380 }
2381 final NetworkAgentInfo nai = nri.getSatisfier();
2382 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2383 if (null != nc
2384 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2385 && !result.containsKey(nai.network)) {
2386 result.put(
2387 nai.network,
2388 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002389 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002390 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2391 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002392 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002393 }
2394
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002395 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002396 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002397 if (null != networks) {
2398 for (final Network network : networks) {
2399 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2400 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002401 result.put(
2402 network,
2403 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002404 nc,
2405 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002406 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002407 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002408 }
2409 }
2410 }
2411
2412 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2413 out = result.values().toArray(out);
2414 return out;
2415 }
2416
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002417 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2418 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2419 // can call sampleConnectivityState and make the checks on it.
2420 @NonNull
2421 private StatsEvent sampleConnectivityStateToStatsEvent() {
2422 final ConnectivityStateSample sample = sampleConnectivityState();
2423 return ConnectivityStatsLog.buildStatsEvent(
2424 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2425 sample.getNetworkCountPerTransports().toByteArray(),
2426 sample.getConnectionDurationPerTransports().toByteArray(),
2427 sample.getNetworkRequestCount().toByteArray(),
2428 sample.getNetworks().toByteArray());
2429 }
2430
2431 /**
2432 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2433 *
2434 * This is used for metrics. These snapshots will be sampled and constitute a base for
2435 * statistics about connectivity state of devices.
2436 */
2437 @VisibleForTesting
2438 @NonNull
2439 public ConnectivityStateSample sampleConnectivityState() {
2440 ensureRunningOnConnectivityServiceThread();
2441 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2442 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2443 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2444 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2445 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2446 return builder.build();
2447 }
2448
2449 private static NetworkCountPerTransports sampleNetworkCount(
2450 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2451 final SparseIntArray countPerTransports = new SparseIntArray();
2452 for (final NetworkAgentInfo nai : nais) {
2453 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2454 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2455 }
2456 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2457 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2458 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2459 c.setTransportTypes(countPerTransports.keyAt(i));
2460 c.setNetworkCount(countPerTransports.valueAt(i));
2461 builder.addNetworkCountForTransports(c);
2462 }
2463 return builder.build();
2464 }
2465
2466 private static ConnectionDurationPerTransports sampleConnectionDuration(
2467 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2468 final ConnectionDurationPerTransports.Builder builder =
2469 ConnectionDurationPerTransports.newBuilder();
2470 for (final NetworkAgentInfo nai : nais) {
2471 final ConnectionDurationForTransports.Builder c =
2472 ConnectionDurationForTransports.newBuilder();
2473 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2474 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2475 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2476 // Add millisPerSecond/2 to round up or down to the nearest value
2477 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2478 builder.addConnectionDurationForTransports(c);
2479 }
2480 return builder.build();
2481 }
2482
2483 private static NetworkRequestCount sampleNetworkRequestCount(
2484 @NonNull final Collection<NetworkRequestInfo> nris) {
2485 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2486 final SparseIntArray countPerType = new SparseIntArray();
2487 for (final NetworkRequestInfo nri : nris) {
2488 final int type;
2489 if (Process.SYSTEM_UID == nri.mAsUid) {
2490 // The request is filed "as" the system, so it's the system on its own behalf.
2491 type = RequestType.RT_SYSTEM.getNumber();
2492 } else if (Process.SYSTEM_UID == nri.mUid) {
2493 // The request is filed by the system as some other app, so it's the system on
2494 // behalf of an app.
2495 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2496 } else {
2497 // Not the system, so it's an app requesting on its own behalf.
2498 type = RequestType.RT_APP.getNumber();
2499 }
2500 countPerType.put(type, countPerType.get(type, 0));
2501 }
2502 for (int i = countPerType.size() - 1; i >= 0; --i) {
2503 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2504 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2505 r.setRequestCount(countPerType.valueAt(i));
2506 builder.addRequestCountForType(r);
2507 }
2508 return builder.build();
2509 }
2510
2511 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2512 final NetworkList.Builder builder = NetworkList.newBuilder();
2513 for (final NetworkAgentInfo nai : nais) {
2514 final NetworkCapabilities nc = nai.networkCapabilities;
2515 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2516 d.setTransportTypes((int) nc.getTransportTypesInternal());
2517 final MeteredState meteredState;
2518 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2519 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2520 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2521 meteredState = MeteredState.METERED_NO;
2522 } else {
2523 meteredState = MeteredState.METERED_YES;
2524 }
2525 d.setMeteredState(meteredState);
2526 final ValidatedState validatedState;
2527 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2528 validatedState = ValidatedState.VS_PORTAL;
2529 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2530 validatedState = ValidatedState.VS_PARTIAL;
2531 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2532 validatedState = ValidatedState.VS_VALID;
2533 } else {
2534 validatedState = ValidatedState.VS_INVALID;
2535 }
2536 d.setValidatedState(validatedState);
2537 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2538 d.setCapabilities(nc.getCapabilitiesInternal());
2539 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2540 builder.addNetworkDescription(d);
2541 }
2542 return builder.build();
2543 }
2544
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002545 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002546 public boolean isNetworkSupported(int networkType) {
2547 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002548 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002549 }
2550
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002551 /**
2552 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002553 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002554 * @return the ip properties for the active network, or {@code null} if
2555 * none is active
2556 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002557 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002558 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002559 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002560 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002561 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2562 if (nai == null) return null;
2563 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002564 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002565 }
2566
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002567 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002568 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002569 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002570 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002571 final LinkProperties lp = getLinkProperties(nai);
2572 if (lp == null) return null;
2573 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002574 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002575 }
2576
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002577 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002578 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002579 public LinkProperties getLinkProperties(Network network) {
2580 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002581 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2582 if (lp == null) return null;
2583 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002584 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002585 }
2586
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002587 @Nullable
2588 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002589 if (nai == null) {
2590 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002591 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002592 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002593 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002594 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002595 }
2596
lucaslinc582d502022-01-27 09:07:00 +08002597 @Override
2598 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002599 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002600 @NonNull String packageName, @Nullable String callingAttributionTag) {
2601 Objects.requireNonNull(packageName);
2602 Objects.requireNonNull(lp);
2603 enforceNetworkStackOrSettingsPermission();
2604 if (!checkAccessPermission(-1 /* pid */, uid)) {
2605 return null;
2606 }
2607 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2608 }
2609
Qingxi Lib2748102020-01-08 12:51:49 -08002610 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2611 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2612 }
2613
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002614 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002615 if (nai == null) return null;
2616 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002617 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002618 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002619 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002620 }
2621
2622 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002623 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2624 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002625 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002626 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002627 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002628 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002629 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002630 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002631 }
2632
lucaslinc582d502022-01-27 09:07:00 +08002633 @Override
lucaslind2b06132022-03-02 10:56:57 +08002634 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2635 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2636 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002637 Objects.requireNonNull(nc);
2638 Objects.requireNonNull(packageName);
2639 enforceNetworkStackOrSettingsPermission();
2640 if (!checkAccessPermission(-1 /* pid */, uid)) {
2641 return null;
2642 }
2643 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2644 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2645 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2646 callingAttributionTag);
2647 }
2648
lucaslin69e1aa92022-03-22 18:15:09 +08002649 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2650 if (nc.getUnderlyingNetworks() != null
2651 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2652 nc.setUnderlyingNetworks(null);
2653 }
2654 }
2655
Chalard Jean53017782022-11-24 17:13:44 +09002656 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
2657 return Process.SYSTEM_UID == uid
Chalard Jean53017782022-11-24 17:13:44 +09002658 || checkAnyPermissionOf(mContext, pid, uid,
2659 android.Manifest.permission.NETWORK_FACTORY);
2660 }
2661
Qingxi Libb8da982020-01-17 17:54:27 -08002662 @VisibleForTesting
2663 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002664 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002665 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2666 // this would be expensive (one more permission check every time any NC callback is
2667 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2668 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2669 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002670 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002671 if (!checkSettingsPermission(callerPid, callerUid)) {
2672 newNc.setUids(null);
2673 newNc.setSSID(null);
2674 }
Etan Cohen107ae952018-12-30 17:59:59 -08002675 if (newNc.getNetworkSpecifier() != null) {
2676 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2677 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002678 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2679 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002680 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2681 newNc.setAdministratorUids(new int[0]);
2682 }
Chalard Jean53017782022-11-24 17:13:44 +09002683 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09002684 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002685 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002686 }
lucaslin69e1aa92022-03-22 18:15:09 +08002687 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002688
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002689 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002690 }
2691
Roshan Pius98f59ec2021-02-23 08:47:39 -08002692 /**
2693 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002694 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002695 * NetworkCapabilities.
2696 * Note: This wrapper does not support any sort of invalidation and thus must not be
2697 * persistent or long-lived. It may only be used for the time necessary to
2698 * compute the redactions required by one particular NetworkCallback or
2699 * synchronous call.
2700 */
2701 private class RedactionPermissionChecker {
2702 private final int mCallingPid;
2703 private final int mCallingUid;
2704 @NonNull private final String mCallingPackageName;
2705 @Nullable private final String mCallingAttributionTag;
2706
2707 private Boolean mHasLocationPermission = null;
2708 private Boolean mHasLocalMacAddressPermission = null;
2709 private Boolean mHasSettingsPermission = null;
2710
2711 RedactionPermissionChecker(int callingPid, int callingUid,
2712 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2713 mCallingPid = callingPid;
2714 mCallingUid = callingUid;
2715 mCallingPackageName = callingPackageName;
2716 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002717 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002718
2719 private boolean hasLocationPermissionInternal() {
2720 final long token = Binder.clearCallingIdentity();
2721 try {
2722 return mLocationPermissionChecker.checkLocationPermission(
2723 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2724 null /* message */);
2725 } finally {
2726 Binder.restoreCallingIdentity(token);
2727 }
2728 }
2729
2730 /**
2731 * Returns whether the app holds location permission or not (might return cached result
2732 * if the permission was already checked before).
2733 */
2734 public boolean hasLocationPermission() {
2735 if (mHasLocationPermission == null) {
2736 // If there is no cached result, perform the check now.
2737 mHasLocationPermission = hasLocationPermissionInternal();
2738 }
2739 return mHasLocationPermission;
2740 }
2741
2742 /**
2743 * Returns whether the app holds local mac address permission or not (might return cached
2744 * result if the permission was already checked before).
2745 */
2746 public boolean hasLocalMacAddressPermission() {
2747 if (mHasLocalMacAddressPermission == null) {
2748 // If there is no cached result, perform the check now.
2749 mHasLocalMacAddressPermission =
2750 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2751 }
2752 return mHasLocalMacAddressPermission;
2753 }
2754
2755 /**
2756 * Returns whether the app holds settings permission or not (might return cached
2757 * result if the permission was already checked before).
2758 */
2759 public boolean hasSettingsPermission() {
2760 if (mHasSettingsPermission == null) {
2761 // If there is no cached result, perform the check now.
2762 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2763 }
2764 return mHasSettingsPermission;
2765 }
2766 }
2767
2768 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2769 @NetworkCapabilities.NetCapability long redaction) {
2770 return (redactions & redaction) != 0;
2771 }
2772
2773 /**
2774 * Use the provided |applicableRedactions| to check the receiving app's
2775 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2776 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2777 * before being sent to the corresponding app.
2778 */
2779 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2780 @NetworkCapabilities.RedactionType long applicableRedactions,
2781 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2782 boolean includeLocationSensitiveInfo) {
2783 long redactions = applicableRedactions;
2784 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2785 if (includeLocationSensitiveInfo
2786 && redactionPermissionChecker.hasLocationPermission()) {
2787 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2788 }
2789 }
2790 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2791 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2792 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2793 }
2794 }
2795 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2796 if (redactionPermissionChecker.hasSettingsPermission()) {
2797 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2798 }
2799 }
2800 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002801 }
2802
Qingxi Lib2748102020-01-08 12:51:49 -08002803 @VisibleForTesting
2804 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002805 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002806 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002807 int callingPid, int callingUid, @NonNull String callingPkgName,
2808 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002809 if (nc == null) {
2810 return null;
2811 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002812 // Avoid doing location permission check if the transport info has no location sensitive
2813 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002814 final RedactionPermissionChecker redactionPermissionChecker =
2815 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2816 callingAttributionTag);
2817 final long redactions = retrieveRequiredRedactions(
2818 nc.getApplicableRedactions(), redactionPermissionChecker,
2819 includeLocationSensitiveInfo);
2820 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002821 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002822 // TODO : calling UID is redacted because apps should generally not know what UID is
2823 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002824 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002825 newNc.setOwnerUid(INVALID_UID);
2826 return newNc;
2827 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002828 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2829 if (nc.hasTransport(TRANSPORT_VPN)) {
2830 // Owner UIDs already checked above. No need to re-check.
2831 return newNc;
2832 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002833 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2834 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002835 // compatibility for older apps.
2836 if (!includeLocationSensitiveInfo
2837 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002838 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002839 newNc.setOwnerUid(INVALID_UID);
2840 return newNc;
2841 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002842 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002843 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002844 newNc.setOwnerUid(INVALID_UID);
2845 }
Qingxi Lib2748102020-01-08 12:51:49 -08002846 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002847 }
2848
lucaslinc582d502022-01-27 09:07:00 +08002849 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002850 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2851 LinkProperties lp, int callerPid, int callerUid) {
2852 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002853 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2854 // this would be expensive (one more permission check every time any LP callback is
2855 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2856 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2857 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002858
2859 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2860 final boolean needsSanitization =
2861 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2862 if (!needsSanitization) {
2863 return new LinkProperties(lp);
2864 }
2865
2866 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002867 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002868 }
2869
2870 final LinkProperties newLp = new LinkProperties(lp);
2871 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2872 // object gets parceled.
2873 newLp.setCaptivePortalApiUrl(null);
2874 newLp.setCaptivePortalData(null);
2875 return newLp;
2876 }
2877
Roshan Pius08c94fb2020-01-16 12:17:17 -08002878 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2879 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002880 // There is no need to track the effective UID of the request here. If the caller
2881 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002882 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002883 // Unprivileged apps can only pass in null or their own UID.
2884 if (nc.getUids() == null) {
2885 // If the caller passes in null, the callback will also match networks that do not
2886 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2887 // In this case, redact everything in the request immediately. This ensures that the
2888 // app is not able to get any redacted information by filing an unredacted request
2889 // and observing whether the request matches something.
2890 if (nc.getNetworkSpecifier() != null) {
2891 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2892 }
2893 } else {
2894 nc.setSingleUid(callerUid);
2895 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002896 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002897 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002898 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002899
2900 // Clear owner UID; this can never come from an app.
2901 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002902 }
2903
Chalard Jean38354d12018-03-20 19:13:57 +09002904 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002905 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002906 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2907 }
2908 }
2909
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002910 @Override
2911 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2912 enforceAccessPermission();
2913 final int callerUid = Binder.getCallingUid();
2914 final long token = Binder.clearCallingIdentity();
2915 try {
2916 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2917 } finally {
2918 Binder.restoreCallingIdentity(token);
2919 }
2920 }
2921
junyulaiebd15162021-03-03 12:09:05 +08002922 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002923 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002924 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002925 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002926 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002927
Serik Beketayev05130302021-01-15 16:47:25 -08002928 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002929 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002930 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2931 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002932 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002933 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002934 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002935 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2936 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002937 }
2938 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002939 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002940 }
2941
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002942 @Override
junyulaiebd15162021-03-03 12:09:05 +08002943 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002944 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002945 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002946 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002947
2948 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2949 for (Network network : getAllNetworks()) {
2950 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002951 final boolean includeNetwork = (nai != null) && nai.isCreated();
2952 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002953 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2954 // NetworkCapabilities, which may contain UIDs of apps to which the
2955 // network applies. Should the UIDs be cleared so as not to leak or
2956 // interfere ?
2957 result.add(nai.getNetworkStateSnapshot());
2958 }
2959 }
2960 return result;
2961 }
2962
2963 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002964 public boolean isActiveNetworkMetered() {
2965 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002966
Qingxi Lib2748102020-01-08 12:51:49 -08002967 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002968 if (caps != null) {
2969 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2970 } else {
2971 // Always return the most conservative value
2972 return true;
2973 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002974 }
2975
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002976 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002977 * Ensures that the system cannot call a particular method.
2978 */
2979 private boolean disallowedBecauseSystemCaller() {
2980 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002981 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2982 // for devices launched with Q and above. However, existing devices upgrading to Q and
2983 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002984 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002985 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002986 log("This method exists only for app backwards compatibility"
2987 + " and must not be called by system services.");
2988 return true;
2989 }
2990 return false;
2991 }
2992
paulhub2c28682021-08-18 18:35:54 +08002993 private int getAppUid(final String app, final UserHandle user) {
2994 final PackageManager pm =
2995 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2996 final long token = Binder.clearCallingIdentity();
2997 try {
2998 return pm.getPackageUid(app, 0 /* flags */);
2999 } catch (PackageManager.NameNotFoundException e) {
3000 return -1;
3001 } finally {
3002 Binder.restoreCallingIdentity(token);
3003 }
3004 }
3005
3006 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
3007 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
3008 if (getAppUid(packageName, user) != callingUid) {
3009 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
3010 }
3011 }
3012
Lorenzo Colitti23862912018-09-28 11:31:55 +09003013 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003014 * Ensure that a network route exists to deliver traffic to the specified
3015 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003016 * @param networkType the type of the network over which traffic to the
3017 * specified host is to be routed
3018 * @param hostAddress the IP address of the host to which the route is
3019 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003020 * @return {@code true} on success, {@code false} on failure
3021 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003022 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003023 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3024 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003025 if (disallowedBecauseSystemCaller()) {
3026 return false;
3027 }
paulhub2c28682021-08-18 18:35:54 +08003028 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003029 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003030 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003031 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003032 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003033
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003034 InetAddress addr;
3035 try {
3036 addr = InetAddress.getByAddress(hostAddress);
3037 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003038 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003039 return false;
3040 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003041
The Android Open Source Project28527d22009-03-03 19:31:44 -08003042 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003043 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003044 return false;
3045 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003046
3047 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3048 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003049 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003050 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3051 } else {
3052 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3053 }
3054 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003055 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003056
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003057 DetailedState netState;
3058 synchronized (nai) {
3059 netState = nai.networkInfo.getDetailedState();
3060 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003061
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003062 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003063 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003064 log("requestRouteToHostAddress on down network "
3065 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003066 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003067 }
3068 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003069 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003070
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003071 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003072 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003073 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003074 LinkProperties lp;
3075 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003076 synchronized (nai) {
3077 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003078 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003079 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003080 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003081 if (DBG) {
3082 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3083 }
Wink Saville32506bc2013-06-29 21:10:57 -07003084 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003085 } finally {
3086 Binder.restoreCallingIdentity(token);
3087 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003088 }
3089
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003090 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003091 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003092 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003093 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003094 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003095 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003096 if (bestRoute.getGateway().equals(addr)) {
3097 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003098 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003099 } else {
3100 // if we will connect to this through another route, add a direct route
3101 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003102 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003103 }
3104 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003105 if (DBG) log("Adding legacy route " + bestRoute +
3106 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003107
3108 final String dst = bestRoute.getDestinationLinkAddress().toString();
3109 final String nextHop = bestRoute.hasGateway()
3110 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003111 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003112 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3113 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003114 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003115 return false;
3116 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003117 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003118 }
3119
paulhu7c0a2e62021-01-08 00:51:49 +08003120 class DnsResolverUnsolicitedEventCallback extends
3121 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003122 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003123 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003124 try {
3125 mHandler.sendMessage(mHandler.obtainMessage(
3126 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003127 new PrivateDnsValidationUpdate(event.netId,
3128 InetAddresses.parseNumericAddress(event.ipAddress),
3129 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003130 } catch (IllegalArgumentException e) {
3131 loge("Error parsing ip address in validation event");
3132 }
3133 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003134
3135 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003136 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3137 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003138 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3139 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3140 // event callback for certain nai. e.g. cellular. Register here to pass to
3141 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003142 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003143 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3144 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003145 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003146 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003147 }
3148 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003149
3150 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003151 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3152 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3153 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003154 }
dalyk1720e542018-03-05 12:42:22 -05003155
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003156 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003157 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003158 return this.VERSION;
3159 }
3160
3161 @Override
3162 public String getInterfaceHash() {
3163 return this.HASH;
3164 }
paulhu7c0a2e62021-01-08 00:51:49 +08003165 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003166
3167 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003168 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3169 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003170
paulhu7c0a2e62021-01-08 00:51:49 +08003171 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003172 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003173 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003174 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003175 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003176 }
3177 }
3178
Sudheer Shanka9967d462021-03-18 19:09:25 +00003179 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003180 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003181 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003182 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3183 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003184 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003185 };
3186
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003187 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003188 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003189 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003190 }
3191
Mark Fasheh7c999d82023-05-04 20:23:11 +00003192 static final class UidFrozenStateChangedArgs {
3193 final int[] mUids;
3194 final int[] mFrozenStates;
3195
3196 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3197 mUids = uids;
3198 mFrozenStates = frozenStates;
3199 }
3200 }
3201
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003202 /**
3203 * Check if the cell network is idle.
3204 * @return true if the cell network state is idle
3205 * false if the cell network state is active or unknown
3206 */
3207 private boolean isCellNetworkIdle() {
3208 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3209 if (defaultNai == null
3210 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3211 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3212 // cell network is not the default network, cell network state is unknown.
3213 // TODO(b/279380356): Track cell network state when the cell is not the default network
3214 return false;
3215 }
3216
3217 return !mNetworkActivityTracker.isDefaultNetworkActive();
3218 }
3219
Mark Fasheh7c999d82023-05-04 20:23:11 +00003220 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003221 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003222
3223 for (int i = 0; i < uids.length; i++) {
3224 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003225 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003226 } else {
3227 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003228 }
3229 }
3230
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003231 if (ownerUids.isEmpty()) {
3232 return;
3233 }
3234
3235 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3236 // Delay closing sockets to avoid waking the cell modem up.
3237 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3238 // than waking cell modem up.
3239 mPendingFrozenUids.addAll(ownerUids);
3240 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003241 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003242 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003243 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003244 loge("Exception in socket destroy: " + e);
3245 }
3246 }
3247 }
3248
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003249 private void closePendingFrozenSockets() {
3250 ensureRunningOnConnectivityServiceThread();
3251
3252 try {
3253 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3254 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3255 loge("Failed to close pending frozen app sockets: " + e);
3256 }
3257 mPendingFrozenUids.clear();
3258 }
3259
3260 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3261 mNetworkActivityTracker.handleReportNetworkActivity(params);
3262
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003263 final boolean isCellNetworkActivity;
3264 if (mTrackMultiNetworkActivities) {
3265 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3266 // nai could be null if netd receives a netlink message and calls the network
3267 // activity change callback after the network is unregistered from ConnectivityService.
3268 isCellNetworkActivity = nai != null
3269 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3270 } else {
3271 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3272 }
3273
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003274 if (mDelayDestroyFrozenSockets
3275 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003276 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003277 && !mPendingFrozenUids.isEmpty()) {
3278 closePendingFrozenSockets();
3279 }
3280 }
3281
3282 /**
3283 * If the cellular network is no longer the default network, close pending frozen sockets.
3284 *
3285 * @param newNetwork new default network
3286 * @param oldNetwork old default network
3287 */
3288 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3289 NetworkAgentInfo oldNetwork) {
3290 final boolean isOldNetworkCellular = oldNetwork != null
3291 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3292 final boolean isNewNetworkCellular = newNetwork != null
3293 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3294
3295 if (isOldNetworkCellular
3296 && !isNewNetworkCellular
3297 && !mPendingFrozenUids.isEmpty()) {
3298 closePendingFrozenSockets();
3299 }
3300 }
3301
3302 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3303 pw.println("CloseFrozenAppSockets:");
3304 pw.increaseIndent();
3305 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3306 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3307 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3308 pw.decreaseIndent();
3309 }
3310
Junyu Lai155760b2023-10-05 14:51:00 +08003311 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3312 pw.println("Bpf Program Status:");
3313 pw.increaseIndent();
3314 try {
3315 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003316 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003317 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003318 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003319 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003320 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003321 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003322 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003323 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003324 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003325 } catch (IOException e) {
3326 pw.println(" IOException");
3327 }
3328 pw.decreaseIndent();
3329 }
3330
Mark Fasheh7c999d82023-05-04 20:23:11 +00003331 @VisibleForTesting
3332 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003333 @VisibleForTesting
3334 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3335 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003336
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003337 @VisibleForTesting
3338 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3339 "allow_sysui_connectivity_reports";
3340
Yuyang Huang41557552023-11-28 12:47:22 +09003341 public static final String LOG_BPF_RC = "log_bpf_rc_force_disable";
3342
Paul Jensen83f5d572014-08-29 09:54:01 -04003343 private void enforceInternetPermission() {
3344 mContext.enforceCallingOrSelfPermission(
3345 android.Manifest.permission.INTERNET,
3346 "ConnectivityService");
3347 }
3348
The Android Open Source Project28527d22009-03-03 19:31:44 -08003349 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003350 mContext.enforceCallingOrSelfPermission(
3351 android.Manifest.permission.ACCESS_NETWORK_STATE,
3352 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003353 }
3354
lucaslinc582d502022-01-27 09:07:00 +08003355 private boolean checkAccessPermission(int pid, int uid) {
3356 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3357 == PERMISSION_GRANTED;
3358 }
3359
paulhua6ee2122021-02-22 15:40:43 +08003360 /**
3361 * Performs a strict and comprehensive check of whether a calling package is allowed to
3362 * change the state of network, as the condition differs for pre-M, M+, and
3363 * privileged/preinstalled apps. The caller is expected to have either the
3364 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3365 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3366 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3367 * permission and cannot be revoked. See http://b/23597341
3368 *
3369 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3370 * of this app will be updated to the current time.
3371 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003372 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003373 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3374 == PackageManager.PERMISSION_GRANTED) {
3375 return;
3376 }
3377
3378 if (callingPkg == null) {
3379 throw new SecurityException("Calling package name is null.");
3380 }
3381
3382 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3383 final int uid = mDeps.getCallingUid();
3384 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3385 callingPkg, callingAttributionTag, null /* message */);
3386
3387 if (mode == AppOpsManager.MODE_ALLOWED) {
3388 return;
3389 }
3390
3391 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3392 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3393 return;
3394 }
3395
3396 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3397 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3398 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003399 }
3400
Charles He9369e612017-05-15 17:07:18 +01003401 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003402 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003403 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003404 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003405 }
3406
Quang Luong98858d62023-02-11 00:25:24 +00003407 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003408 enforceAnyPermissionOf(mContext,
3409 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003410 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003411 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3412 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3413 }
3414
paulhu8e96a752019-08-12 16:25:11 +08003415 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003416 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003417 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003418 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003419 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003420 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003421 }
3422
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003423 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003424 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003425 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003426 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003427 android.Manifest.permission.NETWORK_SETTINGS,
3428 android.Manifest.permission.NETWORK_FACTORY,
3429 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3430 }
3431
3432 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003433 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003434 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003435 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003436 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3437 android.Manifest.permission.NETWORK_FACTORY,
3438 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3439 }
3440
lucaslin69e1aa92022-03-22 18:15:09 +08003441 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3442 return PERMISSION_GRANTED == mContext.checkPermission(
3443 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3444 || PERMISSION_GRANTED == mContext.checkPermission(
3445 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3446 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003447 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003448 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003449 }
3450
Chalard Jean9a396cc2018-02-21 18:43:54 +09003451 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003452 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003453 android.Manifest.permission.NETWORK_SETTINGS,
3454 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003455 }
3456
3457 private boolean checkSettingsPermission(int pid, int uid) {
3458 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003459 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3460 || PERMISSION_GRANTED == mContext.checkPermission(
3461 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003462 }
3463
paulhu8e96a752019-08-12 16:25:11 +08003464 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003465 enforceNetworkStackPermissionOr(mContext,
3466 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003467 }
3468
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003469 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003470 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003471 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003472 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003473 }
3474
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003475 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003476 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003477 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3478 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003479 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003480 }
3481
James Mattis8378aec2021-01-26 14:05:36 -08003482 private void enforceOemNetworkPreferencesPermission() {
3483 mContext.enforceCallingOrSelfPermission(
3484 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3485 "ConnectivityService");
3486 }
3487
James Mattisfa270db2021-05-31 17:11:10 -07003488 private void enforceManageTestNetworksPermission() {
3489 mContext.enforceCallingOrSelfPermission(
3490 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3491 "ConnectivityService");
3492 }
3493
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003494 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003495 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003496 android.Manifest.permission.NETWORK_STACK,
3497 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003498 }
3499
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003500 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003501 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003502 android.Manifest.permission.NETWORK_STACK,
3503 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3504 }
3505
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003506 private boolean checkSystemBarServicePermission(int pid, int uid) {
3507 return checkAnyPermissionOf(mContext, pid, uid,
3508 android.Manifest.permission.STATUS_BAR_SERVICE);
3509 }
3510
paulhu1a407652019-03-22 16:35:06 +08003511 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003512 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003513 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003514 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3515 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003516 }
3517
Paul Hu8fc2a552022-05-04 18:44:42 +08003518 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3519 boolean checkUidsAllowedList) {
3520 if (PermissionUtils.checkAnyPermissionOf(mContext,
3521 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3522 return true;
3523 }
3524
3525 // fallback to ConnectivityInternalPermission
3526 // TODO: Remove this fallback check after all apps have declared
3527 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3528 if (PermissionUtils.checkAnyPermissionOf(mContext,
3529 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3530 return true;
3531 }
3532
3533 // Check whether uid is in allowed on restricted networks list.
3534 if (checkUidsAllowedList
3535 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3536 return true;
3537 }
3538 return false;
3539 }
3540
3541 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3542 final int callingUid = mDeps.getCallingUid();
3543 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3544 throw new SecurityException("ConnectivityService: user " + callingUid
3545 + " has no permission to access restricted network.");
3546 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003547 }
3548
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003549 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003550 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003551 }
3552
Roshan Pius98f59ec2021-02-23 08:47:39 -08003553 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3554 return PERMISSION_GRANTED == mContext.checkPermission(
3555 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3556 }
3557
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003558 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003559 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003560 }
3561
3562 private void sendInetConditionBroadcast(NetworkInfo info) {
3563 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3564 }
3565
Wink Saville4f0de1e2011-08-04 15:01:58 -07003566 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003567 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003568 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003569 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003570 if (info.isFailover()) {
3571 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3572 info.setFailover(false);
3573 }
3574 if (info.getReason() != null) {
3575 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3576 }
3577 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003578 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3579 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003580 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003581 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003582 return intent;
3583 }
3584
3585 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3586 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3587 }
3588
Michael Groover73f69482023-01-27 11:01:25 -06003589 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3590 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003591 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3592 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003593 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003594 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003595 if (!mSystemReady
3596 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003597 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003598 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003599 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003600 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003601 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003602 }
3603
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003604 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003605 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003606 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003607 final NetworkInfo ni = intent.getParcelableExtra(
3608 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003609 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3610 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003611 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003612 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003613 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003614 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003615 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003616 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003617 } finally {
3618 Binder.restoreCallingIdentity(ident);
3619 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003620 }
3621 }
3622
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003623 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3624 NetworkInfo info) {
3625 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003626 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003627
3628 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3629 try {
3630 // This allows us to discard older broadcasts still waiting to be delivered
3631 // which have the same namespace and key.
3632 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3633 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3634 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003635 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003636 } catch (UnsupportedApiLevelException e) {
3637 Log.wtf(TAG, "Using unsupported API" + e);
3638 }
3639 }
3640
3641 @VisibleForTesting
3642 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3643 final StringBuilder sb = new StringBuilder();
3644 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3645 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3646 sb.append(info.getExtraInfo());
3647 return sb.toString();
3648 }
3649
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003650 /**
Aaron Huang96011892020-06-27 07:18:23 +08003651 * Called by SystemServer through ConnectivityManager when the system is ready.
3652 */
3653 @Override
3654 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003655 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003656 throw new SecurityException("Calling Uid is not system uid.");
3657 }
3658 systemReadyInternal();
3659 }
3660
3661 /**
3662 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003663 */
3664 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003665 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003666 // Load flags after PackageManager is ready to query module version
3667 mFlags.loadFlags(mDeps, mContext);
3668
Aaron Huang9a57acf2020-12-08 10:03:29 +08003669 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3670 // listening network request which is sent by MultipathPolicyTracker won't be added
3671 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3672 // be called after PermissionMonitor#startMonitoring().
3673 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3674 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3675 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003676 final ConditionVariable startMonitoringDone = new ConditionVariable();
3677 mHandler.post(() -> {
3678 mPermissionMonitor.startMonitoring();
3679 startMonitoringDone.open();
3680 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003681 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003682 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003683
Hugo Benichie5220992017-04-26 14:53:28 +09003684 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003685 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003686 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003687 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003688 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003689 }
3690 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003691
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003692 // Create network requests for always-on networks.
3693 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003694
3695 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003696 // Note that updating can be skipped here if the list is empty only because no uid
3697 // rules are applied before system ready. Normally, the empty uid list means to clear
3698 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003699 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3700 updateMobileDataPreferredUids();
3701 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003702
3703 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003704 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003705 mBpfNetMaps.setPullAtomCallback(mContext);
3706 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003707 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3708 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003709 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3710 // have permission problem. While CV#block() is unbounded in time and can in principle block
3711 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3712 // could have blocked forever too.
3713 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003714 }
3715
The Android Open Source Project28527d22009-03-03 19:31:44 -08003716 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003717 * Start listening for default data network activity state changes.
3718 */
3719 @Override
3720 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003721 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003722 }
3723
3724 /**
3725 * Stop listening for default data network activity state changes.
3726 */
3727 @Override
3728 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003729 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003730 }
3731
3732 /**
3733 * Check whether the default network radio is currently active.
3734 */
3735 @Override
3736 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003737 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003738 }
3739
3740 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003741 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003742 * and set it on it's iface.
3743 */
Junyu Lai970963e2022-10-25 15:46:47 +08003744 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003745 final String iface = newLp.getInterfaceName();
3746 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003747 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003748 // Silently ignore unset MTU value.
3749 return;
3750 }
Hansen Kurli04252032022-12-07 11:21:49 +00003751 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3752 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3753 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003754 return;
3755 }
Hansen Kurli04252032022-12-07 11:21:49 +00003756 // Cannot set MTU without interface name
3757 if (TextUtils.isEmpty(iface)) {
3758 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003759 return;
3760 }
sy.yun4aa73922013-09-02 05:24:09 +09003761
Hansen Kurli04252032022-12-07 11:21:49 +00003762 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3763 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003764 return;
3765 }
3766
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003767 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003768 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003769 mNetd.interfaceSetMtu(iface, mtu);
3770 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003771 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003772 }
3773 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003774
Chenbo Feng15416292018-11-08 17:36:21 -08003775 @VisibleForTesting
3776 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003777
Junyu Lai970963e2022-10-25 15:46:47 +08003778 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003779 String[] values = null;
3780 if (tcpBufferSizes != null) {
3781 values = tcpBufferSizes.split(",");
3782 }
3783
3784 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003785 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003786 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3787 values = tcpBufferSizes.split(",");
3788 }
3789
3790 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3791
3792 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003793 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003794
Chenbo Feng15416292018-11-08 17:36:21 -08003795 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3796 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3797 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003798 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003799 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003800 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003801 }
3802 }
3803
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003804 @Override
3805 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003806 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003807 NETWORK_RESTORE_DELAY_PROP_NAME);
3808 if(restoreDefaultNetworkDelayStr != null &&
3809 restoreDefaultNetworkDelayStr.length() != 0) {
3810 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003811 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003812 } catch (NumberFormatException e) {
3813 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003814 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003815 // if the system property isn't set, use the value for the apn type
3816 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3817
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003818 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3819 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003820 }
3821 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003822 }
3823
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003824 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003825 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003826 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003827 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003828 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003829 // Start gathering diagnostic information.
3830 netDiags.add(new NetworkDiagnostics(
3831 nai.network,
3832 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003833 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003834 DIAG_TIME_MS));
3835 }
3836
3837 for (NetworkDiagnostics netDiag : netDiags) {
3838 pw.println();
3839 netDiag.waitForMeasurements();
3840 netDiag.dump(pw);
3841 }
3842 }
3843
The Android Open Source Project28527d22009-03-03 19:31:44 -08003844 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003845 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3846 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003847 if (!checkDumpPermission(mContext, TAG, writer)) return;
3848
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003849 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003850 }
3851
lucaslin99473f62020-12-10 15:10:54 +08003852 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3853 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3854 != PackageManager.PERMISSION_GRANTED) {
3855 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003856 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003857 + " due to missing android.permission.DUMP permission");
3858 return false;
3859 } else {
3860 return true;
3861 }
3862 }
3863
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003864 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003865 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003866
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003867 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003868 dumpNetworkDiagnostics(pw);
3869 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003870 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003871 dumpNetworks(pw);
3872 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003873 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003874 dumpNetworkRequests(pw);
3875 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003876 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3877 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3878 dumpTrafficController(pw, fd, verbose);
3879 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003880 }
Erik Kline9647f382015-06-05 17:47:34 +09003881
Junyu Lai0da479b2022-04-20 15:06:29 +08003882 pw.println("NetworkProviders for:");
3883 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003884 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003885 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003886 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003887 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003888 pw.println();
3889
Chalard Jean5b409c72021-02-04 13:12:59 +09003890 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003891 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003892 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003893 pw.println("none");
3894 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003895 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003896 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003897 pw.println();
3898
James Mattis8b298a02021-06-01 22:34:04 -07003899 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003900 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003901 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003902 pw.decreaseIndent();
3903 pw.println();
3904
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003905 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003906 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003907 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003908 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003909 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003910
junyulaif2c67e42018-08-07 19:50:45 +08003911 pw.println("Status for known UIDs:");
3912 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003913 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003914 for (int i = 0; i < size; i++) {
3915 // Don't crash if the array is modified while dumping in bugreports.
3916 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003917 final int uid = mUidBlockedReasons.keyAt(i);
3918 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3919 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003920 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003921 } catch (ArrayIndexOutOfBoundsException e) {
3922 pw.println(" ArrayIndexOutOfBoundsException");
3923 } catch (ConcurrentModificationException e) {
3924 pw.println(" ConcurrentModificationException");
3925 }
3926 }
3927 pw.println();
3928 pw.decreaseIndent();
3929
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003930 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003931 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003932 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003933 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003934 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003935
Junyu Lai0da479b2022-04-20 15:06:29 +08003936 pw.println("Network Offers:");
3937 pw.increaseIndent();
3938 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3939 pw.println(offerInfo.offer);
3940 }
3941 pw.decreaseIndent();
3942 pw.println();
3943
Robert Greenwalt94e22142014-07-30 16:31:24 -07003944 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003945
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003946 pw.println();
markchien5e866652019-09-30 14:40:57 +08003947 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003948
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003949 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003950 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003951
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003952 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003953 dumpCloseFrozenAppSockets(pw);
3954
3955 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003956 dumpBpfProgramStatus(pw);
3957
Chalard Jean53017782022-11-24 17:13:44 +09003958 if (null != mCarrierPrivilegeAuthenticator) {
3959 pw.println();
3960 mCarrierPrivilegeAuthenticator.dump(pw);
3961 }
3962
Junyu Lai155760b2023-10-05 14:51:00 +08003963 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003964
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003965 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003966 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003967 pw.println("mNetworkRequestInfoLogs (most recent first):");
3968 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003969 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003970 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003971
3972 pw.println();
3973 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3974 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003975 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003976 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003977
3978 pw.println();
3979 pw.println("NetTransition WakeLock activity (most recent first):");
3980 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003981 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3982 pw.println("total releases: " + mTotalWakelockReleases);
3983 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3984 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3985 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3986 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3987 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3988 }
James Mattiscb1e0362021-04-06 17:07:42 -07003989 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003990
3991 pw.println();
3992 pw.println("bandwidth update requests (by uid):");
3993 pw.increaseIndent();
3994 synchronized (mBandwidthRequests) {
3995 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3996 pw.println("[" + mBandwidthRequests.keyAt(i)
3997 + "]: " + mBandwidthRequests.valueAt(i));
3998 }
3999 }
4000 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004001 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004002
James Mattiscb1e0362021-04-06 17:07:42 -07004003 pw.println();
4004 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4005 pw.increaseIndent();
4006 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004007 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004008 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004009
4010 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004011
4012 pw.println();
4013 pw.println("Permission Monitor:");
4014 pw.increaseIndent();
4015 mPermissionMonitor.dump(pw);
4016 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004017
4018 pw.println();
4019 pw.println("Legacy network activity:");
4020 pw.increaseIndent();
4021 mNetworkActivityTracker.dump(pw);
4022 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08004023 }
4024
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004025 private void dumpNetworks(IndentingPrintWriter pw) {
4026 for (NetworkAgentInfo nai : networksSortedById()) {
4027 pw.println(nai.toString());
4028 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004029 pw.println("Nat464Xlat:");
4030 pw.increaseIndent();
4031 nai.dumpNat464Xlat(pw);
4032 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004033 pw.println(String.format(
4034 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4035 nai.numForegroundNetworkRequests(),
4036 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4037 nai.numBackgroundNetworkRequests(),
4038 nai.numNetworkRequests()));
4039 pw.increaseIndent();
4040 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4041 pw.println(nai.requestAt(i).toString());
4042 }
4043 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004044 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004045 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004046 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004047 pw.decreaseIndent();
4048 pw.decreaseIndent();
4049 }
4050 }
4051
James Mattis8b298a02021-06-01 22:34:04 -07004052 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4053 if (!mProfileNetworkPreferences.isEmpty()) {
4054 pw.println("Profile preferences:");
4055 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004056 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004057 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004058 }
James Mattis8b298a02021-06-01 22:34:04 -07004059 if (!mOemNetworkPreferences.isEmpty()) {
4060 pw.println("OEM preferences:");
4061 pw.increaseIndent();
4062 pw.println(mOemNetworkPreferences);
4063 pw.decreaseIndent();
4064 }
4065 if (!mMobileDataPreferredUids.isEmpty()) {
4066 pw.println("Mobile data preferred UIDs:");
4067 pw.increaseIndent();
4068 pw.println(mMobileDataPreferredUids);
4069 pw.decreaseIndent();
4070 }
James Mattis45d81842021-01-10 14:24:24 -08004071
James Mattis8b298a02021-06-01 22:34:04 -07004072 pw.println("Default requests:");
4073 pw.increaseIndent();
4074 dumpPerAppDefaultRequests(pw);
4075 pw.decreaseIndent();
4076 }
4077
4078 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004079 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4080 if (mDefaultRequest == defaultRequest) {
4081 continue;
4082 }
4083
James Mattis8b298a02021-06-01 22:34:04 -07004084 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4085 final String networkOutput;
4086 if (null == satisfier) {
4087 networkOutput = "null";
4088 } else if (mNoServiceNetwork.equals(satisfier)) {
4089 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004090 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004091 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004092 }
James Mattis8b298a02021-06-01 22:34:04 -07004093 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4094 ? "" : " asUid: " + defaultRequest.mAsUid;
4095 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4096 + defaultRequest.mPid + asUidString + "]";
4097 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4098 + " Preference order: " + defaultRequest.mPreferenceOrder
4099 + " Tracked UIDs: " + defaultRequest.getUids();
4100 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004101 }
4102 }
4103
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004104 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004105 NetworkRequestInfo[] infos = null;
4106 while (infos == null) {
4107 try {
4108 infos = requestsSortedById();
4109 } catch (ConcurrentModificationException e) {
4110 // mNetworkRequests should only be accessed from handler thread, except dump().
4111 // As dump() is never called in normal usage, it would be needlessly expensive
4112 // to lock the collection only for its benefit. Instead, retry getting the
4113 // requests if ConcurrentModificationException is thrown during dump().
4114 }
4115 }
4116 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004117 pw.println(nri.toString());
4118 }
4119 }
4120
Ken Chene6d511f2022-01-25 11:10:42 +08004121 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4122 boolean verbose) {
4123 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004124 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004125 } catch (ServiceSpecificException e) {
4126 pw.println(e.getMessage());
4127 } catch (IOException e) {
4128 loge("Dump BPF maps failed, " + e);
4129 }
4130 }
4131
Chalard Jean524f0b12021-10-25 21:11:56 +09004132 private void dumpAllRequestInfoLogsToLogcat() {
4133 try (PrintWriter logPw = new PrintWriter(new Writer() {
4134 @Override
4135 public void write(final char[] cbuf, final int off, final int len) {
4136 // This method is called with 0-length and 1-length arrays for empty strings
4137 // or strings containing only the DEL character.
4138 if (len <= 1) return;
4139 Log.e(TAG, new String(cbuf, off, len));
4140 }
4141 @Override public void flush() {}
4142 @Override public void close() {}
4143 })) {
4144 mNetworkRequestInfoLogs.dump(logPw);
4145 }
4146 }
4147
Hugo Benichia480ba52018-09-03 08:19:02 +09004148 /**
4149 * Return an array of all current NetworkAgentInfos sorted by network id.
4150 */
4151 private NetworkAgentInfo[] networksSortedById() {
4152 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004153 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004154 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004155 return networks;
4156 }
4157
4158 /**
4159 * Return an array of all current NetworkRequest sorted by request id.
4160 */
James Mattis258ea3c2020-11-15 15:04:40 -08004161 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004162 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004163 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004164 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004165 // Sort the array based off the NRI containing the min requestId in its requests.
4166 Arrays.sort(requests,
4167 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4168 Comparator.comparingInt(req -> req.requestId)).requestId
4169 )
4170 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004171 return requests;
4172 }
4173
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004174 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004175 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004176 if (officialNai != null && officialNai.equals(nai)) return true;
4177 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004178 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004179 " - " + nai);
4180 }
4181 return false;
4182 }
4183
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004184 private boolean isDisconnectRequest(Message msg) {
4185 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4186 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4187 return info.getState() == NetworkInfo.State.DISCONNECTED;
4188 }
4189
Robert Greenwalt2034b912009-08-12 16:08:25 -07004190 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004191 private class NetworkStateTrackerHandler extends Handler {
4192 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004193 super(looper);
4194 }
4195
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004196 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004197 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4198 final NetworkAgentInfo nai = arg.first;
4199 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004200 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004201 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004202 }
4203 return;
4204 }
4205
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004206 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004207 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004208 return;
4209 }
4210
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004211 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004212 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004213 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4214 if (!nai.respectsNcStructuralConstraints(proposed)) {
4215 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4216 + nai.networkCapabilities + " -> " + proposed);
4217 disconnectAndDestroyNetwork(nai);
4218 return;
4219 }
4220 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004221 final NetworkCapabilities sanitized =
4222 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004223 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004224 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004225 break;
4226 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004227 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004228 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004229 processLinkPropertiesFromAgent(nai, newLp);
4230 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004231 break;
4232 }
4233 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004234 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004235 updateNetworkInfo(nai, info);
4236 break;
4237 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004238 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4239 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004240 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004241 break;
4242 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004243 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004244 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004245 break;
4246 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004247 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004248 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004249 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004250 // Note that if the NAI had been connected, this would affect the
4251 // score, and therefore would require re-mixing the score and performing
4252 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004253 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004254 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4255 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004256 // Mark the network as temporarily accepting partial connectivity so that it
4257 // will be validated (and possibly become default) even if it only provides
4258 // partial internet access. Note that if user connects to partial connectivity
4259 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4260 // out of wifi coverage) and if the same wifi is available again, the device
4261 // will auto connect to this wifi even though the wifi has "no internet".
4262 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004263 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004264 break;
4265 }
junyulai011b1f12019-01-03 18:50:15 +08004266 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004267 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004268 break;
4269 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004270 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004271 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004272 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004273
4274 if (isLegacyLockdownNai(nai)
4275 && (underlying == null || underlying.size() != 1)) {
4276 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4277 + " must have exactly one underlying network: " + underlying);
4278 }
4279
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004280 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4281 nai.declaredUnderlyingNetworks = (underlying != null)
4282 ? underlying.toArray(new Network[0]) : null;
4283
4284 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4285 if (DBG) {
4286 log(nai.toShortString() + " changed underlying networks to "
4287 + Arrays.toString(nai.declaredUnderlyingNetworks));
4288 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004289 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004290 notifyIfacesChangedForNetworkStats();
4291 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004292 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004293 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004294 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4295 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4296 nai.teardownDelayMs = msg.arg1;
4297 } else {
4298 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4299 }
Chalard Jean550b5212021-03-05 23:07:53 +09004300 break;
4301 }
4302 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4303 nai.setLingerDuration((int) arg.second);
4304 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004305 }
Tyler Wear72388212021-09-09 14:49:02 -07004306 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4307 DscpPolicy policy = (DscpPolicy) arg.second;
4308 if (mDscpPolicyTracker != null) {
4309 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4310 }
4311 break;
4312 }
4313 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4314 if (mDscpPolicyTracker != null) {
4315 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4316 }
4317 break;
4318 }
4319 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4320 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004321 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004322 }
4323 break;
4324 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004325 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004326 if (!nai.everConnected()) {
4327 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4328 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004329 teardownUnneededNetwork(nai);
4330 break;
4331 }
4332
4333 if (nai.isDestroyed()) {
4334 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4335 + ", ignoring");
4336 break;
4337 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004338
4339 final int timeoutMs = (int) arg.second;
4340 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4341 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4342 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4343 }
4344
4345 // Marking a network awaiting replacement is used to ensure that any requests
4346 // satisfied by the network do not switch to another network until a
4347 // replacement is available or the wait for a replacement times out.
4348 // If the network is inactive (i.e., nascent or lingering), then there are no
4349 // such requests, and there is no point keeping it. Just tear it down.
4350 // Note that setLingerDuration(0) cannot be used to do this because the network
4351 // could be nascent.
4352 nai.clearInactivityState();
4353 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4354 Log.d(TAG, nai.toShortString()
4355 + " marked awaiting replacement is unneeded, tearing down instead");
4356 teardownUnneededNetwork(nai);
4357 break;
4358 }
4359
4360 Log.d(TAG, "Marking " + nai.toShortString()
4361 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4362 destroyNativeNetwork(nai);
4363
4364 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4365 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4366 // consider the fact that the network could already have disconnected or been
4367 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4368 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4369 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4370 mKeepaliveTracker.handleStopAllKeepalives(nai,
4371 SocketKeepalive.ERROR_INVALID_NETWORK);
4372
4373 nai.updateScoreForNetworkAgentUpdate();
4374 // This rematch is almost certainly not going to result in any changes, because
4375 // the destroyed flag is only just above the "current satisfier wins"
4376 // tie-breaker. But technically anything that affects scoring should rematch.
4377 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004378 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004379 break;
4380 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004381 }
4382 }
4383
4384 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004385 final int netId = msg.arg2;
4386 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004387 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004388 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004389 switch (msg.what) {
4390 default:
4391 return false;
lucasline117e2e2019-10-22 18:27:33 +08004392 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004393 if (nai == null) {
4394 break;
4395 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004396 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4397 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004398 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004399 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004400 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004401 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004402 if (probePrivateDnsCompleted) {
4403 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4404 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004405 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004406 }
4407 // Only show the notification when the private DNS is broken and the
4408 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004409 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004410 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4411 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004412 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004413 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4414 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4415 // private DNS is broken, it means this network is being reevaluated.
4416 // Either probing private DNS is not necessary any more or it hasn't been
4417 // done yet. In either case, the networkCapabilities should be updated to
4418 // reflect the new status.
4419 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004420 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004421 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004422 }
4423 break;
4424 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004425 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004426 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4427
Erik Kline31b4a9e2018-01-11 21:07:29 +09004428 if (nai == null) break;
4429
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004430 handleNetworkTested(nai, results.mTestResult,
4431 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004432 break;
4433 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004434 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004435 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004436 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004437 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004438 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004439 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004440 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4441 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004442 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004443 if (nai == null) {
4444 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4445 break;
4446 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004447 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004448 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004449 (PendingIntent) msg.obj,
4450 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004451 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004452 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004453 break;
4454 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004455 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004456 if (nai == null) break;
4457
Erik Kline9a62f012018-03-21 07:18:33 -07004458 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004459 break;
4460 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004461 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004462 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004463 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004464 break;
4465 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004466 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004467 return true;
4468 }
4469
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004470 private void handleNetworkTested(
4471 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004472 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4473 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004474 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004475
4476 // If there is any kind of working networking, then the NAI has been evaluated
4477 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4478 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004479 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004480 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004481 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4482 // any callback that receives onAvailable for that rematch receives an extra caps
4483 // callback. To prevent that, update the score in the agent so the updates below won't
4484 // see an update to both caps and score at the same time.
4485 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004486 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4487
he_won.hwang881307a2022-03-15 21:23:52 +09004488 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4489 // Assume the validation failure is due to a temporary failure after roaming
4490 // and ignore it. NetworkMonitor will continue to retry validation. If it
4491 // continues to fail after the block timeout expires, the network will be
4492 // marked unvalidated. If it succeeds, then validation state will not change.
4493 return;
4494 }
4495
Chalard Jean254bd162022-08-25 13:04:51 +09004496 final boolean wasValidated = nai.isValidated();
4497 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004498 final boolean wasPortal = nai.captivePortalDetected();
4499 nai.setPartialConnectivity(partial);
4500 nai.setCaptivePortalDetected(portal);
4501 nai.updateScoreForNetworkAgentUpdate();
4502 final boolean partialConnectivityChanged = (wasPartial != partial);
4503 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004504
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004505 if (DBG) {
4506 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4507 ? " with redirect to " + redirectUrl
4508 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004509 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004510 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004511 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004512 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004513 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004514 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004515 if (valid) {
4516 handleFreshlyValidatedNetwork(nai);
4517 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4518 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004519 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004520 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004521 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004522 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004523 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004524 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004525 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004526 NotificationType.PRIVATE_DNS_BROKEN);
4527 // If network becomes valid, the hasShownBroken should be reset for
4528 // that network so that the notification will be fired when the private
4529 // DNS is broken again.
4530 nai.networkAgentConfig.hasShownBroken = false;
4531 }
4532 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004533 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004534 } else if (portalChanged) {
4535 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004536 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004537 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4538 nai.onPreventAutomaticReconnect();
4539 teardownUnneededNetwork(nai);
4540 return;
4541 } else {
4542 updateCapabilitiesForNetwork(nai);
4543 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004544 } else if (becameEvaluated) {
4545 // If valid or partial connectivity changed, updateCapabilities* has
4546 // done the rematch.
4547 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004548 }
4549 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004550
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004551 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004552 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004553 nai.onValidationStatusChanged(
4554 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4555 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004556
4557 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004558 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004559 // immediately. Re-notify partial connectivity silently if no internet
4560 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004561 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004562 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004563 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4564 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004565 }
4566
Chalard Jean254bd162022-08-25 13:04:51 +09004567 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004568 handleNetworkUnvalidated(nai);
4569 }
4570 }
4571
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004572 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4573 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4574 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4575 // Do not avoid captive portal when network is wear proxy.
4576 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4577 }
4578
Calvin Ondada1452016-10-11 15:10:46 -07004579 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004580 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4581 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004582 }
4583
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004584 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4585 switch (msg.what) {
4586 default:
4587 return false;
4588 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4589 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4590 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4591 handleLingerComplete(nai);
4592 }
4593 break;
4594 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004595 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4596 handleNetworkAgentRegistered(msg);
4597 break;
4598 }
4599 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4600 handleNetworkAgentDisconnected(msg);
4601 break;
4602 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004603 }
4604 return true;
4605 }
4606
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004607 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004608 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004609 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004610 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004611 maybeHandleNetworkAgentMessage(msg);
4612 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004613 }
4614 }
4615
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004616 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004617 private final int mNetId;
4618 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004619
4620 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004621 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004622 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004623 }
4624
4625 @Override
4626 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4627 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004628 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004629 }
4630
4631 @Override
4632 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004633 // Legacy version of notifyNetworkTestedWithExtras.
4634 // Would only be called if the system has a NetworkStack module older than the
4635 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004636 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004637 }
4638
4639 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004640 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004641 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4642 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004643 final Message msg = mTrackerHandler.obtainMessage(
4644 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004645 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004646 new NetworkTestedResults(
4647 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004648 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004649
4650 // Invoke ConnectivityReport generation for this Network test event.
4651 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4652 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004653
Cody Kestingf1120be2020-08-03 18:01:40 -07004654 // NetworkMonitor reports the network validation result as a bitmask while
4655 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4656 // logical value for ConnectivityDiagnostics.
4657 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4658 p.result);
4659
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004660 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004661 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004662 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4663 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4664
Aaron Huang959d3642021-01-21 15:47:41 +08004665 ConnectivityReportEvent reportEvent =
4666 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4667 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004668 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004669 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004670 }
4671
4672 @Override
4673 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4674 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4675 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004676 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004677 }
4678
4679 @Override
lucasline117e2e2019-10-22 18:27:33 +08004680 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4681 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4682 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004683 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004684 }
4685
4686 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004687 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4688 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4689 EVENT_CAPPORT_DATA_CHANGED,
4690 0, mNetId, data));
4691 }
4692
4693 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004694 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004695 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004696 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004697
4698 final PendingIntent pendingIntent;
4699 // Only the system server can register notifications with package "android"
4700 final long token = Binder.clearCallingIdentity();
4701 try {
paulhu7746e4e2020-06-09 19:07:03 +08004702 pendingIntent = PendingIntent.getBroadcast(
4703 mContext,
4704 0 /* requestCode */,
4705 intent,
4706 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004707 } finally {
4708 Binder.restoreCallingIdentity(token);
4709 }
4710 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4711 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004712 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004713 }
4714
4715 @Override
4716 public void hideProvisioningNotification() {
4717 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004718 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004719 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004720
4721 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004722 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004723 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004724 }
4725
4726 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004727 public int getInterfaceVersion() {
4728 return this.VERSION;
4729 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004730
4731 @Override
4732 public String getInterfaceHash() {
4733 return this.HASH;
4734 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004735 }
4736
Cody Kestingf1120be2020-08-03 18:01:40 -07004737 /**
4738 * Converts the given NetworkMonitor-specific validation result bitmask to a
4739 * ConnectivityDiagnostics-specific validation result int.
4740 */
4741 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4742 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4743 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4744 }
4745 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4746 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4747 }
4748 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4749 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4750 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4751 }
4752
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004753 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004754 log("Data stall detected with methods: " + p.detectionMethod);
4755
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004756 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004757 int detectionMethod = 0;
4758 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4759 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4760 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4761 }
4762 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4763 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4764 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4765 p.tcpMetricsCollectionPeriodMillis);
4766 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004767 }
4768
Cody Kestingf53a0752020-04-15 12:33:28 -07004769 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004770 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004771 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004772
4773 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4774 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4775 // the cost of going through two handlers.
4776 mConnectivityDiagnosticsHandler.sendMessage(msg);
4777 }
4778
Cody Kestingb37958e2020-05-15 10:36:01 -07004779 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4780 return (p.detectionMethod & detectionMethod) != 0;
4781 }
4782
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004783 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4784 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004785 }
4786
Erik Klinea73af002018-06-26 18:53:43 +09004787 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4788 if (nai == null) return;
4789 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4790 // in order to restart a validation pass from within netd.
4791 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00004792 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004793 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004794 }
4795 }
4796
Erik Kline31b4a9e2018-01-11 21:07:29 +09004797 private void handlePrivateDnsSettingsChanged() {
4798 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4799
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004800 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004801 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004802 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004803 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4804 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004805 }
4806 }
4807
Erik Kline9a62f012018-03-21 07:18:33 -07004808 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4809 // Private DNS only ever applies to networks that might provide
4810 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004811 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004812
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004813 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004814 // schedule DNS resolutions. If a DNS resolution is required the
4815 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004816 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004817
4818 // With Private DNS bypass support, we can proceed to update the
4819 // Private DNS config immediately, even if we're in strict mode
4820 // and have not yet resolved the provider name into a set of IPs.
4821 updatePrivateDns(nai, cfg);
4822 }
4823
4824 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4825 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004826 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004827 }
4828
dalyk1720e542018-03-05 12:42:22 -05004829 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4830 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4831 if (nai == null) {
4832 return;
4833 }
4834 mDnsManager.updatePrivateDnsValidation(update);
4835 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4836 }
4837
paulhu7c0a2e62021-01-08 00:51:49 +08004838 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004839 int prefixLength) {
4840 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4841 if (nai == null) return;
4842
paulhu7c0a2e62021-01-08 00:51:49 +08004843 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4844 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004845
4846 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004847 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004848 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004849 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004850 prefixLength);
4851 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004852 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004853 return;
4854 }
4855 }
4856
Lorenzo Colittid523d142020-04-01 20:16:30 +09004857 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004858 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4859 }
4860
Hai Shalome58bdc62021-01-11 18:45:34 -08004861 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004862 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004863 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004864 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4865 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4866 }
4867
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004868 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004869 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004870 * @param nai the agent info to update
4871 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004872 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004873 */
junyulai2b6f0c22021-02-03 20:15:30 +08004874 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4875 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4876 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004877 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004878 // one lingered request, set inactive.
4879 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004880 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004881 if (DBG) log("Unsetting inactive " + nai.toShortString());
4882 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004883 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004884 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004885 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004886 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4887 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004888 }
junyulai2b6f0c22021-02-03 20:15:30 +08004889 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004890 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004891 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004892 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004893 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004894 }
4895
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004896 private void handleNetworkAgentRegistered(Message msg) {
4897 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4898 if (!mNetworkAgentInfos.contains(nai)) {
4899 return;
4900 }
4901
4902 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4903 if (VDBG) log("NetworkAgent registered");
4904 } else {
4905 loge("Error connecting NetworkAgent");
4906 mNetworkAgentInfos.remove(nai);
4907 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004908 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004909 synchronized (mNetworkForNetId) {
4910 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004911 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004912 mNetIdManager.releaseNetId(nai.network.getNetId());
4913 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004914 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004915 }
4916 }
4917 }
Paul Jensend5f53392014-11-25 15:26:53 -05004918
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004919 @VisibleForTesting
4920 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004921 // The feature of creating the networks immediately was slated for U, but race conditions
4922 // detected late required this was flagged off.
4923 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4924 // in NetworkAgentTest.
4925 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004926 }
4927
4928 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4929 @NonNull NetworkInfo.State state) {
4930 if (nai.isCreated()) return false;
4931 if (state == NetworkInfo.State.CONNECTED) return true;
4932 if (state != NetworkInfo.State.CONNECTING) {
4933 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004934 if (shouldCreateNetworksImmediately()) {
4935 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4936 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004937 return false;
4938 }
4939 return nai.isVPN() || shouldCreateNetworksImmediately();
4940 }
4941
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004942 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004943 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004944 }
4945
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004946 @VisibleForTesting
4947 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004948 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004949 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004950
4951 // If the network never roamed, return false. The check below is not sufficient if time
4952 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4953 if (nai.lastRoamTime == 0) return false;
4954
he_won.hwang881307a2022-03-15 21:23:52 +09004955 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4956 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004957 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004958 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004959 final long currentTimeMs = SystemClock.elapsedRealtime();
4960 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004961 if (timeSinceLastRoam <= blockTimeOut) {
4962 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4963 return true;
4964 }
4965 }
4966 return false;
4967 }
4968
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004969 private void handleNetworkAgentDisconnected(Message msg) {
4970 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004971 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004972 }
4973
Chalard Jeand9fffc32018-05-11 20:19:20 +09004974 // Destroys a network, remove references to it from the internal state managed by
4975 // ConnectivityService, free its interfaces and clean up.
4976 // Must be called on the Handler thread.
4977 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004978 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004979
4980 if (!mNetworkAgentInfos.contains(nai)) return;
4981
Chalard Jeand9fffc32018-05-11 20:19:20 +09004982 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004983 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004984 }
lucaslinb25c9a62019-02-12 15:30:13 +08004985 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004986 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004987 // A network agent has disconnected.
4988 // TODO - if we move the logic to the network agent (have them disconnect
4989 // because they lost all their requests or because their score isn't good)
4990 // then they would disconnect organically, report their new state and then
4991 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004992 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004993 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4994 null, null);
4995 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004996 final boolean wasDefault = isDefaultNetwork(nai);
4997 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004998 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004999 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005000 if (mTrackMultiNetworkActivities) {
5001 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
5002 // the network becomes no longer the default network.
5003 mNetworkActivityTracker.removeDataActivityTracking(nai);
5004 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005005 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005006 // If this was a local network forwarded to some upstream, or if some local network was
5007 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005008 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005009 // If this is a local network with an upstream selector, remove the associated network
5010 // request.
5011 if (nai.isLocalNetwork()) {
5012 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5013 if (null != selector) {
5014 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5015 }
5016 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005017 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5018 // by other networks that are already connected. Perhaps that can be done by
5019 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5020 // of rematchAllNetworksAndRequests
5021 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005022 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005023
5024 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005025 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5026 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005027 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005028 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005029 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005030 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005031 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005032 synchronized (mNetworkForNetId) {
5033 // Remove the NetworkAgent, but don't mark the netId as
5034 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005035 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005036 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005037 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005038 // Update allowed network lists in netd. This should be called after removing nai
5039 // from mNetworkAgentInfos.
5040 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005041 // Remove all previously satisfied requests.
5042 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005043 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005044 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005045 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005046 if (currentNetwork != null
5047 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005048 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005049 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5050 // rematch not to keep disconnected agents instead of setting it here ; this
5051 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005052 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005053 for (final NetworkOfferInfo noi : mNetworkOffers) {
5054 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005055 }
James Mattise3ef1912020-12-20 11:09:58 -08005056
Chalard Jean5b409c72021-02-04 13:12:59 +09005057 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005058 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005059 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005060 ensureNetworkTransitionWakelock(nai.toShortString());
5061 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005062 }
5063 }
junyulai2b6f0c22021-02-03 20:15:30 +08005064 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005065 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005066 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005067 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005068 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005069 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005070 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005071
Aaron Huang9fe47be2021-06-08 13:11:45 +08005072 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5073 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5074 // not called by the rematch in this case. This is because the code above unset
5075 // this network from the default request's satisfier, and that is what the rematch
5076 // is using as its source data to know what the old satisfier was. So as far as the
5077 // rematch above is concerned, the old default network was null.
5078 // Therefore if there is no new default, the default network was null and is still
5079 // null, thus there was no change so makeDefault() is not called. So if the old
5080 // network had a proxy and there is no new default, the proxy tracker should be told
5081 // that there is no longer a default proxy.
5082 // Strictly speaking this is not essential because having a proxy setting when
5083 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5084 mProxyTracker.setDefaultProxy(null);
5085 }
5086
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005087 // Immediate teardown.
5088 if (nai.teardownDelayMs == 0) {
5089 destroyNetwork(nai);
5090 return;
5091 }
5092
5093 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005094 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305095 try {
5096 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5097 } catch (RemoteException e) {
5098 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5099 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005100 }
5101 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5102 }
5103
5104 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005105 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005106 // Tell netd to clean up the configuration for this network
5107 // (routing rules, DNS, etc).
5108 // This may be slow as it requires a lot of netd shelling out to ip and
5109 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005110 // after we've rematched networks with requests (which might change the default
5111 // network or service a new request from an app), so network traffic isn't interrupted
5112 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005113 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005114 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005115 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005116 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5117 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5118 // false if the network was never created.
5119 // TODO: delete when S is no longer supported.
5120 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005121 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005122 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005123 }
5124
Chalard Jean1e4c2182023-10-06 18:45:53 +09005125 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005126 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005127 // Step 1 : maybe this network was the upstream for one or more local networks.
5128 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5129 if (!local.isLocalNetwork()) continue;
5130 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5131 if (null == selector) continue;
5132 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5133 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5134 // called after removing all associated NRIs from mNetworkRequests.
5135 if (null == nri) continue;
5136 final NetworkAgentInfo satisfier = nri.getSatisfier();
5137 if (disconnecting != satisfier) continue;
5138 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005139 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5140 // correctly contains null as an upstream.
5141 if (sendCallbacks) {
5142 nri.setSatisfier(null, null);
5143 notifyNetworkCallbacks(local,
5144 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5145 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005146 }
5147
5148 // Step 2 : maybe this is a local network that had an upstream.
5149 if (!disconnecting.isLocalNetwork()) return;
5150 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5151 if (null == selector) return;
5152 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5153 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5154 // is called after removing all associated NRIs from mNetworkRequests.
5155 if (null == nri) return;
5156 final NetworkAgentInfo satisfier = nri.getSatisfier();
5157 if (null == satisfier) return;
5158 removeLocalNetworkUpstream(disconnecting, satisfier);
5159 }
5160
5161 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5162 @NonNull final NetworkAgentInfo upstream) {
5163 try {
5164 mRoutingCoordinatorService.removeInterfaceForward(
5165 localAgent.linkProperties.getInterfaceName(),
5166 upstream.linkProperties.getInterfaceName());
5167 } catch (RemoteException e) {
5168 loge("Couldn't remove interface forward for "
5169 + localAgent.linkProperties.getInterfaceName() + " to "
5170 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5171 }
5172 }
5173
Ken Chen6df7a902021-04-09 15:08:42 +08005174 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005175 try {
5176 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005177 final NativeNetworkConfig config;
5178 if (nai.isVPN()) {
5179 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005180 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005181 return false;
5182 }
5183 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5184 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005185 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005186 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005187 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005188 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005189 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5190 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005191 getNetworkPermission(nai.networkCapabilities),
5192 false /* secure */,
5193 VpnManager.TYPE_VPN_NONE,
5194 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005195 }
Ken Chen6df7a902021-04-09 15:08:42 +08005196 mNetd.networkCreate(config);
5197 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005198 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5199 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005200 return true;
5201 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005202 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005203 return false;
5204 }
5205 }
5206
Ken Chen6df7a902021-04-09 15:08:42 +08005207 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005208 if (mDscpPolicyTracker != null) {
5209 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5210 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005211 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005212 // the interface is going to go away. Don't send the callbacks however ; if the network
5213 // was is being disconnected the callbacks have already been sent, and if it is being
5214 // destroyed pending replacement they will be sent when it is disconnected.
5215 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005216 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005217 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005218 } catch (RemoteException | ServiceSpecificException e) {
5219 loge("Exception destroying network(networkDestroy): " + e);
5220 }
5221 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005222 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005223 } catch (RemoteException | ServiceSpecificException e) {
5224 loge("Exception destroying network: " + e);
5225 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005226 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5227 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5228 // gets created, could add data to DnsManager data structures that will never get deleted.
5229 mDnsManager.removeNetwork(nai.network);
5230
5231 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005232 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005233 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5234 }
5235
Chalard Jean254bd162022-08-25 13:04:51 +09005236 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005237 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005238 }
5239
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005240 // If this method proves to be too slow then we can maintain a separate
5241 // pendingIntent => NetworkRequestInfo map.
5242 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5243 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005244 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5245 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5246 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005247 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005248 return entry.getValue();
5249 }
5250 }
5251 return null;
5252 }
5253
Chalard Jean524f0b12021-10-25 21:11:56 +09005254 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005255 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005256 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5257 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5258 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5259 // bug is fixed.
5260 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005261 throw new IllegalStateException("This NRI is already registered. New : " + nri
5262 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005263 }
5264 }
5265 }
5266 }
5267
Chalard Jeanac9ace02022-01-26 16:54:05 +09005268 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5269 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005270 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09005271 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09005272 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005273 }
5274 return false;
5275 }
5276
James Mattisf7027322020-12-13 16:28:14 -08005277 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005278 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005279 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5280 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5281 final NetworkRequestInfo existingRequest =
5282 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005283 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005284 if (DBG) {
5285 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5286 + nri.mRequests.get(0) + " because their intents matched.");
5287 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005288 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005289 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005290 }
Erik Kline05f2b402015-04-30 12:58:40 +09005291 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005292 }
5293
James Mattisf7027322020-12-13 16:28:14 -08005294 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005295 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005296 }
5297
James Mattis3ce3d3c2021-02-09 18:18:28 -08005298 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005299 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005300 for (final NetworkRequestInfo nri : nris) {
5301 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005302 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005303 for (final NetworkRequest req : nri.mRequests) {
5304 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005305 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005306 if (req.isListen()) {
5307 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5308 if (req.networkCapabilities.hasSignalStrength()
5309 && network.satisfiesImmutableCapabilitiesOf(req)) {
5310 updateSignalStrengthThresholds(network, "REGISTER", req);
5311 }
James Mattisf7027322020-12-13 16:28:14 -08005312 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005313 }
5314 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005315
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005316 // If this NRI has a satisfier already, it is replacing an older request that
5317 // has been removed. Track it.
5318 final NetworkRequest activeRequest = nri.getActiveRequest();
5319 if (null != activeRequest) {
5320 // If there is an active request, then for sure there is a satisfier.
5321 nri.getSatisfier().addRequest(activeRequest);
5322 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005323 }
James Mattisf7027322020-12-13 16:28:14 -08005324
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005325 if (mFlags.noRematchAllRequestsOnRegister()) {
5326 rematchNetworksAndRequests(nris);
5327 } else {
5328 rematchAllNetworksAndRequests();
5329 }
James Mattis45d81842021-01-10 14:24:24 -08005330
Chalard Jean0354d8c2021-01-12 10:58:56 +09005331 // Requests that have not been matched to a network will not have been sent to the
5332 // providers, because the old satisfier and the new satisfier are the same (null in this
5333 // case). Send these requests to the providers.
5334 for (final NetworkRequestInfo nri : nris) {
5335 for (final NetworkOfferInfo noi : mNetworkOffers) {
5336 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005337 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005338 }
5339 }
5340
James Mattisf7027322020-12-13 16:28:14 -08005341 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5342 final int callingUid) {
5343 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005344 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005345 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5346 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5347 handleReleaseNetworkRequest(
5348 nri.mRequests.get(0),
5349 callingUid,
5350 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005351 }
5352 }
5353
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005354 // Determines whether the network is the best (or could become the best, if it validated), for
5355 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5356 // on the value of reason:
5357 //
5358 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5359 // then it should be torn down.
5360 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5361 // then it should be lingered.
5362 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005363 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005364
Chalard Jean254bd162022-08-25 13:04:51 +09005365 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005366 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5367 return false;
5368 }
5369
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005370 final int numRequests;
5371 switch (reason) {
5372 case TEARDOWN:
5373 numRequests = nai.numRequestNetworkRequests();
5374 break;
5375 case LINGER:
5376 numRequests = nai.numForegroundNetworkRequests();
5377 break;
5378 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005379 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005380 return true;
5381 }
5382
Chalard Jean947acd42021-03-08 22:29:27 +09005383 if (numRequests > 0) return false;
5384
Paul Jensende49eb12015-06-25 15:30:08 -04005385 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005386 if (reason == UnneededFor.LINGER
5387 && !nri.isMultilayerRequest()
5388 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005389 // Background requests don't affect lingering.
5390 continue;
5391 }
5392
James Mattis3d229892020-11-16 16:46:28 -08005393 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005394 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005395 }
5396 }
Paul Jensende49eb12015-06-25 15:30:08 -04005397 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005398 }
5399
James Mattis3d229892020-11-16 16:46:28 -08005400 private boolean isNetworkPotentialSatisfier(
5401 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005402 // While destroyed network sometimes satisfy requests (including occasionally newly
5403 // satisfying requests), *potential* satisfiers are networks that might beat a current
5404 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5405 // because it's never a good idea to keep a destroyed network in case it validates.
5406 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5407 // candidate after it's been replaced by another unvalidated network.
5408 if (candidate.isDestroyed()) return false;
5409 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005410 // request, return immediately. For multilayer requests, check to see if any of the
5411 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005412 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5413 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005414 return false;
5415 }
5416 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005417 // This multilayer listen request is satisfied therefore no further requests need to be
5418 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005419 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005420 return false;
5421 }
James Mattis3d229892020-11-16 16:46:28 -08005422 // As non-multilayer listen requests have already returned, the below would only happen
5423 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005424 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005425 continue;
5426 }
Chalard Jean80685f42023-10-30 18:31:27 +09005427 // If there is hope for this network might validate and subsequently become the best
5428 // network for that request, then it is needed. Note that this network can't already
5429 // be the best for this request, or it would be the current satisfier, and therefore
5430 // there would be no need to call this method to find out if it is a *potential*
5431 // satisfier ("unneeded", the only caller, only calls this if this network currently
5432 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005433 if (candidate.satisfies(req)) {
5434 // As soon as a network is found that satisfies a request, return. Specifically for
5435 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5436 // is important so as to not evaluate lower priority requests further in
5437 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005438 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5439 ? nri.getSatisfier() : null;
5440 // Note that this catches two important cases:
5441 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5442 // is currently satisfying the request. This is desirable when
5443 // cellular ends up validating but WiFi does not.
5444 // 2. Unvalidated WiFi will not be reaped when validated cellular
5445 // is currently satisfying the request. This is desirable when
5446 // WiFi ends up validating and out scoring cellular.
5447 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005448 }
5449 }
5450
5451 return false;
5452 }
5453
Erik Kline0c04b742016-07-07 16:50:58 +09005454 private NetworkRequestInfo getNriForAppRequest(
5455 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005456 // Looking up the app passed param request in mRequests isn't possible since it may return
5457 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5458 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005459 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5460 // to avoid potential race conditions when validating a package->uid mapping when sending
5461 // the callback on the very low-chance that an application shuts down prior to the callback
5462 // being sent.
5463 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5464 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005465
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005466 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005467 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005468 log(String.format("UID %d attempted to %s for unowned request %s",
5469 callingUid, requestedOperation, nri));
5470 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005471 }
Erik Kline0c04b742016-07-07 16:50:58 +09005472 }
5473
5474 return nri;
5475 }
5476
James Mattisf7027322020-12-13 16:28:14 -08005477 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5478 final String callingMethod) {
5479 if (nri.isMultilayerRequest()) {
5480 throw new IllegalStateException(
5481 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005482 }
5483 }
5484
James Mattisf7027322020-12-13 16:28:14 -08005485 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005486 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005487 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5488 // single NetworkRequest and thus does not apply to multilayer requests.
5489 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5490 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005491 return;
5492 }
James Mattis2516da32021-01-31 17:06:19 -08005493 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005494 return;
5495 }
James Mattisf7027322020-12-13 16:28:14 -08005496 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5497 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005498 }
5499 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005500 callCallbackForRequest(
5501 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005502 }
5503
James Mattisf7027322020-12-13 16:28:14 -08005504 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5505 final int callingUid,
5506 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005507 final NetworkRequestInfo nri =
5508 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5509 if (nri == null) {
5510 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005511 }
James Mattisf7027322020-12-13 16:28:14 -08005512 if (VDBG || (DBG && request.isRequest())) {
5513 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005514 }
5515 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005516 if (callOnUnavailable) {
5517 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5518 }
Erik Kline155a59a2015-11-25 12:49:38 +09005519 }
Erik Kline0c04b742016-07-07 16:50:58 +09005520
James Mattisa076c532020-12-02 14:12:41 -08005521 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005522 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005523 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005524 if (null == mNetworkRequests.remove(req)) {
5525 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5526 continue;
5527 }
James Mattisa076c532020-12-02 14:12:41 -08005528 if (req.isListen()) {
5529 removeListenRequestFromNetworks(req);
5530 }
5531 }
James Mattis8f036802021-06-20 16:26:01 -07005532 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005533 if (mDefaultNetworkRequests.remove(nri)) {
5534 // If this request was one of the defaults, then the UID rules need to be updated
5535 // WARNING : if the app(s) for which this network request is the default are doing
5536 // traffic, this will kill their connected sockets, even if an equivalent request
5537 // is going to be reinstated right away ; unconnected traffic will go on the default
5538 // until the new default is set, which will happen very soon.
5539 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5540 // remove ranges for those requests that won't have a replacement
5541 final NetworkAgentInfo satisfier = nri.getSatisfier();
5542 if (null != satisfier) {
5543 try {
paulhu0e79d952021-06-09 16:11:35 +08005544 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5545 satisfier.network.getNetId(),
5546 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005547 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005548 } catch (RemoteException e) {
5549 loge("Exception setting network preference default network", e);
5550 }
5551 }
5552 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005553
Junyu Lai00d92df2022-07-05 11:01:52 +08005554 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005555 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005556 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005557
5558 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005559 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005560 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005561 }
5562 }
5563
Chalard Jean0354d8c2021-01-12 10:58:56 +09005564 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5565 // needed for this offer.
5566 for (final NetworkOfferInfo noi : mNetworkOffers) {
5567 for (final NetworkRequest req : nri.mRequests) {
5568 if (req.isRequest() && noi.offer.neededFor(req)) {
5569 noi.offer.onNetworkUnneeded(req);
5570 }
5571 }
5572 }
James Mattisa076c532020-12-02 14:12:41 -08005573 }
5574
James Mattis3ce3d3c2021-02-09 18:18:28 -08005575 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5576 for (final NetworkRequestInfo nri : nris) {
5577 if (mDefaultRequest == nri) {
5578 // Make sure we never remove the default request.
5579 continue;
5580 }
5581 handleRemoveNetworkRequest(nri);
5582 }
5583 }
5584
James Mattisa076c532020-12-02 14:12:41 -08005585 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5586 // listens don't have a singular affected Network. Check all networks to see
5587 // if this listen request applies and remove it.
5588 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5589 nai.removeRequest(req.requestId);
5590 if (req.networkCapabilities.hasSignalStrength()
5591 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5592 updateSignalStrengthThresholds(nai, "RELEASE", req);
5593 }
5594 }
5595 }
5596
5597 /**
5598 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5599 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5600 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5601 */
5602 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5603 boolean wasKept = false;
5604 final NetworkAgentInfo nai = nri.getSatisfier();
5605 if (nai != null) {
5606 final int requestLegacyType = nri.getActiveRequest().legacyType;
5607 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5608 nai.removeRequest(nri.getActiveRequest().requestId);
5609 if (VDBG || DDBG) {
5610 log(" Removing from current network " + nai.toShortString()
5611 + ", leaving " + nai.numNetworkRequests() + " requests.");
5612 }
5613 // If there are still lingered requests on this network, don't tear it down,
5614 // but resume lingering instead.
5615 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005616 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005617 notifyNetworkLosing(nai, now);
5618 }
5619 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5620 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5621 teardownUnneededNetwork(nai);
5622 } else {
5623 wasKept = true;
5624 }
James Mattisa076c532020-12-02 14:12:41 -08005625 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5626 // Went from foreground to background.
5627 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005628 }
5629
Erik Kline0c04b742016-07-07 16:50:58 +09005630 // Maintain the illusion. When this request arrived, we might have pretended
5631 // that a network connected to serve it, even though the network was already
5632 // connected. Now that this request has gone away, we might have to pretend
5633 // that the network disconnected. LegacyTypeTracker will generate that
5634 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005635 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005636 boolean doRemove = true;
5637 if (wasKept) {
5638 // check if any of the remaining requests for this network are for the
5639 // same legacy type - if so, don't remove the nai
5640 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5641 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005642 if (otherRequest.legacyType == requestLegacyType
5643 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005644 if (DBG) log(" still have other legacy request - leaving");
5645 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005646 }
5647 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005648 }
5649
Erik Kline0c04b742016-07-07 16:50:58 +09005650 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005651 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005652 }
5653 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005654 }
5655 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005656
Junyu Lai00d92df2022-07-05 11:01:52 +08005657 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005658 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005659 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5660 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5661 }
5662
Lorenzo Colittid6459092016-07-04 12:55:44 +09005663 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005664 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005665 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005666 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005667 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005668 }
5669
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005670 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005671 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5672 enforceNetworkStackSettingsOrSetup();
5673 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5674 encodeBool(accept), encodeBool(always), network));
5675 }
5676
5677 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005678 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005679 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005680 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5681 }
5682
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005683 @Override
5684 public void setTestAllowBadWifiUntil(long timeMs) {
5685 enforceSettingsPermission();
5686 if (!Build.isDebuggable()) {
5687 throw new IllegalStateException("Does not support in non-debuggable build");
5688 }
5689
5690 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5691 throw new IllegalArgumentException("It should not exceed "
5692 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5693 }
5694
5695 mHandler.sendMessage(
5696 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5697 }
5698
chiachangwange0192a72023-02-06 13:25:01 +00005699 @Override
5700 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5701 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005702
5703 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5704 throw new IllegalArgumentException("Argument should not exceed "
5705 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5706 }
5707
5708 mHandler.sendMessage(
5709 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5710 }
5711
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005712 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5713 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5714 " accept=" + accept + " always=" + always);
5715
5716 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5717 if (nai == null) {
5718 // Nothing to do.
5719 return;
5720 }
5721
Chalard Jean254bd162022-08-25 13:04:51 +09005722 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005723 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005724 return;
5725 }
5726
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005727 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005728 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005729 }
5730
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005731 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5732 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005733 // If network becomes partial connectivity and user already accepted to use this
5734 // network, we should respect the user's option and don't need to popup the
5735 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005736 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005737 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005738 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005739 }
5740
5741 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005742 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005743 }
5744
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005745 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005746 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005747 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005748 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005749 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005750 }
5751
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005752 }
5753
lucaslin2240ef62019-03-12 13:08:03 +08005754 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5755 boolean always) {
5756 if (DBG) {
5757 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5758 + " always=" + always);
5759 }
5760
5761 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5762 if (nai == null) {
5763 // Nothing to do.
5764 return;
5765 }
5766
Chalard Jean254bd162022-08-25 13:04:51 +09005767 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005768 // The network validated while the dialog box was up. Take no action.
5769 return;
5770 }
5771
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005772 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5773 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005774 }
5775
5776 // TODO: Use the current design or save the user choice into IpMemoryStore.
5777 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005778 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005779 }
5780
5781 if (!accept) {
5782 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005783 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005784 // Tear down the network.
5785 teardownUnneededNetwork(nai);
5786 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005787 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5788 // result in a partial connectivity result which will be processed by
5789 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005790 //
5791 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5792 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005793 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005794 }
5795 }
5796
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005797 private void handleSetAvoidUnvalidated(Network network) {
5798 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005799 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005800 // Nothing to do. The network either disconnected or revalidated.
5801 return;
5802 }
Chalard Jean254bd162022-08-25 13:04:51 +09005803 if (0L == nai.getAvoidUnvalidated()) {
5804 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005805 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005806 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005807 }
5808 }
5809
Chalard Jean5fb43c72022-09-08 19:03:14 +09005810 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005811 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005812 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005813 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005814 }
5815
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005816 @Override
5817 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005818 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005819 mHandler.post(() -> {
5820 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5821 if (nai == null) return;
5822 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005823 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005824 });
5825 }
5826
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005827 /**
5828 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5829 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005830 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005831 * @param appExtras Bundle to use as intent extras for the captive portal application.
5832 * Must be treated as opaque to avoid preventing the captive portal app to
5833 * update its arguments.
5834 */
5835 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005836 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005837 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5838 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005839
5840 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5841 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005842 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5843 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005844 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5845
lucaslin75ff7022020-12-17 04:14:35 +08005846 final long token = Binder.clearCallingIdentity();
5847 try {
5848 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5849 } finally {
5850 Binder.restoreCallingIdentity(token);
5851 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005852 }
5853
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005854 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5855 private final Network mNetwork;
5856
5857 private CaptivePortalImpl(Network network) {
5858 mNetwork = network;
5859 }
5860
5861 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005862 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005863 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5864 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005865 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5866 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5867 // Since the network will be disconnected, skip notifying NetworkMonitor
5868 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005869 }
5870
Chiachang Wang938bfba2020-01-09 13:50:55 +08005871 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005872 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005873 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005874 }
5875
5876 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005877 public void appRequest(final int request) {
5878 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5879 if (nm == null) return;
5880
5881 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005882 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005883 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005884 }
5885 }
5886
5887 @Nullable
5888 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5889 // getNetworkAgentInfoForNetwork is thread-safe
5890 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5891 if (nai == null) return null;
5892
5893 // nai.networkMonitor() is thread-safe
5894 return nai.networkMonitor();
5895 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005896 }
5897
Hugo Benichic9048bc2016-09-14 23:23:08 +00005898 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005899 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005900 }
5901
Chalard Jean020b93a2022-09-01 13:20:14 +09005902 private boolean activelyPreferBadWifi() {
5903 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5904 }
5905
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005906 /**
5907 * Return whether the device should maintain continuous, working connectivity by switching away
5908 * from WiFi networks having no connectivity.
5909 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5910 */
5911 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005912 if (!checkNetworkStackPermission()) {
5913 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5914 }
5915 return avoidBadWifi();
5916 }
5917
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005918 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005919 ensureRunningOnConnectivityServiceThread();
5920 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005921 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005922 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005923 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005924 if (avoidBadWifi) {
5925 // If the device is now avoiding bad wifi, remove notifications that might have
5926 // been put up when the device didn't.
5927 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5928 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005929 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005930 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5931 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5932 for (final NetworkOfferInfo noi : offersToUpdate) {
5933 updateOfferScore(noi.offer);
5934 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005935 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005936 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005937 }
5938
Erik Kline95ecfee2016-10-02 18:02:14 +09005939 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005940 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005941 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005942 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005943 if (!configRestrict) {
5944 pw.println("Bad Wi-Fi avoidance: unrestricted");
5945 return;
5946 }
5947
5948 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5949 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005950 pw.println("Config restrict: " + configRestrict);
5951 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005952
Chalard Jeane0fdea32022-09-14 21:44:22 +09005953 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005954 String description;
5955 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005956 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005957 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005958 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005959 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005960 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005961 description = "avoid";
5962 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005963 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005964 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005965 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005966
5967 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5968 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005969 if (null == configValue) {
5970 description = "unset";
5971 } else if (configValue) {
5972 description = "force true";
5973 } else {
5974 description = "force false";
5975 }
5976 pw.println("Actively prefer bad wifi conf: " + description);
5977 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005978 pw.println("Network overrides:");
5979 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005980 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005981 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005982 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005983 }
5984 }
5985 pw.decreaseIndent();
5986 pw.decreaseIndent();
5987 }
5988
paulhu7746e4e2020-06-09 19:07:03 +08005989 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5990 // unify the method.
5991 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5992 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5993 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5994 return settingsComponent != null
5995 ? settingsComponent.getPackageName() : "com.android.settings";
5996 }
5997
lucaslinb1e8e382019-01-24 15:55:30 +08005998 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005999 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006000 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006001 switch (type) {
6002 case NO_INTERNET:
6003 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006004 // High priority because it is only displayed for explicitly selected networks.
6005 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006006 break;
lucasline117e2e2019-10-22 18:27:33 +08006007 case PRIVATE_DNS_BROKEN:
6008 action = Settings.ACTION_WIRELESS_SETTINGS;
6009 // High priority because we should let user know why there is no internet.
6010 highPriority = true;
6011 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006012 case LOST_INTERNET:
6013 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006014 // High priority because it could help the user avoid unexpected data usage.
6015 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006016 break;
lucaslin2240ef62019-03-12 13:08:03 +08006017 case PARTIAL_CONNECTIVITY:
6018 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006019 // Don't bother the user with a high-priority notification if the network was not
6020 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006021 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006022 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006023 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006024 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006025 return;
6026 }
6027
6028 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006029 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006030 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006031 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006032 // Some OEMs have their own Settings package. Thus, need to get the current using
6033 // Settings package name instead of just use default name "com.android.settings".
6034 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6035 intent.setClassName(settingsPkgName,
6036 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006037 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006038
paulhu2af50222020-10-11 22:52:27 +08006039 PendingIntent pendingIntent = PendingIntent.getActivity(
6040 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006041 0 /* requestCode */,
6042 intent,
paulhu2af50222020-10-11 22:52:27 +08006043 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006044
Serik Beketayevec8ad212020-12-07 22:43:07 -08006045 mNotifier.showNotification(
6046 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006047 }
6048
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006049 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6050 // Don't prompt if the network is validated, and don't prompt on captive portals
6051 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006052 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006053 return false;
6054 }
6055
6056 // If a network has partial connectivity, always prompt unless the user has already accepted
6057 // partial connectivity and selected don't ask again. This ensures that if the device
6058 // automatically connects to a network that has partial Internet access, the user will
6059 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006060 // because we have prompted them.
6061 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006062 return true;
6063 }
6064
6065 // If a network has no Internet access, only prompt if the network was explicitly selected
6066 // and if the user has not already told us to use the network regardless of whether it
6067 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006068 if (nai.networkAgentConfig.explicitlySelected
6069 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006070 return true;
6071 }
6072
6073 return false;
6074 }
6075
Chalard Jean5fb43c72022-09-08 19:03:14 +09006076 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6077 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006078
Chalard Jean5fb43c72022-09-08 19:03:14 +09006079 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6080 if (null == nai) return;
6081
6082 if (nai.setEvaluated()) {
6083 // If setEvaluated() returned true, the network never had any form of connectivity.
6084 // This may have an impact on request matching if bad WiFi avoidance is off and the
6085 // network was found not to have Internet access.
6086 nai.updateScoreForNetworkAgentUpdate();
6087 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006088
6089 // Also, if this is WiFi and it should be preferred actively, now is the time to
6090 // prompt the user that they walked past and connected to a bad WiFi.
6091 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6092 && !avoidBadWifi()
6093 && activelyPreferBadWifi()) {
6094 // The notification will be removed if the network validates or disconnects.
6095 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6096 return;
6097 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006098 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006099
Chalard Jean5fb43c72022-09-08 19:03:14 +09006100 if (!shouldPromptUnvalidated(nai)) return;
6101
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006102 // Stop automatically reconnecting to this network in the future. Automatically connecting
6103 // to a network that provides no or limited connectivity is not useful, because the user
6104 // cannot use that network except through the notification shown by this method, and the
6105 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006106 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006107
Chalard Jean254bd162022-08-25 13:04:51 +09006108 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006109 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006110 } else {
6111 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6112 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006113 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006114
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006115 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6116 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006117 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006118
lucaslin2240ef62019-03-12 13:08:03 +08006119 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6120 return;
6121 }
6122
6123 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006124 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006125 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006126 }
6127
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006128 @Override
6129 public int getMultipathPreference(Network network) {
6130 enforceAccessPermission();
6131
6132 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006133 if (nai != null && nai.networkCapabilities
6134 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006135 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6136 }
6137
Aaron Huang9a57acf2020-12-08 10:03:29 +08006138 final NetworkPolicyManager netPolicyManager =
6139 mContext.getSystemService(NetworkPolicyManager.class);
6140
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006141 final long token = Binder.clearCallingIdentity();
6142 final int networkPreference;
6143 try {
6144 networkPreference = netPolicyManager.getMultipathPreference(network);
6145 } finally {
6146 Binder.restoreCallingIdentity(token);
6147 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006148 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006149 return networkPreference;
6150 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006151 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6152 }
6153
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006154 @Override
6155 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006156 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006157 }
6158
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006159 private class InternalHandler extends Handler {
6160 public InternalHandler(Looper looper) {
6161 super(looper);
6162 }
6163
6164 @Override
6165 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006166 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006167 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006168 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006169 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006170 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006171 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006172 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006173 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006174 break;
6175 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006176 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006177 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006178 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006179 break;
6180 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006181 case EVENT_REGISTER_NETWORK_PROVIDER: {
6182 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006183 break;
6184 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006185 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6186 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006187 break;
6188 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006189 case EVENT_REGISTER_NETWORK_OFFER: {
6190 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6191 break;
6192 }
6193 case EVENT_UNREGISTER_NETWORK_OFFER: {
6194 final NetworkOfferInfo offer =
6195 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6196 if (null != offer) {
6197 handleUnregisterNetworkOffer(offer);
6198 }
6199 break;
6200 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006201 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006202 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6203 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6204 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006205 break;
6206 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006207 case EVENT_REGISTER_NETWORK_REQUEST:
6208 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006209 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006210 break;
6211 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006212 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6213 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006214 handleRegisterNetworkRequestWithIntent(msg);
6215 break;
6216 }
Erik Kline155a59a2015-11-25 12:49:38 +09006217 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6218 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6219 handleTimedOutNetworkRequest(nri);
6220 break;
6221 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006222 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6223 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6224 break;
6225 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006226 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006227 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6228 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006229 break;
6230 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006231 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006232 Network network = (Network) msg.obj;
6233 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006234 break;
6235 }
lucaslin2240ef62019-03-12 13:08:03 +08006236 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6237 Network network = (Network) msg.obj;
6238 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6239 toBool(msg.arg2));
6240 break;
6241 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006242 case EVENT_SET_AVOID_UNVALIDATED: {
6243 handleSetAvoidUnvalidated((Network) msg.obj);
6244 break;
6245 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006246 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6247 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006248 break;
6249 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006250 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6251 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006252 break;
6253 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006254 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6255 // handler thread.
6256 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006257 mKeepaliveTracker.handleStartKeepalive(msg);
6258 break;
6259 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006260 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006261 final AutomaticOnOffKeepalive ki =
6262 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6263 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006264
chiachangwang676c84e2023-02-14 09:22:05 +00006265 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006266 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006267 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006268 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006269 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6270 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006271 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6272 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006273 }
6274 }
6275
6276 // If the network no longer exists, then the keepalive should have been
6277 // cleaned up already. There is no point trying to resume keepalives.
6278 if (!networkFound) return;
6279
chiachangwang676c84e2023-02-14 09:22:05 +00006280 if (underpinnedNetworkFound) {
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006281 final NetworkCapabilities underpinnedNc =
6282 getNetworkCapabilitiesInternal(underpinnedNetwork);
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006283 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006284 underpinnedNetwork.netId, underpinnedNc.getUids());
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006285 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006286 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006287 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006288 }
6289 break;
6290 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006291 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006292 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006293 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6294 (IBinder) msg.obj);
6295 if (ki == null) {
6296 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006297 return;
6298 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006299 final int reason = msg.arg2;
6300 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006301 break;
6302 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006303 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6304 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6305 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006306 break;
6307 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006308 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6309 handlePrivateDnsSettingsChanged();
6310 break;
dalyk1720e542018-03-05 12:42:22 -05006311 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6312 handlePrivateDnsValidationUpdate(
6313 (PrivateDnsValidationUpdate) msg.obj);
6314 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006315 case EVENT_UID_BLOCKED_REASON_CHANGED:
6316 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006317 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006318 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6319 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6320 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006321 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006322 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6323 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006324 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006325 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006326 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006327 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006328 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6329 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006330 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006331 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006332 }
lucaslin1193a5d2021-01-21 02:04:15 +08006333 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006334 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006335 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006336 break;
paulhu51f77dc2021-06-07 02:34:20 +00006337 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6338 handleMobileDataPreferredUidsChanged();
6339 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006340 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6341 final long timeMs = ((Long) msg.obj).longValue();
6342 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6343 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006344 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6345 handleIngressRateLimitChanged();
6346 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006347 case EVENT_USER_DOES_NOT_WANT:
6348 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6349 if (nai == null) break;
6350 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006351 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006352 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006353 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6354 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6355 break;
chiachangwange0192a72023-02-06 13:25:01 +00006356 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6357 final long time = ((Long) msg.obj).longValue();
6358 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6359 break;
6360 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006361 case EVENT_UID_FROZEN_STATE_CHANGED:
6362 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6363 handleFrozenUids(args.mUids, args.mFrozenStates);
6364 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006365 }
6366 }
6367 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006368
Lorenzo Colittid6459092016-07-04 12:55:44 +09006369 @Override
markchien5776f962019-12-16 20:15:20 +08006370 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006371 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006372 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006373 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6374 Context.TETHERING_SERVICE);
6375 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006376 }
6377
Lorenzo Colittid6459092016-07-04 12:55:44 +09006378 @Override
markchien5776f962019-12-16 20:15:20 +08006379 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006380 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006381 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006382 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6383 Context.TETHERING_SERVICE);
6384 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006385 }
6386
Lorenzo Colittid6459092016-07-04 12:55:44 +09006387 @Override
markchien5776f962019-12-16 20:15:20 +08006388 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006389 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006390 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006391 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6392 Context.TETHERING_SERVICE);
6393 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006394 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006395
markchien5776f962019-12-16 20:15:20 +08006396
Lorenzo Colittid6459092016-07-04 12:55:44 +09006397 @Override
markchien5776f962019-12-16 20:15:20 +08006398 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006399 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006400 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006401 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6402 Context.TETHERING_SERVICE);
6403
6404 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006405 }
6406
Lorenzo Colittid6459092016-07-04 12:55:44 +09006407 @Override
markchien5776f962019-12-16 20:15:20 +08006408 @Deprecated
6409 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006410 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006411 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6412 Context.TETHERING_SERVICE);
6413
6414 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006415 }
6416
Udam Saini8f7d6a72017-06-07 12:06:28 -07006417 @Override
markchien5776f962019-12-16 20:15:20 +08006418 @Deprecated
6419 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006420 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006421 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6422 Context.TETHERING_SERVICE);
6423 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006424 }
6425
Robert Greenwalte0b00512014-07-02 09:59:16 -07006426 // Called when we lose the default network and have no replacement yet.
6427 // This will automatically be cleared after X seconds or a new default network
6428 // becomes CONNECTED, whichever happens first. The timer is started by the
6429 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006430 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006431 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006432 if (mNetTransitionWakeLock.isHeld()) {
6433 return;
6434 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006435 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006436 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6437 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006438 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006439 mWakelockLogs.log("ACQUIRE for " + forWhom);
6440 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006441 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006442 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006443 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006444 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006445
Hugo Benichi471b62a2017-03-30 23:18:10 +09006446 // Called when we gain a new default network to release the network transition wakelock in a
6447 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6448 // message is cancelled.
6449 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006450 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006451 if (!mNetTransitionWakeLock.isHeld()) {
6452 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006453 }
6454 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006455 // Cancel self timeout on wakelock hold.
6456 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6457 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6458 mHandler.sendMessageDelayed(msg, 1000);
6459 }
6460
6461 // Called when either message of ensureNetworkTransitionWakelock or
6462 // scheduleReleaseNetworkTransitionWakelock is processed.
6463 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6464 String event = eventName(eventId);
6465 synchronized (this) {
6466 if (!mNetTransitionWakeLock.isHeld()) {
6467 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006468 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006469 return;
6470 }
6471 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006472 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6473 mTotalWakelockDurationMs += lockDuration;
6474 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6475 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006476 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006477 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006478 }
6479
Robert Greenwalt986c7412010-09-08 15:24:47 -07006480 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006481 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006482 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006483 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006484 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006485 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006486 }
6487
Lorenzo Colittid6459092016-07-04 12:55:44 +09006488 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006489 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006490 enforceAccessPermission();
6491 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006492 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006493 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006494
6495 final NetworkAgentInfo nai;
6496 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006497 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006498 } else {
6499 nai = getNetworkAgentInfoForNetwork(network);
6500 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006501
6502 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006503 mHandler.obtainMessage(
6504 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006505 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006506
Hugo Benichid6b510a2017-04-06 17:22:18 +09006507 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006508 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006509 if (nai == null
6510 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006511 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006512 return;
6513 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006514 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006515 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006516 mConnectivityDiagnosticsHandler.sendMessage(
6517 mConnectivityDiagnosticsHandler.obtainMessage(
6518 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6519 new ReportedNetworkConnectivityInfo(
6520 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006521 return;
6522 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006523 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006524 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006525 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006526 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006527 // Validating a network that has not yet connected could result in a call to
6528 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006529 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006530 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006531 }
paulhu7aeba372020-12-30 00:42:19 +08006532 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6533 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006534 return;
6535 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006536
6537 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6538 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6539 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6540 // completed.
6541 mConnectivityDiagnosticsHandler.sendMessage(
6542 mConnectivityDiagnosticsHandler.obtainMessage(
6543 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6544 new ReportedNetworkConnectivityInfo(
6545 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006546 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006547 }
6548
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006549 // TODO: call into netd.
6550 private boolean queryUserAccess(int uid, Network network) {
6551 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6552 if (nai == null) return false;
6553
6554 // Any UID can use its default network.
6555 if (nai == getDefaultNetworkForUid(uid)) return true;
6556
6557 // Privileged apps can use any network.
6558 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6559 return true;
6560 }
6561
6562 // An unprivileged UID can use a VPN iff the VPN applies to it.
6563 if (nai.isVPN()) {
6564 return nai.networkCapabilities.appliesToUid(uid);
6565 }
6566
6567 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6568 // sockets, i.e., if it is the owner.
6569 final NetworkAgentInfo vpn = getVpnForUid(uid);
6570 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6571 && uid != vpn.networkCapabilities.getOwnerUid()) {
6572 return false;
6573 }
6574
6575 // The UID's permission must be at least sufficient for the network. Since the restricted
6576 // permission was already checked above, that just leaves background networks.
6577 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6578 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6579 }
6580
6581 // Unrestricted network. Anyone gets to use it.
6582 return true;
6583 }
6584
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006585 /**
6586 * Returns information about the proxy a certain network is using. If given a null network, it
6587 * it will return the proxy for the bound network for the caller app or the default proxy if
6588 * none.
6589 *
6590 * @param network the network we want to get the proxy information for.
6591 * @return Proxy information if a network has a proxy configured, or otherwise null.
6592 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006593 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006594 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006595 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006596 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006597 if (network == null) {
6598 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006599 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006600 true);
6601 if (activeNetwork == null) {
6602 return null;
6603 }
6604 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006605 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006606 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6607 // caller may not have.
6608 return getLinkPropertiesProxyInfo(network);
6609 }
6610 // No proxy info available if the calling UID does not have network access.
6611 return null;
6612 }
6613
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006614
6615 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006616 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6617 if (nai == null) return null;
6618 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006619 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6620 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006621 }
6622 }
6623
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006624 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006625 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006626 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006627 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006628 }
6629
Chalard Jean777e2e52018-06-07 18:02:37 +09006630 @Override
6631 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006632 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006633 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006634 }
6635
Aaron Huang9fe47be2021-06-08 13:11:45 +08006636 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006637 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006638 final NetworkAgentInfo nai = getDefaultNetwork();
6639 // TODO : this method should check that net == nai.network, unfortunately at this point
6640 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6641 // is only ever installed on the default network so in practice this is okay.
6642 if (null == nai) return;
6643 // PAC proxies only work on the default network. Therefore, only the default network
6644 // should have its link properties fixed up for PAC proxies.
6645 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6646 if (nai.everConnected()) {
6647 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6648 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006649 }
6650
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006651 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6652 // when any network changes proxy.
6653 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6654 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006655 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6656 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006657 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6658
Chalard Jean7d97afc2018-06-07 17:41:29 +09006659 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006660 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006661 }
6662 }
6663
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006664 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006665 final private HashMap<Uri, Integer> mUriEventMap;
6666 final private Context mContext;
6667 final private Handler mHandler;
6668
6669 SettingsObserver(Context context, Handler handler) {
6670 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006671 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006672 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006673 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006674 }
6675
Erik Kline05f2b402015-04-30 12:58:40 +09006676 void observe(Uri uri, int what) {
6677 mUriEventMap.put(uri, what);
6678 final ContentResolver resolver = mContext.getContentResolver();
6679 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006680 }
6681
6682 @Override
6683 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006684 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006685 }
6686
6687 @Override
6688 public void onChange(boolean selfChange, Uri uri) {
6689 final Integer what = mUriEventMap.get(uri);
6690 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006691 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006692 } else {
6693 loge("No matching event to send for URI=" + uri);
6694 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006695 }
6696 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006697
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006698 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006699 Log.d(TAG, s);
6700 }
6701
6702 private static void logw(String s) {
6703 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006704 }
6705
Daniel Brightf9e945b2020-06-15 16:10:01 -07006706 private static void logwtf(String s) {
6707 Log.wtf(TAG, s);
6708 }
6709
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006710 private static void logwtf(String s, Throwable t) {
6711 Log.wtf(TAG, s, t);
6712 }
6713
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006714 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006715 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006716 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006717
Hugo Benichi39621362017-02-11 17:04:43 +09006718 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006719 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006720 }
6721
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006722 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006723 * Return the information of all ongoing VPNs.
6724 *
6725 * <p>This method is used to update NetworkStatsService.
6726 *
6727 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006728 */
junyulai2050bed2021-01-23 09:46:34 +08006729 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006730 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006731 if (mLockdownEnabled) {
6732 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006733 }
junyulai2050bed2021-01-23 09:46:34 +08006734 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006735 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006736 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006737 if (info != null) {
6738 infoList.add(info);
6739 }
6740 }
junyulai2050bed2021-01-23 09:46:34 +08006741 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006742 }
6743
6744 /**
6745 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006746 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006747 */
junyulai2050bed2021-01-23 09:46:34 +08006748 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006749 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006750 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6751 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006752 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6753 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6754 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006755 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6756 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006757 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006758 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006759 }
6760 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006761
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006762 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006763
6764 List<String> interfaces = new ArrayList<>();
6765 for (Network network : underlyingNetworks) {
6766 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6767 if (underlyingNai == null) continue;
6768 LinkProperties lp = underlyingNai.linkProperties;
6769 for (String iface : lp.getAllInterfaceNames()) {
6770 if (!TextUtils.isEmpty(iface)) {
6771 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006772 }
6773 }
Benedict Wong34857f82019-06-12 17:46:15 +00006774 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006775
6776 if (interfaces.isEmpty()) return null;
6777
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006778 // Must be non-null or NetworkStatsService will crash.
6779 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6780 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006781 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006782 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006783
junyulai2050bed2021-01-23 09:46:34 +08006784 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6785 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006786 }
6787
James Mattisd31bdfa2020-12-23 16:37:26 -08006788 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006789 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6790 Network[] underlyingNetworks) {
6791 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006792 if (underlyingNetworks == null && defaultNetwork != null) {
6793 // null underlying networks means to track the default.
6794 underlyingNetworks = new Network[] { defaultNetwork };
6795 }
6796 return underlyingNetworks;
6797 }
6798
6799 // Returns true iff |network| is an underlying network of |nai|.
6800 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6801 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6802 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006803 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006804 final Network[] underlying = underlyingNetworksOrDefault(
6805 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006806 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006807 }
6808
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006809 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006810 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006811 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006812 * When underlying networks change, such networks may have to update capabilities to reflect
6813 * things like the metered bit, their transports, and so on. The capabilities are calculated
6814 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006815 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006816 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006817 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006818 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006819 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006820 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006821 }
6822 }
6823 }
6824
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006825 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6826 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6827 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6828 // a VPN is not up.
6829 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6830 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6831 for (UidRange range : blockedUidRanges) {
6832 if (range.contains(uid)) return true;
6833 }
6834 return false;
6835 }
6836
6837 @Override
6838 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006839 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006840 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6841 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6842 }
6843
6844 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6845 if (DBG) {
6846 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6847 + Arrays.toString(ranges));
6848 }
6849 // Cannot use a Set since the list of UID ranges might contain duplicates.
6850 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6851 for (int i = 0; i < ranges.length; i++) {
6852 if (requireVpn) {
6853 newVpnBlockedUidRanges.add(ranges[i]);
6854 } else {
6855 newVpnBlockedUidRanges.remove(ranges[i]);
6856 }
6857 }
6858
6859 try {
6860 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6861 } catch (RemoteException | ServiceSpecificException e) {
6862 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6863 + Arrays.toString(ranges) + "): netd command failed: " + e);
6864 }
6865
Chalard Jeandf29a852023-05-29 17:02:43 +09006866 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006867 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6868 }
6869
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006870 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6871 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006872 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6873 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006874 }
6875
6876 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6877 }
6878
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006879 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006880 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006881 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006882 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006883 }
6884
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006885 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6886 return mLockdownEnabled
6887 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6888 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006889 }
6890
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006891 private NetworkAgentInfo getLegacyLockdownNai() {
6892 if (!mLockdownEnabled) {
6893 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006894 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006895 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006896 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6897 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006898
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006899 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006900 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6901 // a local variable. There is no need to make a copy because its contents cannot change.
6902 final Network[] underlying = nai.declaredUnderlyingNetworks;
6903 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006904 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006905 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006906
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006907 // The legacy lockdown VPN always uses the default network.
6908 // If the VPN's underlying network is no longer the current default network, it means that
6909 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006910 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6911 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006912 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006913 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006914 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006915 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006916
6917 return nai;
6918 };
6919
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006920 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6921 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6922 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006923 private DetailedState getLegacyLockdownState(DetailedState origState) {
6924 if (origState != DetailedState.CONNECTED) {
6925 return origState;
6926 }
6927 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6928 ? DetailedState.CONNECTING
6929 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006930 }
6931
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006932 private void filterForLegacyLockdown(NetworkInfo ni) {
6933 if (!mLockdownEnabled || !ni.isConnected()) return;
6934 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6935 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6936 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6937 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6938 // network, this time with a state of CONNECTED.
6939 //
6940 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6941 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6942 // is not too far off the truth, since an always-on VPN, when not connected, is always
6943 // trying to reconnect.
6944 if (getLegacyLockdownNai() == null) {
6945 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6946 }
6947 }
6948
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006949 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006950 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006951 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006952 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006953 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6954 return;
6955 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006956 final long ident = Binder.clearCallingIdentity();
6957 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006958 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006959 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006960 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006961 } finally {
6962 Binder.restoreCallingIdentity(ident);
6963 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006964 }
Wink Savillecb117d32013-08-29 14:57:08 -07006965
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006966 @Override
6967 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006968 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006969 final long ident = Binder.clearCallingIdentity();
6970 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006971 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006972 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006973 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6974 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006975 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006976 } finally {
6977 Binder.restoreCallingIdentity(ident);
6978 }
6979 }
6980
James Mattis02220e22021-03-13 19:27:21 -08006981 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006982 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6983 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6984 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006985 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006986 }
6987
James Mattis02220e22021-03-13 19:27:21 -08006988 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006989 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006990 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006991 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6992 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006993 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006994 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6995 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6996 }
junyulaid91e7052020-08-28 13:44:33 +08006997 }
6998
James Mattis02220e22021-03-13 19:27:21 -08006999 private void onPackageChanged(@NonNull final String packageName) {
7000 // This is necessary in case a package is added or removed, but also when it's replaced to
7001 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
7002 // as one in the preferences, then it should follow the same routing as that other package,
7003 // which means updating the rules is never to be needed in this case (whether it joins or
7004 // leaves a UID with a preference).
7005 if (isMappedInOemNetworkPreference(packageName)) {
7006 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7007 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007008
7009 // Invalidates cache entry when the package is updated.
7010 synchronized (mSelfCertifiedCapabilityCache) {
7011 mSelfCertifiedCapabilityCache.remove(packageName);
7012 }
James Mattis02220e22021-03-13 19:27:21 -08007013 }
7014
7015 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007016 @Override
7017 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007018 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007019 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007020 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007021
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007022 // User should be filled for below intents, check the existence.
7023 if (user == null) {
7024 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7025 return;
7026 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007027
Lorenzo Colitticd675292021-02-04 17:32:07 +09007028 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007029 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007030 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007031 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007032 } else {
junyulaid91e7052020-08-28 13:44:33 +08007033 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007034 }
7035 }
7036 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007037
James Mattis02220e22021-03-13 19:27:21 -08007038 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7039 @Override
7040 public void onReceive(Context context, Intent intent) {
7041 ensureRunningOnConnectivityServiceThread();
7042 switch (intent.getAction()) {
7043 case Intent.ACTION_PACKAGE_ADDED:
7044 case Intent.ACTION_PACKAGE_REMOVED:
7045 case Intent.ACTION_PACKAGE_REPLACED:
7046 onPackageChanged(intent.getData().getSchemeSpecificPart());
7047 break;
7048 default:
7049 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7050 }
7051 }
7052 };
7053
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007054 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007055 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007056
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007057 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007058 public final String name;
7059 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007060 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007061 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007062
lifraf3a3492021-03-10 13:58:14 +08007063 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7064 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007065 this.name = name;
7066 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007067 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007068 mDeathRecipient = deathRecipient;
7069
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007070 if (mDeathRecipient == null) {
7071 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007072 }
7073 }
7074
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007075 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007076 try {
7077 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7078 } catch (RemoteException e) {
7079 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007080 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007081 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007082 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007083
James Mattis4fce5d12020-11-12 15:53:42 -08007084 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7085 for (int i = 0; i < requests.size(); i++) {
7086 ensureNetworkRequestHasType(requests.get(i));
7087 }
7088 }
7089
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007090 private void ensureNetworkRequestHasType(NetworkRequest request) {
7091 if (request.type == NetworkRequest.Type.NONE) {
7092 throw new IllegalArgumentException(
7093 "All NetworkRequests in ConnectivityService must have a type");
7094 }
7095 }
7096
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007097 /**
7098 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007099 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007100 */
James Mattis258ea3c2020-11-15 15:04:40 -08007101 @VisibleForTesting
7102 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007103 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7104 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007105 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007106
James Mattisa076c532020-12-02 14:12:41 -08007107 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7108 void setSatisfier(
7109 @Nullable final NetworkAgentInfo satisfier,
7110 @Nullable final NetworkRequest activeRequest) {
7111 mSatisfier = satisfier;
7112 mActiveRequest = activeRequest;
7113 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007114
James Mattisd31bdfa2020-12-23 16:37:26 -08007115 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007116 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007117 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007118 private NetworkAgentInfo mSatisfier;
7119 NetworkAgentInfo getSatisfier() {
7120 return mSatisfier;
7121 }
7122
7123 // The request in mRequests assigned to a network agent. This is null if none of the
7124 // requests in mRequests can be satisfied. This member has the constraint of only being
7125 // accessible on the handler thread.
7126 @Nullable
7127 private NetworkRequest mActiveRequest;
7128 NetworkRequest getActiveRequest() {
7129 return mActiveRequest;
7130 }
7131
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007132 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007133 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007134 @Nullable
7135 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007136
7137 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007138 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007139 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007140 final int mPid;
7141 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007142 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007143 @Nullable
7144 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007145
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007146 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007147 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007148
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007149 // Effective UID of this request. This is different from mUid when a privileged process
7150 // files a request on behalf of another UID. This UID is used to determine blocked status,
7151 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7152 // maximum limit of registered callbacks per UID.
7153 final int mAsUid;
7154
paulhu48291862021-07-14 14:53:57 +08007155 // Preference order of this request.
7156 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007157
James Mattis3ce3d3c2021-02-09 18:18:28 -08007158 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7159 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7160 // maintained for keying off of. This is only a concern when the original nri
7161 // mNetworkRequests changes which happens currently for apps that register callbacks to
7162 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7163 // that match the per-app default nri that currently tracks the calling app's uid so that
7164 // callbacks are fired at the appropriate time. When the callbacks fire,
7165 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7166 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7167 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7168 @NonNull
7169 private final NetworkRequest mNetworkRequestForCallback;
7170 NetworkRequest getNetworkRequestForCallback() {
7171 return mNetworkRequestForCallback;
7172 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007173
James Mattisd31bdfa2020-12-23 16:37:26 -08007174 /**
7175 * Get the list of UIDs this nri applies to.
7176 */
7177 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007178 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007179 // networkCapabilities.getUids() returns a defensive copy.
7180 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007181 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7182 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007183 }
7184
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007185 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7186 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007187 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007188 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007189 }
7190
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007191 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007192 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007193 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007194 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007195 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007196 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007197 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007198 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007199 mBinder = null;
7200 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007201 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007202 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007203 mPerUidCounter = getRequestCounter(this);
7204 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007205 /**
7206 * Location sensitive data not included in pending intent. Only included in
7207 * {@link NetworkCallback}.
7208 */
7209 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007210 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007211 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007212 }
7213
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007214 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007215 @Nullable final IBinder binder,
7216 @NetworkCallback.Flag int callbackFlags,
7217 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007218 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7219 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007220 }
7221
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007222 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007223 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007224 @Nullable final IBinder binder,
7225 @NetworkCallback.Flag int callbackFlags,
7226 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007227 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007228 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007229 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007230 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007231 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007232 mBinder = binder;
7233 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007234 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007235 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007236 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007237 mPerUidCounter = getRequestCounter(this);
7238 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007239 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007240 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007241 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007242 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007243 }
7244
James Mattis3ce3d3c2021-02-09 18:18:28 -08007245 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7246 @NonNull final List<NetworkRequest> r) {
7247 super();
7248 ensureAllNetworkRequestsHaveType(r);
7249 mRequests = initializeRequests(r);
7250 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007251 final NetworkAgentInfo satisfier = nri.getSatisfier();
7252 if (null != satisfier) {
7253 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7254 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007255 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007256 // As this code creates a new NRI with a new set of requests, figure out which of
7257 // the list of requests should be the active request. It is always the first
7258 // request of the list that can be satisfied by the satisfier since the order of
7259 // requests is a priority order.
7260 // Note even in the presence of a satisfier there may not be an active request,
7261 // when the satisfier is the no-service network.
7262 NetworkRequest activeRequest = null;
7263 for (final NetworkRequest candidate : r) {
7264 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7265 activeRequest = candidate;
7266 break;
7267 }
7268 }
7269 setSatisfier(satisfier, activeRequest);
7270 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007271 mMessenger = nri.mMessenger;
7272 mBinder = nri.mBinder;
7273 mPid = nri.mPid;
7274 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007275 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007276 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007277 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007278 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007279 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007280 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007281 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007282 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007283 }
7284
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007285 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007286 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007287 }
7288
paulhue9913722021-05-26 15:19:20 +08007289 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007290 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007291 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007292 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007293 }
7294
James Mattis2516da32021-01-31 17:06:19 -08007295 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7296 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7297 // false.
7298 boolean isBeingSatisfied() {
7299 return (null != mSatisfier && null != mActiveRequest);
7300 }
7301
James Mattis3d229892020-11-16 16:46:28 -08007302 boolean isMultilayerRequest() {
7303 return mRequests.size() > 1;
7304 }
7305
James Mattis45d81842021-01-10 14:24:24 -08007306 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7307 // Creating a defensive copy to prevent the sender from modifying the list being
7308 // reflected in the return value of this method.
7309 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007310 return Collections.unmodifiableList(tempRequests);
7311 }
7312
James Mattisb1392002021-03-31 13:57:52 -07007313 void linkDeathRecipient() {
7314 if (null != mBinder) {
7315 try {
7316 mBinder.linkToDeath(this, 0);
7317 } catch (RemoteException e) {
7318 binderDied();
7319 }
7320 }
7321 }
7322
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007323 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007324 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007325 try {
7326 mBinder.unlinkToDeath(this, 0);
7327 } catch (NoSuchElementException e) {
7328 // Temporary workaround for b/194394697 pending analysis of additional logs
7329 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7330 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007331 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007332 }
7333
paulhu48291862021-07-14 14:53:57 +08007334 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7335 // Compare two preference orders.
7336 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007337 }
7338
paulhu48291862021-07-14 14:53:57 +08007339 int getPreferenceOrderForNetd() {
7340 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7341 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7342 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007343 }
paulhu48291862021-07-14 14:53:57 +08007344 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007345 }
7346
James Mattis4fce5d12020-11-12 15:53:42 -08007347 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007348 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007349 // As an immutable collection, mRequests cannot change by the time the
7350 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7351 // is acceptable. Use handleReleaseNetworkRequest and not directly
7352 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7353 // the app already unregistered the request.
7354 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7355 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007356 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007357
James Mattis4fce5d12020-11-12 15:53:42 -08007358 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007359 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007360 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7361 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007362 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007363 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007364 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007365 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007366 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007367 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007368 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007369 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007370 }
7371
Junyu Lai00d92df2022-07-05 11:01:52 +08007372 // Keep backward compatibility since the ServiceSpecificException is used by
7373 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7374 public static class RequestInfoPerUidCounter extends PerUidCounter {
7375 RequestInfoPerUidCounter(int maxCountPerUid) {
7376 super(maxCountPerUid);
7377 }
7378
7379 @Override
7380 public synchronized void incrementCountOrThrow(int uid) {
7381 try {
7382 super.incrementCountOrThrow(uid);
7383 } catch (IllegalStateException e) {
7384 throw new ServiceSpecificException(
7385 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7386 "Uid " + uid + " exceeded its allotted requests limit");
7387 }
7388 }
7389
7390 @Override
7391 public synchronized void decrementCountOrThrow(int uid) {
7392 throw new UnsupportedOperationException("Use decrementCount instead.");
7393 }
7394
7395 public synchronized void decrementCount(int uid) {
7396 try {
7397 super.decrementCountOrThrow(uid);
7398 } catch (IllegalStateException e) {
7399 logwtf("Exception when decrement per uid request count: ", e);
7400 }
7401 }
7402 }
7403
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007404 // This checks that the passed capabilities either do not request a
7405 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007406 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007407 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007408 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007409 throw new SecurityException("Insufficient permissions to request a specific SSID");
7410 }
paulhu1a407652019-03-22 16:35:06 +08007411
7412 if (nc.hasSignalStrength()
7413 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7414 throw new SecurityException(
7415 "Insufficient permissions to request a specific signal strength");
7416 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007417 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007418
junyulai2217bec2021-04-14 23:33:31 +08007419 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007420 enforceNetworkFactoryPermission();
7421 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007422 }
7423
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007424 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007425 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007426 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007427 // mNetworkRequests may contain the same value multiple times in case of
7428 // multilayer requests. It won't matter in this case because the thresholds
7429 // will then be the same and be deduplicated as they enter the `thresholds` set.
7430 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007431 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7432 for (final NetworkRequest req : nri.mRequests) {
7433 if (req.networkCapabilities.hasSignalStrength()
7434 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7435 thresholds.add(req.networkCapabilities.getSignalStrength());
7436 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007437 }
7438 }
7439 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007440 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007441 }
7442
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007443 private void updateSignalStrengthThresholds(
7444 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007445 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007446
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007447 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007448 String detail;
7449 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7450 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7451 } else {
7452 detail = reason;
7453 }
7454 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007455 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007456 }
7457
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007458 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007459 }
7460
Chalard Jeandd421992021-12-16 23:16:02 +09007461 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007462 if (nc == null) {
7463 return;
7464 }
7465 NetworkSpecifier ns = nc.getNetworkSpecifier();
7466 if (ns == null) {
7467 return;
7468 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007469 if (ns instanceof MatchAllNetworkSpecifier) {
7470 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7471 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007472 }
7473
Chalard Jeandd421992021-12-16 23:16:02 +09007474 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007475 ensureValidNetworkSpecifier(nc);
7476 if (nc.isPrivateDnsBroken()) {
7477 throw new IllegalArgumentException("Can't request broken private DNS");
7478 }
Chalard Jeande665262022-02-25 16:12:12 +09007479 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007480 throw new IllegalArgumentException("Can't request access UIDs");
7481 }
lucasline117e2e2019-10-22 18:27:33 +08007482 }
7483
Chalard Jeandd421992021-12-16 23:16:02 +09007484 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7485 ensureListenableCapabilities(nc);
7486 final String badCapability = nc.describeFirstNonRequestableCapability();
7487 if (badCapability != null) {
7488 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7489 }
7490 }
7491
Chiachang Wang3bc52762021-11-25 14:17:57 +08007492 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7493 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007494 private boolean isTargetSdkAtleast(int version, int callingUid,
7495 @NonNull String callingPackageName) {
7496 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007497 final PackageManager pm =
7498 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007499 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007500 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007501 if (callingVersion < version) return false;
7502 } catch (PackageManager.NameNotFoundException e) { }
7503 return true;
7504 }
7505
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007506 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007507 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007508 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007509 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007510 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007511 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007512 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7513 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007514 throw new SecurityException("Insufficient permissions to specify legacy type");
7515 }
markchienfac84a22020-03-18 21:16:15 +08007516 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007517 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007518 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007519 // Privileged callers can track the default network of another UID by passing in a UID.
7520 if (asUid != Process.INVALID_UID) {
7521 enforceSettingsPermission();
7522 } else {
7523 asUid = callingUid;
7524 }
junyulaiad010792021-01-11 16:53:38 +08007525 final NetworkRequest.Type reqType;
7526 try {
7527 reqType = NetworkRequest.Type.values()[reqTypeInt];
7528 } catch (ArrayIndexOutOfBoundsException e) {
7529 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7530 }
7531 switch (reqType) {
7532 case TRACK_DEFAULT:
7533 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007534 // is unused and will be replaced by ones appropriate for the UID (usually, the
7535 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007536 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007537 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007538 enforceAccessPermission();
7539 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007540 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007541 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007542 networkCapabilities = new NetworkCapabilities(defaultNc);
7543 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007544 case BACKGROUND_REQUEST:
7545 enforceNetworkStackOrSettingsPermission();
7546 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007547 case REQUEST:
7548 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7549 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007550 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007551 // TODO: this is incorrect. We mark the request as metered or not depending on
7552 // the state of the app when the request is filed, but we never change the
7553 // request if the app changes network state. http://b/29964605
7554 enforceMeteredApnPolicy(networkCapabilities);
7555 break;
junyulai1b1c8742021-03-12 20:05:08 +08007556 case LISTEN_FOR_BEST:
7557 enforceAccessPermission();
7558 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7559 break;
junyulaiad010792021-01-11 16:53:38 +08007560 default:
7561 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007562 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007563 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007564 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007565 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007566
junyulai1b1c8742021-03-12 20:05:08 +08007567 // Enforce FOREGROUND if the caller does not have permission to use background network.
7568 if (reqType == LISTEN_FOR_BEST) {
7569 restrictBackgroundRequestForCaller(networkCapabilities);
7570 }
7571
7572 // Set the UID range for this request to the single UID of the requester, unless the
7573 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007574 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7575 // are no visible methods to set the UIDs, an app could use reflection to try and get
7576 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007577 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007578 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7579 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007580
Etan Cohen85000162017-02-05 10:42:27 -08007581 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007582 throw new IllegalArgumentException("Bad timeout specified");
7583 }
Etan Cohen9786d922015-11-18 10:56:15 -08007584
James Mattis3ce3d3c2021-02-09 18:18:28 -08007585 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007586 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007587 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007588 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007589 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007590 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007591
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007592 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7593 // copied from the default request above. (This is necessary to ensure, for example, that
7594 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7595 // changes don't alter request matching.
7596 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7597 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007598 throw new IllegalStateException(
7599 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007600 + networkCapabilities + " vs. " + defaultNc);
7601 }
7602
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007603 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007604 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007605 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007606 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007607 }
7608 return networkRequest;
7609 }
7610
James Mattis3ce3d3c2021-02-09 18:18:28 -08007611 /**
7612 * Return the nri to be used when registering a network request. Specifically, this is used with
7613 * requests registered to track the default request. If there is currently a per-app default
7614 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7615 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007616 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7617 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007618 * @param nr the network request for the nri.
7619 * @param msgr the messenger for the nri.
7620 * @param binder the binder for the nri.
7621 * @param callingAttributionTag the calling attribution tag for the nri.
7622 * @return the nri to register.
7623 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007624 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007625 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007626 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007627 @Nullable String callingAttributionTag) {
7628 final List<NetworkRequest> requests;
7629 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7630 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007631 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007632 } else {
7633 requests = Collections.singletonList(nr);
7634 }
Roshan Pius951c0032020-12-22 15:10:42 -08007635 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007636 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007637 }
7638
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007639 private boolean shouldCheckCapabilitiesDeclaration(
7640 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7641 @NonNull final String callingPackageName) {
7642 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7643 // Only run the check if the change is enabled.
7644 if (!mDeps.isChangeEnabled(
7645 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7646 callingPackageName, user)) {
7647 return false;
7648 }
7649
7650 return networkCapabilities.hasCapability(
7651 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7652 || networkCapabilities.hasCapability(
7653 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7654 }
7655
7656 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007657 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007658 // This check is added to fix the linter error for "current min is 30", which is not going
7659 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007660 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007661 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7662 return;
7663 }
7664 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007665 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007666 try {
7667 synchronized (mSelfCertifiedCapabilityCache) {
7668 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7669 callerPackageName);
7670 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007671 final PackageManager packageManager =
7672 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
7673 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007674 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7675 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7676 callerPackageName
7677 );
7678 final XmlResourceParser parser = packageManager
7679 .getResourcesForApplication(callerPackageName)
7680 .getXml(networkSliceProperty.getResourceId());
7681 applicationNetworkCapabilities =
7682 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7683 mSelfCertifiedCapabilityCache.put(callerPackageName,
7684 applicationNetworkCapabilities);
7685 }
7686
7687 }
7688 } catch (PackageManager.NameNotFoundException ne) {
7689 throw new SecurityException(
7690 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7691 + " property");
7692 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7693 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007694 } finally {
7695 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007696 }
7697
7698 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7699 networkCapabilities);
7700 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007701 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007702 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007703 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7704 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007705 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
7706 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007707 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007708 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007709 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7710 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7711 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7712 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007713 }
junyulai96bd9fe2022-03-08 17:36:42 +08007714 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007715 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007716 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007717 }
7718 }
7719
fenglu3f357402015-03-20 11:29:56 -07007720 @Override
fenglub00f4882015-04-21 17:12:05 -07007721 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007722 enforceAccessPermission();
7723 NetworkAgentInfo nai = null;
7724 if (network == null) {
7725 return false;
7726 }
7727 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007728 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007729 }
7730 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007731 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007732 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007733 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007734 Integer uidReqs = mBandwidthRequests.get(uid);
7735 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007736 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007737 }
7738 mBandwidthRequests.put(uid, ++uidReqs);
7739 }
fenglu3f357402015-03-20 11:29:56 -07007740 return true;
7741 }
7742 return false;
7743 }
7744
Felipe Leme0a5ae422016-06-20 16:36:29 -07007745 private boolean isSystem(int uid) {
7746 return uid < Process.FIRST_APPLICATION_UID;
7747 }
fenglu3f357402015-03-20 11:29:56 -07007748
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007749 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007750 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007751 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007752 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007753 return;
7754 }
Hugo Benichi39621362017-02-11 17:04:43 +09007755 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7756 // Policy already enforced.
7757 return;
7758 }
paulhuaf50d7d2020-12-24 19:47:34 +08007759 final long ident = Binder.clearCallingIdentity();
7760 try {
7761 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7762 // If UID is restricted, don't allow them to bring up metered APNs.
7763 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7764 }
7765 } finally {
7766 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007767 }
7768 }
7769
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007770 @Override
7771 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007772 PendingIntent operation, @NonNull String callingPackageName,
7773 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007774 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007775 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007776 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007777 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007778 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007779 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007780 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007781 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007782 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007783 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7784 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007785
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007786 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007787 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007788 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7789 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007790 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007791 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7792 nri));
7793 return networkRequest;
7794 }
7795
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007796 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7797 mHandler.sendMessageDelayed(
7798 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007799 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007800 }
7801
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007802 @Override
7803 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007804 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007805 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007806 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007807 }
7808
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007809 // In order to implement the compatibility measure for pre-M apps that call
7810 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7811 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7812 // This ensures it has permission to do so.
7813 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7814 if (nc == null) {
7815 return false;
7816 }
7817 int[] transportTypes = nc.getTransportTypes();
7818 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7819 return false;
7820 }
7821 try {
7822 mContext.enforceCallingOrSelfPermission(
7823 android.Manifest.permission.ACCESS_WIFI_STATE,
7824 "ConnectivityService");
7825 } catch (SecurityException e) {
7826 return false;
7827 }
7828 return true;
7829 }
7830
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007831 @Override
7832 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007833 Messenger messenger, IBinder binder,
7834 @NetworkCallback.Flag int callbackFlags,
7835 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007836 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007837 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7838 enforceAccessPermission();
7839 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007840
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007841 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007842 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007843 Binder.getCallingPid(), callingUid, callingPackageName);
7844 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007845 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7846 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7847 // onLost and onAvailable callbacks when networks move in and out of the background.
7848 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7849 // can't request networks.
7850 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007851 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007852
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007853 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007854 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007855 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007856 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007857 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007858 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007859
7860 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7861 return networkRequest;
7862 }
7863
7864 @Override
7865 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007866 PendingIntent operation, @NonNull String callingPackageName,
7867 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007868 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007869 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007870 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7871 enforceAccessPermission();
7872 }
Chalard Jeandd421992021-12-16 23:16:02 +09007873 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007874 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007875 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007876 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007877 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007878
7879 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007880 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007881 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7882 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007883 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007884
WeiZhang1cc3f172021-06-03 19:02:04 -05007885 mHandler.sendMessage(mHandler.obtainMessage(
7886 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007887 }
7888
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007889 /** Returns the next Network provider ID. */
7890 public final int nextNetworkProviderId() {
7891 return mNextNetworkProviderId.getAndIncrement();
7892 }
7893
Erik Kline0c04b742016-07-07 16:50:58 +09007894 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007895 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007896 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007897 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007898 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007899 }
7900
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007901 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7902 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007903 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7904 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7905 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007906 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007907 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007908 return;
7909 }
7910
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007911 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7912 mNetworkProviderInfos.put(npi.messenger, npi);
7913 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007914 }
7915
7916 @Override
7917 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007918 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007919 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007920 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007921 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007922 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7923 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007924 }
7925
7926 @Override
7927 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007928 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007929 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007930 }
7931
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007932 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007933 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007934 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7935 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007936 Objects.requireNonNull(score);
7937 Objects.requireNonNull(caps);
7938 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007939 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007940 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007941 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7942 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007943 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7944 }
7945
Chalard Jeanbb902a52021-08-18 01:35:19 +09007946 private void updateOfferScore(final NetworkOffer offer) {
7947 final boolean yieldToBadWiFi =
7948 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7949 final NetworkOffer newOffer = new NetworkOffer(
7950 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7951 offer.caps, offer.callback, offer.providerId);
7952 if (offer.equals(newOffer)) return;
7953 handleRegisterNetworkOffer(newOffer);
7954 }
7955
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007956 @Override
7957 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007958 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007959 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7960 }
7961
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007962 private void handleUnregisterNetworkProvider(Messenger messenger) {
7963 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7964 if (npi == null) {
7965 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007966 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007967 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007968 // Unregister all the offers from this provider
7969 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7970 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007971 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007972 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7973 toRemove.add(noi);
7974 }
7975 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007976 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007977 handleUnregisterNetworkOffer(noi);
7978 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007979 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007980 }
7981
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007982 @Override
James Mattisf7027322020-12-13 16:28:14 -08007983 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007984 if (request.hasTransport(TRANSPORT_TEST)) {
7985 enforceNetworkFactoryOrTestNetworksPermission();
7986 } else {
7987 enforceNetworkFactoryPermission();
7988 }
James Mattisf7027322020-12-13 16:28:14 -08007989 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7990 if (nri != null) {
7991 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7992 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7993 mHandler.post(() -> handleReleaseNetworkRequest(
7994 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7995 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007996 }
7997
Paul Jensen1f567382015-02-13 14:18:39 -05007998 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7999 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008000 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05008001 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008002 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05008003 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008004 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008005
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008006 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05008007 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008008 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008009
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008010 // UID ranges for users that are currently blocked by VPNs.
8011 // This array is accessed and iterated on multiple threads without holding locks, so its
8012 // contents must never be mutated. When the ranges change, the array is replaced with a new one
8013 // (on the handler thread).
8014 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
8015
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008016 // Must only be accessed on the handler thread
8017 @NonNull
8018 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8019
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008020 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008021 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008022
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008023 // Current OEM network preferences. This object must only be written to on the handler thread.
8024 // Since it is immutable and always non-null, other threads may read it if they only care
8025 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008026 @NonNull
8027 private OemNetworkPreferences mOemNetworkPreferences =
8028 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008029 // Current per-profile network preferences. This object follows the same threading rules as
8030 // the OEM network preferences above.
8031 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008032 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8033 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008034
lucaslin3ba7cc22022-12-19 02:35:33 +00008035 // Current VPN network preferences. This object follows the same threading rules as the OEM
8036 // network preferences above.
8037 @NonNull
8038 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8039 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8040
paulhu51f77dc2021-06-07 02:34:20 +00008041 // A set of UIDs that should use mobile data preferentially if available. This object follows
8042 // the same threading rules as the OEM network preferences above.
8043 @NonNull
8044 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8045
James Mattiscb1e0362021-04-06 17:07:42 -07008046 // OemNetworkPreferences activity String log entries.
8047 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8048 @NonNull
8049 private final LocalLog mOemNetworkPreferencesLogs =
8050 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8051
James Mattis02220e22021-03-13 19:27:21 -08008052 /**
8053 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8054 * @param packageName the package name to check existence of a mapping for.
8055 * @return true if a mapping exists, false otherwise
8056 */
8057 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8058 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8059 }
8060
James Mattise3ef1912020-12-20 11:09:58 -08008061 // The always-on request for an Internet-capable network that apps without a specific default
8062 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008063 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008064 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008065 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008066 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008067 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008068 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008069 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008070
James Mattisd31bdfa2020-12-23 16:37:26 -08008071 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8072 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8073 }
8074
8075 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008076 * Return the default network request currently tracking the given uid.
8077 * @param uid the uid to check.
8078 * @return the NetworkRequestInfo tracking the given uid.
8079 */
8080 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008081 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008082 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008083 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008084 // Checking the first request is sufficient as only multilayer requests will have more
8085 // than one request and for multilayer, all requests will track the same uids.
8086 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008087 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008088 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008089 highestPriorityNri = nri;
8090 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008091 }
8092 }
paulhuaa0743d2021-05-26 21:56:03 +08008093 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008094 }
8095
8096 /**
8097 * Get a copy of the network requests of the default request that is currently tracking the
8098 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008099 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8100 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008101 * @param requestorUid the uid to check the default for.
8102 * @param requestorPackageName the requestor's package name.
8103 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8104 */
8105 @NonNull
8106 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008107 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008108 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008109 getDefaultRequestTrackingUid(asUid).mRequests,
8110 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008111 }
8112
8113 /**
8114 * Copy the given nri's NetworkRequest collection.
8115 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008116 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8117 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008118 * @param requestorUid the uid to set on the copied collection.
8119 * @param requestorPackageName the package name to set on the copied collection.
8120 * @return the copied NetworkRequest collection.
8121 */
8122 @NonNull
8123 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008124 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8125 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008126 final List<NetworkRequest> requests = new ArrayList<>();
8127 for (final NetworkRequest nr : requestsToCopy) {
8128 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008129 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008130 nr.legacyType, nextNetworkRequestId(), nr.type));
8131 }
8132 return requests;
8133 }
8134
8135 @NonNull
8136 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008137 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8138 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008139 // These capabilities are for a TRACK_DEFAULT callback, so:
8140 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8141 // mDefaultRequest and a per-UID default request.
8142 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008143 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008144 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008145 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8146 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008147 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008148 restrictRequestUidsForCallerAndSetRequestorInfo(
8149 netCap, requestorUid, requestorPackageName);
8150 return netCap;
8151 }
8152
8153 /**
8154 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8155 * @param nr the network request to check for equality against.
8156 * @return the nri if one exists, null otherwise.
8157 */
8158 @Nullable
8159 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8160 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8161 if (nri.getNetworkRequestForCallback().equals(nr)) {
8162 return nri;
8163 }
8164 }
8165 return null;
8166 }
8167
8168 /**
8169 * Check if an nri is currently being managed by per-app default networking.
8170 * @param nri the nri to check.
8171 * @return true if this nri is currently being managed by per-app default networking.
8172 */
8173 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8174 // nri.mRequests.get(0) is only different from the original request filed in
8175 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8176 // functionality therefore if these two don't match, it means this particular nri is
8177 // currently being managed by a per-app default.
8178 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8179 }
8180
8181 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008182 * Determine if an nri is a managed default request that disallows default networking.
8183 * @param nri the request to evaluate
8184 * @return true if device-default networking is disallowed
8185 */
8186 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8187 // Check if this nri is a managed default that supports the default network at its
8188 // lowest priority request.
8189 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8190 final NetworkCapabilities lowestPriorityNetCap =
8191 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8192 return isPerAppDefaultRequest(nri)
8193 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8194 lowestPriorityNetCap));
8195 }
8196
Erik Kline05f2b402015-04-30 12:58:40 +09008197 // Request used to optionally keep mobile data active even when higher
8198 // priority networks like Wi-Fi are active.
8199 private final NetworkRequest mDefaultMobileDataRequest;
8200
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008201 // Request used to optionally keep wifi data active even when higher
8202 // priority networks like ethernet are active.
8203 private final NetworkRequest mDefaultWifiRequest;
8204
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008205 // Request used to optionally keep vehicle internal network always active
8206 private final NetworkRequest mDefaultVehicleRequest;
8207
James Mattisd31bdfa2020-12-23 16:37:26 -08008208 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8209 // network with no service. This NAI should never be matched against, nor should any public API
8210 // ever return the associated network. For this reason, this NAI is not in the list of available
8211 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8212 // default requests that don't support using the device default network which will ultimately
8213 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8214 @VisibleForTesting
8215 final NetworkAgentInfo mNoServiceNetwork;
8216
Chalard Jean5b409c72021-02-04 13:12:59 +09008217 // The NetworkAgentInfo currently satisfying the default request, if any.
8218 private NetworkAgentInfo getDefaultNetwork() {
8219 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008220 }
8221
James Mattis2516da32021-01-31 17:06:19 -08008222 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008223 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008224 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8225 // Currently, all network requests will have the same uids therefore checking the first
8226 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008227 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008228 if (null == uids) {
8229 continue;
8230 }
8231 for (final UidRange range : uids) {
8232 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008233 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008234 highestPriorityNri = nri;
8235 }
James Mattis2516da32021-01-31 17:06:19 -08008236 }
8237 }
8238 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008239 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008240 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008241 }
8242
Varun Ananddf569952019-02-06 10:13:38 -08008243 @Nullable
8244 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8245 return nai != null ? nai.network : null;
8246 }
8247
8248 private void ensureRunningOnConnectivityServiceThread() {
8249 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8250 throw new IllegalStateException(
8251 "Not running on ConnectivityService thread: "
8252 + Thread.currentThread().getName());
8253 }
8254 }
8255
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008256 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008257 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8258 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008259 }
8260
Chalard Jean29d06db2018-05-02 21:14:54 +09008261 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008262 * Returns whether local agents are supported on this device.
8263 *
8264 * Local agents are supported from U on TVs, and from V on all devices.
8265 */
8266 @VisibleForTesting
8267 public boolean areLocalAgentsSupported() {
8268 final PackageManager pm = mContext.getPackageManager();
8269 // Local agents are supported starting on U on TVs and on V on everything else.
8270 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8271 }
8272
8273 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008274 * Register a new agent with ConnectivityService to handle a network.
8275 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008276 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008277 * @param networkInfo the initial info associated with this network. It can be updated later :
8278 * see {@link #updateNetworkInfo}.
8279 * @param linkProperties the initial link properties of this network. They can be updated
8280 * later : see {@link #updateLinkProperties}.
8281 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008282 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008283 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008284 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008285 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008286 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008287 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008288 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008289 public Network registerNetworkAgent(INetworkAgent na,
8290 NetworkInfo networkInfo,
8291 LinkProperties linkProperties,
8292 NetworkCapabilities networkCapabilities,
8293 @NonNull NetworkScore initialScore,
8294 @Nullable LocalNetworkConfig localNetworkConfig,
8295 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008296 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008297 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8298 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8299 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008300 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008301 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008302 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008303 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008304 } else {
8305 enforceNetworkFactoryPermission();
8306 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008307 final boolean hasLocalCap =
8308 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8309 if (hasLocalCap && !areLocalAgentsSupported()) {
8310 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8311 throw new IllegalArgumentException("Local agents are not supported in this version");
8312 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008313 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8314 if (hasLocalCap != hasLocalNetworkConfig) {
8315 throw new IllegalArgumentException(null != localNetworkConfig
8316 ? "Only local network agents can have a LocalNetworkConfig"
8317 : "Local network agents must have a LocalNetworkConfig"
8318 );
8319 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008320
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008321 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008322 final long token = Binder.clearCallingIdentity();
8323 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008324 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008325 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8326 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008327 } finally {
8328 Binder.restoreCallingIdentity(token);
8329 }
8330 }
8331
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008332 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008333 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008334 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8335 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008336 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008337
Chalard Jeandbc46952022-02-02 00:14:18 +09008338 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8339 // and mutate them at any time.
8340 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8341 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8342 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008343 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008344
Chalard Jean366c5252022-01-25 18:27:53 +09008345 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008346 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008347 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8348 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008349 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008350 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008351 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8352 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8353 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008354
Chalard Jeandbc46952022-02-02 00:14:18 +09008355 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008356 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008357 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008358 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008359 mDeps.getNetworkStack().makeNetworkMonitor(
8360 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008361 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8362 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008363 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008364 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008365 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008366 }
8367
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008368 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008369 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008370 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008371 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008372 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008373 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8374 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8375 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008376
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008377 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008378
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008379 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008380 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008381 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008382 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008383
8384 try {
8385 networkMonitor.start();
8386 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008387 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008388 }
Chalard Jean366c5252022-01-25 18:27:53 +09008389
Chalard Jean1e4c2182023-10-06 18:45:53 +09008390 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008391 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008392 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008393 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008394 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008395 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008396 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008397 }
8398
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008399 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8400 @NonNull public final NetworkOffer offer;
8401
8402 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8403 this.offer = offer;
8404 }
8405
8406 @Override
8407 public void binderDied() {
8408 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8409 }
8410 }
8411
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008412 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8413 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8414 if (npi.providerId == providerId) return true;
8415 }
8416 return false;
8417 }
8418
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008419 /**
8420 * Register or update a network offer.
8421 * @param newOffer The new offer. If the callback member is the same as an existing
8422 * offer, it is an update of that offer.
8423 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008424 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008425 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8426 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008427 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008428 // This may actually happen if a provider updates its score or registers and then
8429 // immediately unregisters. The offer would still be in the handler queue, but the
8430 // provider would have been removed.
8431 if (DBG) log("Received offer from an unregistered provider");
8432 return;
8433 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008434 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8435 if (null != existingOffer) {
8436 handleUnregisterNetworkOffer(existingOffer);
8437 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008438 if (DBG) {
8439 // handleUnregisterNetworkOffer has already logged the old offer
8440 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8441 }
8442 } else {
8443 if (DBG) {
8444 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8445 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008446 }
8447 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8448 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008449 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008450 } catch (RemoteException e) {
8451 noi.binderDied();
8452 return;
8453 }
8454 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008455 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008456 }
8457
8458 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8459 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008460 if (DBG) {
8461 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8462 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008463
8464 // If the provider removes the offer and dies immediately afterwards this
8465 // function may be called twice in a row, but the array will no longer contain
8466 // the offer.
8467 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008468 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008469 }
8470
8471 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8472 @NonNull final INetworkOfferCallback callback) {
8473 ensureRunningOnConnectivityServiceThread();
8474 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008475 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008476 }
8477 return null;
8478 }
8479
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008480 /**
8481 * Called when receiving LinkProperties directly from a NetworkAgent.
8482 * Stores into |nai| any data coming from the agent that might also be written to the network's
8483 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8484 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008485 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008486 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008487 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8488 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008489 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008490 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008491 }
8492
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008493 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008494 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008495 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008496
Lorenzo Colittid523d142020-04-01 20:16:30 +09008497 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8498 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8499 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008500 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008501
Suprabh Shukla1e312032023-01-24 03:36:37 -08008502 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008503
8504 // update filtering rules, need to happen after the interface update so netd knows about the
8505 // new interface (the interface name -> index map becomes initialized)
8506 updateVpnFiltering(newLp, oldLp, networkAgent);
8507
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008508 updateMtu(newLp, oldLp);
8509 // TODO - figure out what to do for clat
8510// for (LinkProperties lp : newLp.getStackedLinks()) {
8511// updateMtu(lp, null);
8512// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008513 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008514 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008515 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8516 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008517
Erik Klineb9888902016-04-05 13:30:49 +09008518 updateRoutes(newLp, oldLp, netId);
8519 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008520 // Make sure LinkProperties represents the latest private DNS status.
8521 // This does not need to be done before updateDnses because the
8522 // LinkProperties are not the source of the private DNS configuration.
8523 // updateDnses will fetch the private DNS configuration from DnsManager.
8524 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008525
Chalard Jean5b409c72021-02-04 13:12:59 +09008526 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008527 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008528 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008529 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008530 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008531
8532 updateWakeOnLan(newLp);
8533
Hai Shalome58bdc62021-01-11 18:45:34 -08008534 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8535 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8536 // does, it needs to be merged here.
8537 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8538 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008539
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008540 // TODO - move this check to cover the whole function
8541 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008542 synchronized (networkAgent) {
8543 networkAgent.linkProperties = newLp;
8544 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008545 // Start or stop DNS64 detection and 464xlat according to network state.
8546 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008547 // Notify NSS when relevant events happened. Currently, NSS only cares about
8548 // interface changed to update clat interfaces accounting.
8549 final boolean interfacesChanged = oldLp == null
8550 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8551 if (interfacesChanged) {
8552 notifyIfacesChangedForNetworkStats();
8553 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008554 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8555 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008556 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008557 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008558
8559 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008560 }
8561
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008562 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8563 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8564 }
8565
Hai Shalome58bdc62021-01-11 18:45:34 -08008566 /**
8567 * @param naData captive portal data from NetworkAgent
8568 * @param apiData captive portal data from capport API
8569 */
8570 @Nullable
8571 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8572 CaptivePortalData apiData) {
8573 if (naData == null || apiData == null) {
8574 return naData == null ? apiData : naData;
8575 }
8576 final CaptivePortalData.Builder captivePortalBuilder =
8577 new CaptivePortalData.Builder(naData);
8578
8579 if (apiData.isCaptive()) {
8580 captivePortalBuilder.setCaptive(true);
8581 }
8582 if (apiData.isSessionExtendable()) {
8583 captivePortalBuilder.setSessionExtendable(true);
8584 }
8585 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8586 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8587 // otherwise data would be inconsistent. Prefer the capport API info if present,
8588 // as it can generally be refreshed more often.
8589 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8590 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8591 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8592 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8593 // No source has time / bytes remaining information: surface the newest refresh time
8594 // for other fields
8595 captivePortalBuilder.setRefreshTime(
8596 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8597 }
8598
Hai Shalom7c6ab402021-02-04 19:34:06 -08008599 // Prioritize the user portal URL from the network agent if the source is authenticated.
8600 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8601 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8602 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8603 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008604 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008605 // Prioritize the venue information URL from the network agent if the source is
8606 // authenticated.
8607 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8608 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8609 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8610 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008611 }
8612 return captivePortalBuilder.build();
8613 }
8614
Suprabh Shukla53e16392023-04-26 18:47:36 -07008615 @VisibleForTesting
8616 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008617 // This needs to be kept in sync and backwards compatible with the decoding logic in
8618 // NetdEventListenerService, which is non-mainline code.
8619 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8620 }
8621
Suprabh Shukla75642282023-04-25 23:15:43 -07008622 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8623 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8624 return true;
8625 }
8626 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8627 return true;
8628 }
8629 return false;
8630 }
8631
Suprabh Shukla1e312032023-01-24 03:36:37 -08008632 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008633 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008634 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008635 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008636 return;
8637 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008638
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008639 // Mask/mark of zero will not detect anything interesting.
8640 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008641 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008642 return;
8643 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008644
Suprabh Shukla1e312032023-01-24 03:36:37 -08008645 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008646 try {
8647 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008648 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008649 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008650 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008651 }
8652 } catch (Exception e) {
8653 loge("Exception modifying wakeup packet monitoring: " + e);
8654 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008655 }
8656
Junyu Lai970963e2022-10-25 15:46:47 +08008657 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008658 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008659 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008660 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008661 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008662 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008663 for (final String iface : interfaceDiff.added) {
8664 try {
8665 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008666 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008667 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008668 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008669 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008670 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008671 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008672 }
Paul Jensenbff73492014-04-28 10:33:11 -04008673 }
8674 }
Chalard Jean9589e722019-11-19 19:03:53 +09008675 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008676 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008677 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008678 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008679 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008680 } catch (Exception e) {
8681 loge("Exception removing interface: " + e);
8682 }
8683 }
8684 }
8685
Paul Jensene0fd4a82014-08-06 15:51:33 -04008686 /**
8687 * Have netd update routes from oldLp to newLp.
8688 * @return true if routes changed between oldLp and newLp
8689 */
Junyu Lai970963e2022-10-25 15:46:47 +08008690 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8691 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008692 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008693 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8694 new CompareOrUpdateResult<>(
8695 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008696 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008697 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008698
8699 // add routes before removing old in case it helps with continuous connectivity
8700
Chalard Jean9dd11612018-06-04 16:52:49 +09008701 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008702 for (RouteInfo route : routeDiff.added) {
8703 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008704 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008705 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008706 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008707 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008708 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008709 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008710 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008711 }
8712 }
8713 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008714 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008715 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008716 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008717 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008718 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008719 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008720 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008721 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008722 }
8723 }
8724
8725 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008726 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008727 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008728 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008729 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008730 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008731 }
8732 }
Tyler Weare4314862019-12-05 14:55:30 -08008733
8734 for (RouteInfo route : routeDiff.updated) {
8735 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8736 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008737 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008738 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008739 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008740 }
8741 }
8742 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8743 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008744 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008745
Junyu Lai970963e2022-10-25 15:46:47 +08008746 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8747 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008748 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8749 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008750 }
Erik Klineb9888902016-04-05 13:30:49 +09008751
Erik Kline31b4a9e2018-01-11 21:07:29 +09008752 if (DBG) {
8753 final Collection<InetAddress> dnses = newLp.getDnsServers();
8754 log("Setting DNS servers for network " + netId + " to " + dnses);
8755 }
Erik Klineb9888902016-04-05 13:30:49 +09008756 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008757 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008758 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008759 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008760 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008761 }
Erik Kline54e35c02017-04-07 15:29:29 +09008762 }
8763
Junyu Lai970963e2022-10-25 15:46:47 +08008764 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8765 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008766 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8767 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008768 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8769 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008770
8771 if (!wasFiltering && !needsFiltering) {
8772 // Nothing to do.
8773 return;
8774 }
8775
8776 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8777 // Nothing changed.
8778 return;
8779 }
8780
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008781 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008782 if (ranges == null || ranges.isEmpty()) {
8783 return;
8784 }
8785
Qingxi Libb8da982020-01-17 17:54:27 -08008786 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008787 // TODO: this create a window of opportunity for apps to receive traffic between the time
8788 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008789 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008790 // old rules are being removed.
8791 if (wasFiltering) {
8792 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8793 }
8794 if (needsFiltering) {
8795 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8796 }
8797 }
8798
Valentin Iftime9fa35092019-09-24 13:32:13 +02008799 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008800 if (mWolSupportedInterfaces == null) {
8801 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008802 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008803 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008804 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8805 }
8806
Luke Huangb913c812018-08-24 20:33:16 +08008807 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008808 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008809 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008810 }
8811 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008812 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008813 }
Luke Huangb913c812018-08-24 20:33:16 +08008814 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008815 }
8816
Chalard Jean62edfd82019-12-02 18:39:29 +09008817 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8818 @NonNull final NetworkCapabilities newNc) {
8819 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8820 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008821 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008822 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008823 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008824 } catch (RemoteException | ServiceSpecificException e) {
8825 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008826 }
8827 }
8828 }
8829
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008830 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008831 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008832 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008833 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008834 underlyingNetworks = underlyingNetworksOrDefault(
8835 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008836 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008837 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8838 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008839 // metered if any underlying is metered, or originally declared metered by the agent.
8840 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008841 boolean roaming = false; // roaming if any underlying is roaming
8842 boolean congested = false; // congested if any underlying is congested
8843 boolean suspended = true; // suspended if all underlying are suspended
8844
8845 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008846 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008847 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008848 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008849 for (Network underlyingNetwork : underlyingNetworks) {
8850 final NetworkAgentInfo underlying =
8851 getNetworkAgentInfoForNetwork(underlyingNetwork);
8852 if (underlying == null) continue;
8853
8854 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8855 hadUnderlyingNetworks = true;
8856 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008857 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008858 }
8859
8860 // Merge capabilities of this underlying network. For bandwidth, assume the
8861 // worst case.
8862 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8863 underlyingCaps.getLinkDownstreamBandwidthKbps());
8864 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8865 underlyingCaps.getLinkUpstreamBandwidthKbps());
8866 // If this underlying network is metered, the VPN is metered (it may cost money
8867 // to send packets on this network).
8868 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8869 // If this underlying network is roaming, the VPN is roaming (the billing structure
8870 // is different than the usual, local one).
8871 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8872 // If this underlying network is congested, the VPN is congested (the current
8873 // condition of the network affects the performance of this network).
8874 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8875 // If this network is not suspended, the VPN is not suspended (the VPN
8876 // is able to transfer some data).
8877 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008878 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008879 }
8880 }
8881 if (!hadUnderlyingNetworks) {
8882 // No idea what the underlying networks are; assume reasonable defaults
8883 metered = true;
8884 roaming = false;
8885 congested = false;
8886 suspended = false;
8887 }
8888
Chalard Jean1d420b32022-10-12 16:39:37 +09008889 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008890 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8891 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8892 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8893 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8894 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8895 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008896 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008897 }
8898
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008899 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008900 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8901 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8902 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008903 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008904 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008905 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008906 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008907 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8908 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008909 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008910 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008911 if (nai.everConnected()
8912 && !nai.isVPN()
8913 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008914 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008915 // does not cause any request (that is not a listen) currently matching that agent to
8916 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008917 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008918 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008919 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008920 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008921 }
8922
Paul Jensen53f08952015-06-16 14:27:36 -04008923 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008924 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008925 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008926 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008927 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008928 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008929 }
Chalard Jean254bd162022-08-25 13:04:51 +09008930 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008931 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008932 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008933 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008934 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008935 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008936 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008937 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008938 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008939 }
Chalard Jean254bd162022-08-25 13:04:51 +09008940 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008941 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8942 } else {
8943 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8944 }
lucasline117e2e2019-10-22 18:27:33 +08008945 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008946
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008947 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008948 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8949 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008950 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008951 }
8952
Lorenzo Colittibd079452021-07-02 11:47:57 +09008953 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008954 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008955 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008956 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008957 }
8958
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008959 return newNc;
8960 }
8961
Lorenzo Colitti44840702021-01-11 22:27:57 +09008962 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8963 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8964 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8965 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8966 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8967 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8968 if (prevSuspended != suspended) {
8969 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8970 // onResumed have been removed.
8971 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8972 : ConnectivityManager.CALLBACK_RESUMED);
8973 }
8974 if (prevSuspended != suspended || prevRoaming != roaming) {
8975 // updateNetworkInfo will mix in the suspended info from the capabilities and
8976 // take appropriate action for the network having possibly changed state.
8977 updateNetworkInfo(nai, nai.networkInfo);
8978 }
8979 }
8980
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008981 /**
8982 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8983 *
8984 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8985 * capabilities we manage and store in {@code nai}, such as validated status and captive
8986 * portal status)
8987 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8988 * potentially triggers rematches.
8989 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8990 * change.)
8991 *
8992 * @param oldScore score of the network before any of the changes that prompted us
8993 * to call this function.
8994 * @param nai the network having its capabilities updated.
8995 * @param nc the new network capabilities.
8996 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008997 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008998 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008999 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009000 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09009001 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
9002 if (null != differences) {
9003 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
9004 }
Chalard Jean62edfd82019-12-02 18:39:29 +09009005 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09009006 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009007
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009008 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09009009 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09009010 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009011
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009012 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009013 // If the requestable capabilities haven't changed, and the score hasn't changed, then
9014 // the change we're processing can't affect any requests, it can only affect the listens
9015 // on this network. We might have been called by rematchNetworkAndRequests when a
9016 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09009017 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009018 } else {
9019 // If the requestable capabilities have changed or the score changed, we can't have been
9020 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009021 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009022 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009023 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009024 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009025
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009026 final boolean oldMetered = prevNc.isMetered();
9027 final boolean newMetered = newNc.isMetered();
9028 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009029
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009030 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009031 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9032 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009033 }
junyulaif2c67e42018-08-07 19:50:45 +08009034
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009035 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9036 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009037
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009038 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009039 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009040 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009041 }
9042
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009043 // This network might have been underlying another network. Propagate its capabilities.
9044 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009045
Ken Chen5a35cf92023-10-07 07:54:22 +08009046 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009047 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009048 }
lucaslin53e8a262021-06-08 01:43:59 +08009049
9050 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009051 }
9052
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009053 /** Convenience method to update the capabilities for a given network. */
9054 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009055 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009056 }
9057
Chalard Jean1e4c2182023-10-06 18:45:53 +09009058 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009059 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009060 @Nullable final LocalNetworkConfig oldConfig,
9061 @NonNull final LocalNetworkConfig newConfig) {
9062 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009063 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9064 return;
9065 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009066
Chalard Jean4fe23392023-10-17 23:02:27 +09009067 if (VDBG) {
9068 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9069 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009070 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
9071 // TODO : apply the diff for multicast routing.
9072 configBuilder.setUpstreamMulticastRoutingConfig(
9073 newConfig.getUpstreamMulticastRoutingConfig());
9074 configBuilder.setDownstreamMulticastRoutingConfig(
9075 newConfig.getDownstreamMulticastRoutingConfig());
9076
9077 final NetworkRequest oldRequest =
9078 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9079 final NetworkCapabilities oldCaps =
9080 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9081 final NetworkRequestInfo oldNri =
9082 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9083 final NetworkAgentInfo oldSatisfier =
9084 null == oldNri ? null : oldNri.getSatisfier();
9085 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9086 final NetworkCapabilities newCaps =
9087 (null == newRequest) ? null : newRequest.networkCapabilities;
9088 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9089 if (null != oldRequest && requestUpdated) {
9090 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9091 if (null == newRequest && null != oldSatisfier) {
9092 // If there is an old satisfier, but no new request, then remove the old upstream.
9093 removeLocalNetworkUpstream(nai, oldSatisfier);
9094 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009095 // When there is a new request, the rematch sees the new request and sends the
9096 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9097 // But here there is no new request, so the rematch won't see anything. Send
9098 // callbacks to apps now to tell them about the loss of upstream.
9099 notifyNetworkCallbacks(nai,
9100 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009101 return;
9102 }
9103 }
9104 if (null != newRequest && requestUpdated) {
9105 // File the new request if :
9106 // - it has changed (requestUpdated), or
9107 // - it's the first time this local info (null == oldConfig)
9108 // is updated and the request has not been filed yet.
9109 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9110 // upstream (the best) but never request it to be brought up.
9111 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9112 nextNetworkRequestId(), LISTEN_FOR_BEST);
9113 configBuilder.setUpstreamSelector(nr);
9114 final NetworkRequestInfo nri = new NetworkRequestInfo(
9115 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9116 0 /* callbackFlags */, null /* attributionTag */);
9117 if (null != oldSatisfier) {
9118 // Set the old satisfier in the new NRI so that the rematch will see any changes
9119 nri.setSatisfier(oldSatisfier, nr);
9120 }
9121 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009122 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9123 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9124 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009125 handleRegisterNetworkRequest(nri);
9126 } else {
9127 configBuilder.setUpstreamSelector(oldRequest);
9128 nai.localNetworkConfig = configBuilder.build();
9129 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009130 }
9131
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009132 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009133 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009134 *
9135 * Ingress interface filtering enforces that all apps under the given network can only receive
9136 * packets from the network's interface (and loopback). This is important for VPNs because
9137 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9138 * non-VPN interfaces.
9139 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009140 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009141 * 1. the network is an app VPN (not legacy VPN)
9142 * 2. the VPN does not allow bypass
9143 * 3. the VPN is fully-routed
9144 * 4. the VPN interface is non-null
9145 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009146 * @see INetd#firewallAddUidInterfaceRules
9147 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009148 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009149 @Nullable
9150 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009151 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009152 if (nc == null || lp == null) return null;
9153 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009154 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009155 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009156 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009157 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009158 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009159 && !lp.hasExcludeRoute()) {
9160 return lp.getInterfaceName();
9161 }
9162 return null;
9163 }
9164
9165 /**
9166 * Returns whether we need to set interface filtering rule or not
9167 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009168 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009169 String isolationIface) {
9170 // Allow rules are always needed if VPN isolation is enabled.
9171 if (isolationIface != null) return true;
9172
9173 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9174 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9175 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009176 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009177 }
9178
Chiachang Wang28afaff2020-12-10 22:24:47 +08009179 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9180 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9181 int index = 0;
9182 for (UidRange range : ranges) {
9183 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9184 index++;
9185 }
9186 return stableRanges;
9187 }
9188
Chalard Jeane6c95272022-01-25 21:04:21 +09009189 private static UidRangeParcel[] intsToUidRangeStableParcels(
9190 final @NonNull ArraySet<Integer> uids) {
9191 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9192 int index = 0;
9193 for (int uid : uids) {
9194 stableRanges[index] = new UidRangeParcel(uid, uid);
9195 index++;
9196 }
9197 return stableRanges;
9198 }
9199
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009200 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9201 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9202 for (int i = 0; i < ranges.length; i++) {
9203 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9204 }
9205 return stableRanges;
9206 }
9207
Motomu Utsumi93a22182023-03-16 17:04:21 +09009208 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009209 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009210 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9211 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009212 if (mDeps.isAtLeastU()) {
9213 final Set<Integer> exemptUidSet = new ArraySet<>();
9214 for (final int uid: exemptUids) {
9215 exemptUidSet.add(uid);
9216 }
9217 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9218 } else {
9219 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9220 }
Ken Chen5e65a852020-12-24 12:59:10 +08009221 } catch (Exception e) {
9222 loge("Exception in socket destroy: ", e);
9223 }
9224 }
9225 }
9226
paulhuaa0743d2021-05-26 21:56:03 +08009227 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009228 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009229 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9230 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9231 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009232 exemptUids[0] = VPN_UID;
9233 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009234 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9235
Motomu Utsumi6345e462023-03-13 13:24:50 +09009236 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009237 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009238 try {
9239 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009240 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009241 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009242 } else {
paulhu0e79d952021-06-09 16:11:35 +08009243 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009244 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009245 }
9246 } catch (Exception e) {
9247 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9248 " on netId " + nai.network.netId + ". " + e);
9249 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009250 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009251 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009252 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009253
lucaslin53e8a262021-06-08 01:43:59 +08009254 private boolean isProxySetOnAnyDefaultNetwork() {
9255 ensureRunningOnConnectivityServiceThread();
9256 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9257 final NetworkAgentInfo nai = nri.getSatisfier();
9258 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9259 return true;
9260 }
9261 }
9262 return false;
9263 }
9264
9265 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9266 NetworkCapabilities newNc) {
9267 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9268 // the proxy might be changed since the default network satisfied by the apps might also
9269 // changed.
9270 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9271 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009272 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9273 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009274 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009275 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9276 mProxyTracker.sendProxyBroadcast();
9277 }
9278 }
9279
Chalard Jeane6c95272022-01-25 21:04:21 +09009280 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9281 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009282 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9283 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009284 if (null == prevRanges) prevRanges = new ArraySet<>();
9285 if (null == newRanges) newRanges = new ArraySet<>();
9286 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9287
9288 prevRanges.removeAll(newRanges);
9289 newRanges.removeAll(prevRangesCopy);
9290
9291 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009292 // When updating the VPN uid routing rules, add the new range first then remove the old
9293 // range. If old range were removed first, there would be a window between the old
9294 // range being removed and the new range being added, during which UIDs contained
9295 // in both ranges are not subject to any VPN routing rules. Adding new range before
9296 // removing old range works because, unlike the filtering rules below, it's possible to
9297 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009298 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9299 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9300 // [1-5] & [1-2],[4-5] == [3]
9301 // Then we can do:
9302 // maybeCloseSockets([3])
9303 // mNetd.networkAddUidRanges([1-2],[4-5])
9304 // mNetd.networkRemoveUidRanges([1-5])
9305 // maybeCloseSockets([3])
9306 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9307 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009308 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009309 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009310 }
9311 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009312 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009313 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009314 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9315 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009316 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9317 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009318 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009319 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009320 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9321 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9322 // were added first and then newRanges got removed later, there would be only one uid
9323 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9324 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9325 // Note that this is in contrast with the (more robust) update of VPN routing rules
9326 // above, where the addition of new ranges happens before the removal of old ranges.
9327 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9328 // to be removed will never overlap with the new range to be added.
9329 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009330 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9331 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009332 }
9333 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009334 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009335 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009336 } catch (Exception e) {
9337 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009338 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009339 }
9340 }
9341
Chalard Jeande665262022-02-25 16:12:12 +09009342 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009343 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9344 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009345 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9346 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009347 if (prevEmpty && newEmpty) return;
9348
9349 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009350 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009351 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009352 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009353
9354 if (prevUids.equals(newUids)) return;
9355
9356 // This implementation is very simple and vastly faster for sets of Integers than
9357 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9358 // a key computed from the value and has storage for that.
9359 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9360 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9361 toRemove.removeAll(newUids);
9362 toAdd.removeAll(prevUids);
9363
9364 try {
9365 if (!toAdd.isEmpty()) {
9366 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9367 nai.network.netId,
9368 intsToUidRangeStableParcels(toAdd),
9369 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9370 }
9371 if (!toRemove.isEmpty()) {
9372 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9373 nai.network.netId,
9374 intsToUidRangeStableParcels(toRemove),
9375 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9376 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009377 } catch (ServiceSpecificException e) {
9378 // Has the interface disappeared since the network was built ?
9379 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009380 } catch (RemoteException e) {
9381 // Netd died. This usually causes a runtime restart anyway.
9382 }
9383 }
9384
Junyu Lai2ed7d412022-10-07 16:52:21 +08009385 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9386 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009387 ensureRunningOnConnectivityServiceThread();
9388
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009389 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009390 // Ignore updates for disconnected networks
9391 return;
9392 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009393 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009394 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009395 + "; created=" + nai.getCreatedTime()
9396 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009397 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009398 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9399 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009400 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009401 }
9402
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009403 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9404 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009405 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009406 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009407 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009408 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9409 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9410 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009411 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9412 // need to be sent as a separate extra.
9413 final NetworkRequest req = nri.isMultilayerRequest()
9414 ? nri.getActiveRequest()
9415 // Non-multilayer listen requests do not have an active request
9416 : nri.mRequests.get(0);
9417 if (req == null) {
9418 Log.wtf(TAG, "No request in NRI " + nri);
9419 }
9420 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009421 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009422 sendIntent(nri.mPendingIntent, intent);
9423 }
9424 // else not handled
9425 }
9426
Michael Groover73f69482023-01-27 11:01:25 -06009427 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9428 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009429 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9430 mPendingIntentWakeLock.acquire();
9431 try {
9432 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009433 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009434 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009435 // Explicitly disallow the receiver from starting activities, to prevent apps from
9436 // utilizing the PendingIntent as a backdoor to do this.
9437 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9438 }
9439 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9440 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009441 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009442 } catch (PendingIntent.CanceledException e) {
9443 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9444 mPendingIntentWakeLock.release();
9445 releasePendingNetworkRequest(pendingIntent);
9446 }
9447 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9448 }
9449
9450 @Override
9451 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9452 String resultData, Bundle resultExtras) {
9453 if (DBG) log("Finished sending " + pendingIntent);
9454 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009455 // Release with a delay so the receiving client has an opportunity to put in its
9456 // own request.
9457 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009458 }
9459
Chalard Jean22350c92023-10-07 19:21:45 +09009460 @Nullable
9461 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9462 if (!nai.isLocalNetwork()) return null;
9463 final Network upstream;
9464 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9465 if (null == selector) {
9466 upstream = null;
9467 } else {
9468 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9469 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9470 upstream = (null == satisfier) ? null : satisfier.network;
9471 }
9472 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9473 }
9474
Chalard Jean46bfbf02022-02-02 00:56:25 +09009475 // networkAgent is only allowed to be null if notificationType is
9476 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9477 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009478 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009479 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009480 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009481 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009482 // Default request has no msgr. Also prevents callbacks from being invoked for
9483 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9484 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9485 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009486 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009487 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009488 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009489 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009490 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009491 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009492 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009493 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9494 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009495 }
Roshan Pius951c0032020-12-22 15:10:42 -08009496 final boolean includeLocationSensitiveInfo =
9497 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009498 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009499 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009500 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009501 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009502 networkCapabilitiesRestrictedForCallerPermissions(
9503 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9504 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009505 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009506 nri.mCallingAttributionTag);
9507 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009508 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9509 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009510 // The local network info is often null, so can't use the static putParcelable
9511 // method here.
9512 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9513 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009514 // For this notification, arg1 contains the blocked status.
9515 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009516 break;
9517 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009518 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009519 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009520 break;
9521 }
9522 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009523 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009524 final NetworkCapabilities netCap =
9525 networkCapabilitiesRestrictedForCallerPermissions(
9526 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9527 putParcelable(
9528 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009529 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009530 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009531 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009532 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009533 break;
9534 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009535 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009536 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9537 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009538 break;
9539 }
junyulaif2c67e42018-08-07 19:50:45 +08009540 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009541 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009542 msg.arg1 = arg1;
9543 break;
9544 }
Chalard Jean22350c92023-10-07 19:21:45 +09009545 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9546 if (!networkAgent.isLocalNetwork()) {
9547 Log.wtf(TAG, "Callback for local info for a non-local network");
9548 return;
9549 }
9550 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9551 break;
9552 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009553 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009554 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009555 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009556 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009557 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009558 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009559 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009560 }
James Mattis45d81842021-01-10 14:24:24 -08009561 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009562 } catch (RemoteException e) {
9563 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009564 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009565 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009566 }
9567
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009568 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9569 bundle.putParcelable(t.getClass().getSimpleName(), t);
9570 }
9571
Chalard Jean0702f982021-09-16 21:50:07 +09009572 /**
9573 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9574 *
9575 * When a request should be assigned to a new network, it is normally lingered to give
9576 * time for apps to gracefully migrate their connections. When both networks are on the same
9577 * radio, but that radio can't do time-sharing efficiently, this may end up being
9578 * counter-productive because any traffic on the old network may drastically reduce the
9579 * performance of the new network.
9580 * The stack supports a configuration to let modem vendors state that their radio can't
9581 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9582 * from one cell network to another can't be done gracefully.
9583 *
9584 * @param oldNai the old network serving the request
9585 * @param newNai the new network serving the request
9586 * @return whether the switch can be graceful
9587 */
9588 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9589 @NonNull final NetworkAgentInfo newSatisfier) {
9590 if (mCellularRadioTimesharingCapable) return true;
9591 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9592 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9593 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9594 }
9595
Paul Jensenaf94b982014-09-30 15:37:41 -04009596 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009597 if (nai.numRequestNetworkRequests() != 0) {
9598 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9599 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009600 // Ignore listening and track default requests.
9601 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009602 loge("Dead network still had at least " + nr);
9603 break;
9604 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009605 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009606 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009607 }
9608
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009609 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9610 if (oldNetwork == null) {
9611 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9612 return;
9613 }
Chalard Jean49707572019-12-10 21:07:02 +09009614 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009615
9616 // If we get here it means that the last linger timeout for this network expired. So there
9617 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009618 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009619
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009620 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009621 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009622 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009623 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009624 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009625 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009626 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009627 }
9628
James Mattise3ef1912020-12-20 11:09:58 -08009629 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9630 boolean isDefaultChanged = false;
9631 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9632 final NetworkReassignment.RequestReassignment reassignment =
9633 changes.getReassignment(defaultRequestInfo);
9634 if (null == reassignment) {
9635 continue;
9636 }
9637 // reassignment only contains those instances where the satisfying network changed.
9638 isDefaultChanged = true;
9639 // Notify system services of the new default.
9640 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9641 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009642
James Mattise3ef1912020-12-20 11:09:58 -08009643 if (isDefaultChanged) {
9644 // Hold a wakelock for a short time to help apps in migrating to a new default.
9645 scheduleReleaseNetworkTransitionWakelock();
9646 }
9647 }
9648
Aaron Huang9fe47be2021-06-08 13:11:45 +08009649 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9650 if (null == oldDefaultNetwork) return;
9651 // The network stopped being the default. If it was using a PAC proxy, then the
9652 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9653 // to the local proxy server, which would forward them over the newly default network.
9654 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9655 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9656 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9657 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9658 }
9659
James Mattise3ef1912020-12-20 11:09:58 -08009660 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9661 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9662 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9663 if (DBG) {
9664 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9665 }
Chalard Jean8e382112019-12-03 20:45:30 +09009666
James Mattisd31bdfa2020-12-23 16:37:26 -08009667 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9668 if (newDefaultNetwork != null) {
9669 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009670 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009671
James Mattisd31bdfa2020-12-23 16:37:26 -08009672 // Set an app level managed default and return since further processing only applies to the
9673 // default network.
9674 if (mDefaultRequest != nri) {
9675 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9676 return;
9677 }
9678
9679 makeDefaultNetwork(newDefaultNetwork);
9680
James Mattise3ef1912020-12-20 11:09:58 -08009681 if (oldDefaultNetwork != null) {
9682 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9683 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09009684 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009685 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009686 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009687 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009688 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009689 updateTcpBufferSizes(null != newDefaultNetwork
9690 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009691 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009692 }
9693
James Mattisd31bdfa2020-12-23 16:37:26 -08009694 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9695 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9696 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9697 try {
9698 if (VDBG) {
9699 log("Setting default network for " + nri
9700 + " using UIDs " + nri.getUids()
9701 + " with old network " + (oldDefaultNetwork != null
9702 ? oldDefaultNetwork.network().getNetId() : "null")
9703 + " and new network " + (newDefaultNetwork != null
9704 ? newDefaultNetwork.network().getNetId() : "null"));
9705 }
9706 if (nri.getUids().isEmpty()) {
9707 throw new IllegalStateException("makeDefaultForApps called without specifying"
9708 + " any applications to set as the default." + nri);
9709 }
9710 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009711 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009712 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009713 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009714 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009715 }
9716 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009717 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009718 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009719 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009720 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009721 }
9722 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009723 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009724 }
9725 }
9726
Junyu Lai35665cc2022-12-19 17:37:48 +08009727 /**
9728 * Collect restricted uid ranges for the given network and UserHandle, these uids
9729 * are not restricted for matched enterprise networks but being restricted for non-matched
9730 * enterprise networks and non-enterprise networks.
9731 */
9732 @NonNull
9733 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9734 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9735 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9736 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9737 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9738
9739 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9740 // The NC is built from a `ProfileNetworkPreference` which has only one
9741 // enterprise ID, so it's guaranteed to have exactly one.
9742 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9743 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9744 continue;
9745 }
9746 }
9747
9748 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9749 pref.capabilities.getUidRanges())) {
9750 throw new IllegalArgumentException(
9751 "Overlapping uid range in preference: " + pref);
9752 }
9753 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9754 }
9755 return restrictedUidRanges;
9756 }
9757
9758 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009759 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009760 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009761
Junyu Lai35665cc2022-12-19 17:37:48 +08009762 ensureRunningOnConnectivityServiceThread();
9763 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9764 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9765 .getUserHandles(true /* excludeDying */);
9766 if (users.isEmpty()) {
9767 throw new IllegalStateException("No user is available");
9768 }
9769
9770 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9771 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9772 for (final UserHandle user : users) {
9773 final ArraySet<UidRange> restrictedUidRanges =
9774 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9775 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9776 UidRange.createForUser(user), restrictedUidRanges));
9777 }
9778
9779 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9780 configs.add(new NativeUidRangeConfig(
9781 nai.network.netId, rangesParcel, 0 /* subPriority */));
9782 }
9783
9784 // The netd API replaces the previous configs with the current configs.
9785 // Thus, for network disconnection or preference removal, no need to
9786 // unset previous config. Instead, collecting all currently needed
9787 // configs and issue to netd.
9788 try {
9789 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9790 } catch (ServiceSpecificException e) {
9791 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009792 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009793 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009794 // Netd died. This will cause a runtime restart anyway.
9795 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009796 }
9797 }
9798
James Mattisd31bdfa2020-12-23 16:37:26 -08009799 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9800 try {
9801 if (null != newDefaultNetwork) {
9802 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9803 } else {
9804 mNetd.networkClearDefault();
9805 }
9806 } catch (RemoteException | ServiceSpecificException e) {
9807 loge("Exception setting default network :" + e);
9808 }
9809 }
9810
Chalard Jean05cbe972019-12-09 11:50:38 +09009811 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009812 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009813 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009814 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009815 processNewlySatisfiedListenRequests(nai);
9816 }
9817
9818 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009819 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9820 if (nri.isMultilayerRequest()) {
9821 continue;
9822 }
9823 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009824 if (!nr.isListen()) continue;
9825 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009826 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009827 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9828 }
9829 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009830 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009831
Chalard Jeancd397a22019-11-22 22:33:33 +09009832 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009833 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9834 if (nri.isMultilayerRequest()) {
9835 continue;
9836 }
9837 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009838 if (!nr.isListen()) continue;
9839 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9840 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009841 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009842 }
9843 }
9844 }
9845
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009846 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009847 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009848 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009849 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009850 @Nullable public final NetworkRequest mOldNetworkRequest;
9851 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009852 @Nullable public final NetworkAgentInfo mOldNetwork;
9853 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009854 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009855 @Nullable final NetworkRequest oldNetworkRequest,
9856 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009857 @Nullable final NetworkAgentInfo oldNetwork,
9858 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009859 mNetworkRequestInfo = networkRequestInfo;
9860 mOldNetworkRequest = oldNetworkRequest;
9861 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009862 mOldNetwork = oldNetwork;
9863 mNewNetwork = newNetwork;
9864 }
Chalard Jean49707572019-12-10 21:07:02 +09009865
9866 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009867 final NetworkRequest requestToShow = null != mNewNetworkRequest
9868 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9869 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009870 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9871 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009872 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009873 }
9874
Chalard Jean46a62372019-12-10 21:25:24 +09009875 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009876
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009877 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009878 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009879 }
9880
9881 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009882 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009883 // The code is never supposed to add two reassignments of the same request. Make
9884 // sure this stays true, but without imposing this expensive check on all
9885 // reassignments on all user devices.
9886 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009887 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009888 throw new IllegalStateException("Trying to reassign ["
9889 + reassignment + "] but already have ["
9890 + existing + "]");
9891 }
9892 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009893 }
Chalard Jean46a62372019-12-10 21:25:24 +09009894 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009895 }
9896
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009897 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009898 // the passed request.
9899 @Nullable
9900 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009901 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009902 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009903 }
9904 return null;
9905 }
Chalard Jean49707572019-12-10 21:07:02 +09009906
9907 public String toString() {
9908 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9909 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009910 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009911 for (final RequestReassignment rr : getRequestReassignments()) {
9912 sj.add(rr.toString());
9913 }
9914 return sj.toString();
9915 }
9916
9917 public String debugString() {
9918 final StringBuilder sb = new StringBuilder();
9919 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009920 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009921 for (final RequestReassignment rr : getRequestReassignments()) {
9922 sb.append("\n ").append(rr);
9923 }
9924 return sb.append("\n").toString();
9925 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009926 }
9927
Chalard Jean24344d72019-12-04 13:32:31 +09009928 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009929 @Nullable final NetworkRequest previousRequest,
9930 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009931 @Nullable final NetworkAgentInfo previousSatisfier,
9932 @Nullable final NetworkAgentInfo newSatisfier,
9933 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009934 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009935 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009936 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009937 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009938 log(" accepting network in place of " + previousSatisfier.toShortString()
9939 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009940 }
James Mattisa076c532020-12-02 14:12:41 -08009941 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009942 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009943 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009944 // If this network switch can't be supported gracefully, the request is not
9945 // lingered. This allows letting go of the network sooner to reclaim some
9946 // performance on the new network, since the radio can't do both at the same
9947 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009948 //
9949 // Also don't linger the request if the old network has been destroyed.
9950 // A destroyed network does not provide actual network connectivity, so
9951 // lingering it is not useful. In particular this ensures that a destroyed
9952 // network is outscored by its replacement,
9953 // then it is torn down immediately instead of being lingered, and any apps that
9954 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009955 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9956 }
Chalard Jean24344d72019-12-04 13:32:31 +09009957 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009958 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009959 }
junyulai0ac374f2020-12-14 18:41:52 +08009960
9961 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9962 // and immediately satisfies a request then remove the timer. This will happen for
9963 // all networks except in the case of an underlying network for a VCN.
9964 if (newSatisfier.isNascent()) {
9965 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009966 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009967 }
9968
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009969 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009970 newSatisfier.unlingerRequest(newRequest.requestId);
9971 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009972 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009973 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009974 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009975 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009976 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009977 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009978 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009979 }
James Mattisa076c532020-12-02 14:12:41 -08009980 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009981 }
James Mattisa076c532020-12-02 14:12:41 -08009982 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009983 }
9984
James Mattisa076c532020-12-02 14:12:41 -08009985 /**
9986 * This function is triggered when something can affect what network should satisfy what
9987 * request, and it computes the network reassignment from the passed collection of requests to
9988 * network match to the one that the system should now have. That data is encoded in an
9989 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9990 * satisfier.
9991 *
9992 * After the reassignment is computed, it is applied to the state objects.
9993 *
9994 * @param networkRequests the nri objects to evaluate for possible network reassignment
9995 * @return NetworkReassignment listing of proposed network assignment changes
9996 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009997 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009998 private NetworkReassignment computeNetworkReassignment(
9999 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090010000 final NetworkReassignment changes = new NetworkReassignment();
10001
Chalard Jeanc81d4c32021-04-07 17:06:19 +090010002 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090010003 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010004 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +090010005 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +090010006 }
Chalard Jean857a1712019-12-10 21:08:07 +090010007
James Mattisa076c532020-12-02 14:12:41 -080010008 for (final NetworkRequestInfo nri : networkRequests) {
10009 // Non-multilayer listen requests can be ignored.
10010 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
10011 continue;
10012 }
10013 NetworkAgentInfo bestNetwork = null;
10014 NetworkRequest bestRequest = null;
10015 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090010016 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080010017 // Stop evaluating as the highest possible priority request is satisfied.
10018 if (null != bestNetwork) {
10019 bestRequest = req;
10020 break;
10021 }
10022 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010023 if (null == bestNetwork && isDefaultBlocked(nri)) {
10024 // Remove default networking if disallowed for managed default requests.
10025 bestNetwork = mNoServiceNetwork;
10026 }
10027 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010028 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010029 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010030 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010031 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010032 }
10033 return changes;
10034 }
10035
James Mattisa076c532020-12-02 14:12:41 -080010036 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10037 return new HashSet<>(mNetworkRequests.values());
10038 }
10039
Paul Jensenc88b39b2015-06-16 14:27:36 -040010040 /**
James Mattisa076c532020-12-02 14:12:41 -080010041 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010042 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010043 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010044 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010045 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10046 }
10047
10048 /**
10049 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10050 * being disconnected.
10051 */
10052 private void rematchNetworksAndRequests(
10053 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10054 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010055 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010056 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010057 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010058 final long computed = SystemClock.elapsedRealtime();
10059 applyNetworkReassignment(changes, start);
10060 final long applied = SystemClock.elapsedRealtime();
10061 issueNetworkNeeds();
10062 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010063 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010064 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10065 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010066 log(changes.debugString());
10067 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010068 // Shorter form, only one line of log
10069 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10070 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010071 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010072 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010073
Chalard Jean1e4c2182023-10-06 18:45:53 +090010074 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10075 @Nullable final NetworkAgentInfo nai2) {
10076 if (null == nai1) return null == nai2;
10077 if (null == nai2) return false;
10078 return nai1.linkProperties.getInterfaceName()
10079 .equals(nai2.linkProperties.getInterfaceName());
10080 }
10081
Chalard Jeand7f762d2019-12-10 19:01:29 +090010082 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010083 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010084 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010085
10086 // Since most of the time there are only 0 or 1 background networks, it would probably
10087 // be more efficient to just use an ArrayList here. TODO : measure performance
10088 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10089 for (final NetworkAgentInfo nai : nais) {
10090 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10091 }
10092
Chalard Jeand7f762d2019-12-10 19:01:29 +090010093 // First, update the lists of satisfied requests in the network agents. This is necessary
10094 // because some code later depends on this state to be correct, most prominently computing
10095 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010096 for (final NetworkReassignment.RequestReassignment event :
10097 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010098 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10099 event.mOldNetworkRequest, event.mNewNetworkRequest,
10100 event.mOldNetwork, event.mNewNetwork,
10101 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010102 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010103
James Mattise3ef1912020-12-20 11:09:58 -080010104 // Process default network changes if applicable.
10105 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010106
Chalard Jean68eab722023-11-16 17:00:04 +090010107 // Update forwarding rules for the upstreams of local networks. Do this before sending
10108 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10109 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10110 // onAvailable so clients know what network the change is about. Store such changes in
10111 // an array that's only allocated if necessary (because it's almost never necessary).
10112 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10113 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10114 if (!nai.isLocalNetwork()) continue;
10115 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10116 if (null == nr) continue; // No upstream for this local network
10117 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10118 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10119 if (null == change) continue; // No change in upstreams for this network
10120 final String fromIface = nai.linkProperties.getInterfaceName();
10121 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10122 || change.mOldNetwork.isDestroyed()) {
10123 // There can be a change with the same interface name if the new network is the
10124 // replacement for the old network that was unregisteredAfterReplacement.
10125 try {
10126 if (null != change.mOldNetwork) {
10127 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10128 change.mOldNetwork.linkProperties.getInterfaceName());
10129 }
10130 // If the new upstream is already destroyed, there is no point in setting up
10131 // a forward (in fact, it might forward to the interface for some new network !)
10132 // Later when the upstream disconnects CS will try to remove the forward, which
10133 // is ignored with a benign log by RoutingCoordinatorService.
10134 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10135 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10136 change.mNewNetwork.linkProperties.getInterfaceName());
10137 }
10138 } catch (final RemoteException e) {
10139 loge("Can't update forwarding rules", e);
10140 }
10141 }
10142 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10143 localInfoChangedAgents.add(nai);
10144 }
10145
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010146 // Notify requested networks are available after the default net is switched, but
10147 // before LegacyTypeTracker sends legacy broadcasts
10148 for (final NetworkReassignment.RequestReassignment event :
10149 changes.getRequestReassignments()) {
10150 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010151 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010152 } else {
James Mattisa076c532020-12-02 14:12:41 -080010153 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010154 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010155 }
10156 }
10157
junyulai0ac374f2020-12-14 18:41:52 +080010158 // Update the inactivity state before processing listen callbacks, because the background
10159 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010160 // just yet though, because they have to be sent after the listens are processed to keep
10161 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010162 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010163 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010164 // Rematching may have altered the inactivity state of some networks, so update all
10165 // inactivity timers. updateInactivityState reads the state from the network agent
10166 // and does nothing if the state has not changed : the source of truth is controlled
10167 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10168 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010169 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010170 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010171 }
10172 }
10173
Chalard Jeanb10ab412019-12-11 14:12:30 +090010174 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010175 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010176 // Process listen requests and update capabilities if the background state has
10177 // changed for this network. For consistency with previous behavior, send onLost
10178 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010179 processNewlyLostListenRequests(nai);
10180 if (oldBackground != nai.isBackgroundNetwork()) {
10181 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010182 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010183 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010184 }
10185
junyulai0ac374f2020-12-14 18:41:52 +080010186 for (final NetworkAgentInfo nai : inactiveNetworks) {
10187 // For nascent networks, if connecting with no foreground request, skip broadcasting
10188 // LOSING for backward compatibility. This is typical when mobile data connected while
10189 // wifi connected with mobile data always-on enabled.
10190 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010191 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010192 }
10193
Chalard Jean68eab722023-11-16 17:00:04 +090010194 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10195 if (null != localInfoChangedAgents) {
10196 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10197 notifyNetworkCallbacks(nai,
10198 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010199 }
10200 }
10201
James Mattise3ef1912020-12-20 11:09:58 -080010202 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010203
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010204 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010205 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010206 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010207 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010208 // This network has active linger timers and no requests, but is not
10209 // lingering. Linger it.
10210 //
10211 // One way (the only way?) this can happen if this network is unvalidated
10212 // and became unneeded due to another network improving its score to the
10213 // point where this network will no longer be able to satisfy any requests
10214 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010215 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010216 notifyNetworkLosing(nai, now);
10217 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010218 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010219 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010220 teardownUnneededNetwork(nai);
10221 }
10222 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010223 }
10224 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010225
Chalard Jean62edfd82019-12-02 18:39:29 +090010226 /**
10227 * Apply a change in background state resulting from rematching networks with requests.
10228 *
10229 * During rematch, a network may change background states by starting to satisfy or stopping
10230 * to satisfy a foreground request. Listens don't count for this. When a network changes
10231 * background states, its capabilities need to be updated and callbacks fired for the
10232 * capability change.
10233 *
10234 * @param nai The network that changed background states
10235 */
10236 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10237 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10238 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10239 updateNetworkPermissions(nai, newNc);
10240 nai.getAndSetNetworkCapabilities(newNc);
10241 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10242 }
10243
Chalard Jeanf0344532019-11-19 19:23:38 +090010244 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010245 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010246 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010247 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10248 changes.getReassignment(mDefaultRequest);
10249 final NetworkAgentInfo oldDefaultNetwork =
10250 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10251 final NetworkAgentInfo newDefaultNetwork =
10252 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010253
Chalard Jean5b409c72021-02-04 13:12:59 +090010254 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010255 // Maintain the illusion : since the legacy API only understands one network at a time,
10256 // if the default network changed, apps should see a disconnected broadcast for the
10257 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010258 if (oldDefaultNetwork != null) {
10259 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10260 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010261 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010262 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010263 // The new default network can be newly null if and only if the old default
10264 // network doesn't satisfy the default request any more because it lost a
10265 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010266 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010267 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010268 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010269 }
10270 }
10271
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010272 // Now that all the callbacks have been sent, send the legacy network broadcasts
10273 // as needed. This is necessary so that legacy requests correctly bind dns
10274 // requests to this network. The legacy users are listening for this broadcast
10275 // and will generally do a dns request so they can ensureRouteToHost and if
10276 // they do that before the callbacks happen they'll use the default network.
10277 //
10278 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10279 // callbacks, but if apps can receive the broadcast before the callback, they still might
10280 // have an inconsistent view of networking.
10281 //
10282 // This *does* introduce a race where if the user uses the new api
10283 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10284 // they may get old info. Reverse this after the old startUsing api is removed.
10285 // This is on top of the multiple intent sequencing referenced in the todo above.
10286 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010287 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010288 addNetworkToLegacyTypeTracker(nai);
10289 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010290 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010291 }
10292
Chalard Jean0354d8c2021-01-12 10:58:56 +090010293 private void issueNetworkNeeds() {
10294 ensureRunningOnConnectivityServiceThread();
10295 for (final NetworkOfferInfo noi : mNetworkOffers) {
10296 issueNetworkNeeds(noi);
10297 }
10298 }
10299
10300 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10301 ensureRunningOnConnectivityServiceThread();
10302 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10303 informOffer(nri, noi.offer, mNetworkRanker);
10304 }
10305 }
10306
10307 /**
10308 * Inform a NetworkOffer about any new situation of a request.
10309 *
10310 * This function handles updates to offers. A number of events may happen that require
10311 * updating the registrant for this offer about the situation :
10312 * • The offer itself was updated. This may lead the offer to no longer being able
10313 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10314 * or conversely being strengthened enough to beat the satisfier (and therefore
10315 * start being needed)
10316 * • The network satisfying a request changed (including cases where the request
10317 * starts or stops being satisfied). The new network may be a stronger or weaker
10318 * match than the old one, possibly affecting whether the offer is needed.
10319 * • The network satisfying a request updated their score. This may lead the offer
10320 * to no longer be able to beat it if the current satisfier got better, or
10321 * conversely start being a good choice if the current satisfier got weaker.
10322 *
10323 * @param nri The request
10324 * @param offer The offer. This may be an updated offer.
10325 */
10326 private static void informOffer(@NonNull NetworkRequestInfo nri,
10327 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10328 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10329 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010330
10331 // Multi-layer requests have a currently active request, the one being satisfied.
10332 // Since the system will try to bring up a better network than is currently satisfying
10333 // the request, NetworkProviders need to be told the offers matching the requests *above*
10334 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10335 // not needed, and the offer is needed for the active request iff the offer can beat
10336 // the satisfier.
10337 // For non-multilayer requests, the logic above gracefully degenerates to only the
10338 // last case.
10339 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10340 // providers that the offer is needed for this request, until the active request is found.
10341 // In a second phase, deal with the currently active request. In a third phase, inform
10342 // the providers that offer is unneeded for the remaining requests.
10343
10344 // First phase : inform providers of all requests above the active request.
10345 int i;
10346 for (i = 0; nri.mRequests.size() > i; ++i) {
10347 final NetworkRequest request = nri.mRequests.get(i);
10348 if (activeRequest == request) break; // Found the active request : go to phase 2
10349 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10350 // Since this request is higher-priority than the one currently satisfied, if the
10351 // offer can satisfy it, the provider should try and bring up the network for sure ;
10352 // no need to even ask the ranker – an offer that can satisfy is always better than
10353 // no network. Hence tell the provider so unless it already knew.
10354 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10355 offer.onNetworkNeeded(request);
10356 }
10357 }
10358
10359 // Second phase : deal with the active request (if any)
10360 if (null != activeRequest && activeRequest.isRequest()) {
10361 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010362 // If an offer can satisfy the request, it is considered needed if it is currently
10363 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010364 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010365 && satisfier.factorySerialNumber == offer.providerId
10366 && activeRequest.canBeSatisfiedBy(offer.caps);
10367 final boolean newNeeded = currentlyServing
10368 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010369 if (newNeeded != oldNeeded) {
10370 if (newNeeded) {
10371 offer.onNetworkNeeded(activeRequest);
10372 } else {
10373 // The offer used to be able to beat the satisfier. Now it can't.
10374 offer.onNetworkUnneeded(activeRequest);
10375 }
10376 }
10377 }
10378
10379 // Third phase : inform the providers that the offer isn't needed for any request
10380 // below the active one.
10381 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10382 final NetworkRequest request = nri.mRequests.get(i);
10383 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10384 // Since this request is lower-priority than the one currently satisfied, if the
10385 // offer can satisfy it, the provider should not try and bring up the network.
10386 // Hence tell the provider so unless it already knew.
10387 if (offer.neededFor(request)) {
10388 offer.onNetworkUnneeded(request);
10389 }
10390 }
10391 }
10392
Chalard Jean61c79252019-11-07 23:07:32 +090010393 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10394 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10395 NetworkRequest nr = nai.requestAt(i);
10396 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10397 // legacy type tracker filters out repeat adds
10398 mLegacyTypeTracker.add(nr.legacyType, nai);
10399 }
10400 }
10401
10402 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010403 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010404 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10405 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10406 if (nai.isVPN()) {
10407 mLegacyTypeTracker.add(TYPE_VPN, nai);
10408 }
10409 }
10410
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010411 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010412 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010413 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010414 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010415 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010416 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010417
Chalard Jean254bd162022-08-25 13:04:51 +090010418 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010419 // Don't repeat publish.
10420 if (newInetCondition == mDefaultInetConditionPublished) return;
10421
10422 mDefaultInetConditionPublished = newInetCondition;
10423 sendInetConditionBroadcast(nai.networkInfo);
10424 }
10425
Chalard Jeand61375d2020-01-14 22:46:36 +090010426 @NonNull
10427 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10428 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010429 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010430 final boolean suspended =
10431 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10432 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10433 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10434 // state. This is because the network could have been suspended before connecting,
10435 // or it could be disconnecting while being suspended, and in both these cases
10436 // the state should not be overridden. Note that the only detailed state that
10437 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10438 // worry about multiple different substates of CONNECTED.
10439 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10440 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010441 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10442 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10443 // network agent is created, then goes to suspended, then goes out of suspended without
10444 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010445 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010446 ? NetworkInfo.DetailedState.CONNECTED
10447 : NetworkInfo.DetailedState.CONNECTING,
10448 info.getReason(),
10449 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010450 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010451 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010452 return newInfo;
10453 }
10454
10455 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10456 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10457
Erik Kline99f301b2017-02-15 19:59:17 +090010458 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010459 NetworkInfo oldInfo = null;
10460 synchronized (networkAgent) {
10461 oldInfo = networkAgent.networkInfo;
10462 networkAgent.networkInfo = newInfo;
10463 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010464
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010465 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010466 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10467 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010468 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010469
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010470 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010471 // A network that has just connected has zero requests and is thus a foreground network.
10472 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10473
Luke Huangfdd11f82019-04-09 18:41:49 +080010474 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010475
10476 networkAgent.setCreated();
10477
10478 // If the network is created immediately on register, then apply the LinkProperties now.
10479 // Otherwise, this is done further down when the network goes into connected state.
10480 // Applying the LinkProperties means that the network is ready to carry traffic -
10481 // interfaces and routing rules have been added, DNS servers programmed, etc.
10482 // For VPNs, this must be done before the capabilities are updated, because as soon as
10483 // that happens, UIDs are routed to the network.
10484 if (shouldCreateNetworksImmediately()) {
10485 applyInitialLinkProperties(networkAgent);
10486 }
10487
10488 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10489 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010490 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010491 // Initialize the network's capabilities to their starting values according to the
10492 // underlying networks. This ensures that the capabilities are correct before
10493 // anything happens to the network.
10494 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010495 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010496 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010497 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010498 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010499 }
10500
Chalard Jean254bd162022-08-25 13:04:51 +090010501 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10502 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010503
lucaslin45e639b2019-04-03 17:09:28 +080010504 // NetworkCapabilities need to be set before sending the private DNS config to
10505 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010506 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10507
Erik Kline9a62f012018-03-21 07:18:33 -070010508 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010509 if (!shouldCreateNetworksImmediately()) {
10510 applyInitialLinkProperties(networkAgent);
10511 } else {
10512 // The network was created when the agent registered, and the LinkProperties are
10513 // already up-to-date. However, updateLinkProperties also makes some changes only
10514 // when the network connects. Apply those changes here. On T and below these are
10515 // handled by the applyInitialLinkProperties call just above.
10516 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10517 // If something depends on both LinkProperties and connected state, it should be in
10518 // this method as well.
10519 networkAgent.clatd.update();
10520 updateProxy(networkAgent.linkProperties, null);
10521 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010522
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010523 // If a rate limit has been configured and is applicable to this network (network
10524 // provides internet connectivity), apply it. The tc police filter cannot be attached
10525 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010526 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010527 // Note: in case of a system server crash, the NetworkController constructor in netd
10528 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10529 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10530 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10531 mIngressRateLimit);
10532 }
10533
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010534 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10535 // command must be sent after updating LinkProperties to maximize chances of
10536 // NetworkMonitor seeing the correct LinkProperties when starting.
10537 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010538 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010539 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010540 }
Chalard Jeand4900722022-02-06 12:25:38 +090010541 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10542 params.networkAgentConfig = networkAgent.networkAgentConfig;
10543 params.networkCapabilities = networkAgent.networkCapabilities;
10544 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10545 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010546 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10547 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10548 // call that would cause a Log.wtf to be emitted from the system_server process, and
10549 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10550 // process to check the interface version, just use an SDK check. NetworkStack will
10551 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010552 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010553 networkAgent.networkMonitor().notifyNetworkConnected(params);
10554 } else {
10555 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10556 params.networkCapabilities);
10557 }
Chalard Jean0f141332023-06-05 19:26:17 +090010558 final long evaluationDelay;
10559 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10560 // If the network is anything other than pure wifi, use the default timeout.
10561 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10562 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10563 // If the network is explicitly selected, use the default timeout because it's
10564 // shorter and the user is likely staring at the screen expecting it to validate
10565 // right away.
10566 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10567 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10568 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10569 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10570 } else {
10571 // It's wifi, automatically connected, and bad wifi is preferred : use the
10572 // longer timeout to avoid the device switching to captive portals with bad
10573 // signal or very slow response.
10574 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10575 }
10576 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010577
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010578 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10579 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10580 // capabilities, so it only needs to be done once on initial connect, not every time the
10581 // network's capabilities change. Note that we do this before rematching the network,
10582 // so we could decide to tear it down immediately afterwards. That's fine though - on
10583 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10584 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010585 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010586
junyulai0ac374f2020-12-14 18:41:52 +080010587 // Before first rematching networks, put an inactivity timer without any request, this
10588 // allows {@code updateInactivityState} to update the state accordingly and prevent
10589 // tearing down for any {@code unneeded} evaluation in this period.
10590 // Note that the timer will not be rescheduled since the expiry time is
10591 // fixed after connection regardless of the network satisfying other requests or not.
10592 // But it will be removed as soon as the network satisfies a request for the first time.
10593 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10594 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010595 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010596
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010597 if (mTrackMultiNetworkActivities) {
10598 // Start tracking activity of this network.
10599 // This must be called before rematchAllNetworksAndRequests since the network
10600 // should be tracked when the network becomes the default network.
10601 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
10602 // can be triggered later if this network becomes the default network.
10603 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
10604 }
10605
Paul Jensen05e85ee2014-09-11 11:00:39 -040010606 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010607 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010608
10609 // This has to happen after matching the requests, because callbacks are just requests.
10610 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010611 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010612 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010613 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010614 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010615 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010616 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010617 if (networkAgent.isVPN()) {
10618 // As the active or bound network changes for apps, broadcast the default proxy, as
10619 // apps may need to update their proxy data. This is called after disconnecting from
10620 // VPN to make sure we do not broadcast the old proxy data.
10621 // TODO(b/122649188): send the broadcast only to VPN users.
10622 mProxyTracker.sendProxyBroadcast();
10623 }
Chalard Jean254bd162022-08-25 13:04:51 +090010624 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10625 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010626 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010627 }
10628 }
10629
Chalard Jean28018572020-12-21 18:36:52 +090010630 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010631 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10632 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010633 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010634 }
10635
Erik Kline99f301b2017-02-15 19:59:17 +090010636 // Notify only this one new request of the current state. Transfer all the
10637 // current state by calling NetworkCapabilities and LinkProperties callbacks
10638 // so that callers can be guaranteed to have as close to atomicity in state
10639 // transfer as can be supported by this current API.
10640 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010641 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010642 if (nri.mPendingIntent != null) {
10643 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10644 // Attempt no subsequent state pushes where intents are involved.
10645 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010646 }
Erik Kline99f301b2017-02-15 19:59:17 +090010647
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010648 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010649 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010650 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10651 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10652 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010653 }
10654
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010655 // Notify the requests on this NAI that the network is now lingered.
10656 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010657 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010658 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10659 }
10660
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010661 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10662 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10663 return vpnBlocked
10664 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10665 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10666 }
10667
10668 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10669 if (blockedReasons == BLOCKED_REASON_NONE) {
10670 mUidBlockedReasons.delete(uid);
10671 } else {
10672 mUidBlockedReasons.put(uid, blockedReasons);
10673 }
10674 }
10675
junyulaif2c67e42018-08-07 19:50:45 +080010676 /**
10677 * Notify of the blocked state apps with a registered callback matching a given NAI.
10678 *
10679 * Unlike other callbacks, blocked status is different between each individual uid. So for
10680 * any given nai, all requests need to be considered according to the uid who filed it.
10681 *
10682 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010683 * @param oldMetered True if the previous network capabilities were metered.
10684 * @param newMetered True if the current network capabilities are metered.
10685 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10686 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010687 */
10688 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010689 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10690 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010691
10692 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10693 NetworkRequest nr = nai.requestAt(i);
10694 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010695
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010696 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10697 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10698 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010699 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010700 : oldVpnBlocked;
10701
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010702 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10703 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10704 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010705 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010706 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010707 }
10708 }
10709 }
10710
10711 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010712 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010713 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010714 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010715 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010716 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010717 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010718 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010719 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010720
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010721 final int oldBlockedState = getBlockedState(
10722 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10723 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10724 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010725 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010726 }
junyulaif2c67e42018-08-07 19:50:45 +080010727 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10728 NetworkRequest nr = nai.requestAt(i);
10729 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010730 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010731 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10732 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010733 }
10734 }
10735 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010736 }
10737
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010738 @VisibleForTesting
10739 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010740 // The NetworkInfo we actually send out has no bearing on the real
10741 // state of affairs. For example, if the default connection is mobile,
10742 // and a request for HIPRI has just gone away, we need to pretend that
10743 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10744 // the state to DISCONNECTED, even though the network is of type MOBILE
10745 // and is still connected.
10746 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10747 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010748 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010749 if (state != DetailedState.DISCONNECTED) {
10750 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010751 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010752 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010753 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010754 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10755 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10756 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10757 if (info.isFailover()) {
10758 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10759 nai.networkInfo.setFailover(false);
10760 }
10761 if (info.getReason() != null) {
10762 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10763 }
10764 if (info.getExtraInfo() != null) {
10765 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10766 }
10767 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010768 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010769 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010770 if (newDefaultAgent != null) {
10771 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10772 newDefaultAgent.networkInfo);
10773 } else {
10774 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10775 }
10776 }
10777 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10778 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010779 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010780 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010781 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010782 }
10783 }
10784 }
10785
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010786 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010787 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010788 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010789 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010790 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010791 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10792 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010793 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10794 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010795 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010796 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010797 } else {
10798 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10799 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010800 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010801 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010802
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010803 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10804 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10805 }
10806
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010807 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010808 * Returns the list of all interfaces that could be used by network traffic that does not
10809 * explicitly specify a network. This includes the default network, but also all VPNs that are
10810 * currently connected.
10811 *
10812 * Must be called on the handler thread.
10813 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010814 @NonNull
10815 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010816 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010817 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010818 final Set<Integer> activeNetIds = new ArraySet<>();
10819 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10820 if (nri.isBeingSatisfied()) {
10821 activeNetIds.add(nri.getSatisfier().network().netId);
10822 }
10823 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010824 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010825 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010826 defaultNetworks.add(nai.network);
10827 }
10828 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010829 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010830 }
10831
10832 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010833 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10834 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010835 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010836 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010837 ensureRunningOnConnectivityServiceThread();
10838 String activeIface = null;
10839 LinkProperties activeLinkProperties = getActiveLinkProperties();
10840 if (activeLinkProperties != null) {
10841 activeIface = activeLinkProperties.getInterfaceName();
10842 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010843
junyulai2050bed2021-01-23 09:46:34 +080010844 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010845 try {
junyulaide41fc22021-01-22 22:46:01 +080010846 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010847 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010848 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10849 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010850 } catch (Exception ignored) {
10851 }
10852 }
10853
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010854 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010855 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010856 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010857 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010858 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010859
10860 if (!TextUtils.isEmpty(settingUrl)) {
10861 return settingUrl;
10862 }
10863
10864 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010865 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010866 if (!TextUtils.isEmpty(settingUrl)) {
10867 return settingUrl;
10868 }
10869
10870 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010871 }
10872
10873 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010874 public void startNattKeepalive(Network network, int intervalSeconds,
10875 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010876 enforceKeepalivePermission();
10877 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010878 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010879 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10880 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010881 // false and set the underpinned network to null because there is no way and no
10882 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10883 // deprecated method.
10884 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010885 }
10886
10887 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010888 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010889 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010890 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010891 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010892 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010893 mKeepaliveTracker.startNattKeepalive(
10894 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010895 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10896 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010897 } finally {
10898 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10899 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010900 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10901 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010902 }
10903 }
junyulaid05a1922019-01-15 11:32:44 +080010904 }
10905
10906 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010907 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010908 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010909 try {
10910 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010911 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010912 mKeepaliveTracker.startTcpKeepalive(
10913 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10914 } finally {
10915 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10916 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010917 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10918 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010919 }
10920 }
junyulai0835a1e2019-01-08 20:04:33 +080010921 }
10922
10923 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010924 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010925 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010926 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10927 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010928 }
10929
10930 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010931 public int[] getSupportedKeepalives() {
10932 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10933 // Backwards compatibility with CTS 13
10934 android.Manifest.permission.QUERY_ALL_PACKAGES);
10935
10936 return BinderUtils.withCleanCallingIdentity(() ->
10937 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10938 }
10939
10940 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010941 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010942 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010943
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010944 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010945 final long token = Binder.clearCallingIdentity();
10946 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010947 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10948 UserHandle.getUserHandleForUid(uid))) {
10949 return;
10950 }
10951
Heemin Seogdb8489d2019-06-12 09:21:44 -070010952 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10953 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010954
10955 // Turn airplane mode off
10956 setAirplaneMode(false);
10957
10958 // restore private DNS settings to default mode (opportunistic)
10959 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10960 UserHandle.getUserHandleForUid(uid))) {
10961 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10962 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10963 }
10964
10965 Settings.Global.putString(mContext.getContentResolver(),
10966 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010967 } finally {
10968 Binder.restoreCallingIdentity(token);
10969 }
Stuart Scottd5463642015-04-02 18:00:02 -070010970 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010971
Ricky Wai7097cc92018-01-23 04:09:45 +000010972 @Override
10973 public byte[] getNetworkWatchlistConfigHash() {
10974 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10975 if (nwm == null) {
10976 loge("Unable to get NetworkWatchlistManager");
10977 return null;
10978 }
10979 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10980 return nwm.getWatchlistConfigHash();
10981 }
10982
Hugo Benichibe0c7652016-05-31 16:28:06 +090010983 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010984 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010985 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010986 }
Hugo Benichif4210292017-04-21 15:07:12 +090010987
10988 private static boolean toBool(int encodedBoolean) {
10989 return encodedBoolean != 0; // Only 0 means false.
10990 }
10991
10992 private static int encodeBool(boolean b) {
10993 return b ? 1 : 0;
10994 }
mswest4632928412018-03-12 10:34:34 -070010995
10996 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010997 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10998 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10999 @NonNull String[] args) {
11000 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
11001 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070011002 }
11003
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011004 private Boolean parseBooleanArgument(final String arg) {
11005 if ("true".equals(arg)) {
11006 return true;
11007 } else if ("false".equals(arg)) {
11008 return false;
11009 } else {
11010 return null;
11011 }
11012 }
11013
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011014 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070011015 @Override
11016 public int onCommand(String cmd) {
11017 if (cmd == null) {
11018 return handleDefaultCommands(cmd);
11019 }
11020 final PrintWriter pw = getOutPrintWriter();
11021 try {
11022 switch (cmd) {
11023 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011024 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11025 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011026 final String action = getNextArg();
11027 if ("enable".equals(action)) {
11028 setAirplaneMode(true);
11029 return 0;
11030 } else if ("disable".equals(action)) {
11031 setAirplaneMode(false);
11032 return 0;
11033 } else if (action == null) {
11034 final ContentResolver cr = mContext.getContentResolver();
11035 final int enabled = Settings.Global.getInt(cr,
11036 Settings.Global.AIRPLANE_MODE_ON);
11037 pw.println(enabled == 0 ? "disabled" : "enabled");
11038 return 0;
11039 } else {
11040 onHelp();
11041 return -1;
11042 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011043 case "set-chain3-enabled": {
11044 final Boolean enabled = parseBooleanArgument(getNextArg());
11045 if (null == enabled) {
11046 onHelp();
11047 return -1;
11048 }
11049 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11050 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11051 enabled);
11052 return 0;
11053 }
11054 case "get-chain3-enabled": {
11055 final boolean chainEnabled = getFirewallChainEnabled(
11056 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11057 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11058 return 0;
11059 }
11060 case "set-package-networking-enabled": {
11061 final Boolean enabled = parseBooleanArgument(getNextArg());
11062 final String packageName = getNextArg();
11063 if (null == enabled || null == packageName) {
11064 onHelp();
11065 return -1;
11066 }
11067 // Throws NameNotFound if the package doesn't exist.
11068 final int appId = setPackageFirewallRule(
11069 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11070 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11071 final String msg = (enabled ? "Enabled" : "Disabled")
11072 + " networking for " + packageName + ", appId " + appId;
11073 Log.i(TAG, msg);
11074 pw.println(msg);
11075 return 0;
11076 }
11077 case "get-package-networking-enabled": {
11078 final String packageName = getNextArg();
11079 final int rule = getPackageFirewallRule(
11080 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11081 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11082 pw.println(packageName + ":" + "allow");
11083 } else if (FIREWALL_RULE_DENY == rule) {
11084 pw.println(packageName + ":" + "deny");
11085 } else {
11086 throw new IllegalStateException("Unknown rule " + rule + " for package "
11087 + packageName);
11088 }
11089 return 0;
11090 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011091 case "reevaluate":
11092 // Usage : adb shell cmd connectivity reevaluate <netId>
11093 // If netId is omitted, then reevaluate the default network
11094 final String netId = getNextArg();
11095 final NetworkAgentInfo nai;
11096 if (null == netId) {
11097 // Note that the command is running on the wrong thread to call this,
11098 // so this could in principle return stale data. But it can't crash.
11099 nai = getDefaultNetwork();
11100 } else {
11101 // If netId can't be parsed, this throws NumberFormatException, which
11102 // is passed back to adb who prints it.
11103 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11104 }
11105 if (null == nai) {
11106 pw.println("Unknown network (net ID not found or no default network)");
11107 return 0;
11108 }
11109 Log.d(TAG, "Reevaluating network " + nai.network);
11110 reportNetworkConnectivity(nai.network, !nai.isValidated());
11111 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011112 case "bpf-get-cgroup-program-id": {
11113 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11114 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11115 // for more detail.
11116 // If type can't be parsed, this throws NumberFormatException, which
11117 // is passed back to adb who prints it.
11118 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011119 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011120 pw.println(ret);
11121 return 0;
11122 }
mswest4632928412018-03-12 10:34:34 -070011123 default:
11124 return handleDefaultCommands(cmd);
11125 }
11126 } catch (Exception e) {
11127 pw.println(e);
11128 }
11129 return -1;
11130 }
11131
11132 @Override
11133 public void onHelp() {
11134 PrintWriter pw = getOutPrintWriter();
11135 pw.println("Connectivity service commands:");
11136 pw.println(" help");
11137 pw.println(" Print this help text.");
11138 pw.println(" airplane-mode [enable|disable]");
11139 pw.println(" Turn airplane mode on or off.");
11140 pw.println(" airplane-mode");
11141 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011142 pw.println(" set-chain3-enabled [true|false]");
11143 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11144 pw.println(" get-chain3-enabled");
11145 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11146 pw.println(" set-package-networking-enabled [true|false] [package name]");
11147 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11148 + " no effect if the chain is disabled.");
11149 pw.println(" get-package-networking-enabled [package name]");
11150 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011151 }
11152 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011153
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011154 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011155 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11156 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11157 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011158 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011159 }
11160
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011161 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11162 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011163 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11164 final TransportInfo newInfo = nc.getTransportInfo();
11165 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11166 return;
11167 }
11168 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011169 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011170 }
11171 }
11172
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011173 /**
11174 * @param connectionInfo the connection to resolve.
11175 * @return {@code uid} if the connection is found and the app has permission to observe it
11176 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11177 * connection is not found.
11178 */
11179 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011180 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11181 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11182 }
11183
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011184 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011185 connectionInfo.local, connectionInfo.remote);
11186
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011187 if (uid == INVALID_UID) return uid; // Not found.
11188
11189 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11190 // VPN, if any, that applies to the UID that owns the connection.
11191 if (checkNetworkStackPermission()) return uid;
11192
11193 final NetworkAgentInfo vpn = getVpnForUid(uid);
11194 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011195 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011196 return INVALID_UID;
11197 }
11198
11199 return uid;
11200 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011201
Benedict Wong493e04b2018-11-09 14:45:34 -080011202 /**
11203 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11204 *
11205 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11206 */
11207 @Override
11208 public IBinder startOrGetTestNetworkService() {
11209 synchronized (mTNSLock) {
11210 TestNetworkService.enforceTestNetworkPermissions(mContext);
11211
11212 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011213 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011214 }
11215
11216 return mTNS;
11217 }
11218 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011219
Cody Kesting73708bf2019-12-18 10:57:50 -080011220 /**
11221 * Handler used for managing all Connectivity Diagnostics related functions.
11222 *
11223 * @see android.net.ConnectivityDiagnosticsManager
11224 *
11225 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11226 */
11227 @VisibleForTesting
11228 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011229 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11230
Cody Kesting73708bf2019-12-18 10:57:50 -080011231 /**
11232 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11233 * android.net.ConnectivityDiagnosticsManager}.
11234 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11235 * NetworkRequestInfo to be registered
11236 */
11237 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11238
11239 /**
11240 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11241 * android.net.ConnectivityDiagnosticsManager}.
11242 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11243 * arg1 = the uid of the caller
11244 */
11245 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11246
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011247 /**
11248 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011249 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011250 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11251 * NetworkMonitor.
11252 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011253 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011254 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011255
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011256 /**
11257 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11258 * been detected on the network.
11259 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11260 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11261 * arg2 = NetID.
11262 * data = PersistableBundle of extras passed from NetworkMonitor.
11263 */
11264 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11265
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011266 /**
11267 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11268 * the platform. This event will invoke {@link
11269 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11270 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011271 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011272 */
11273 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11274
Cody Kesting73708bf2019-12-18 10:57:50 -080011275 private ConnectivityDiagnosticsHandler(Looper looper) {
11276 super(looper);
11277 }
11278
11279 @Override
11280 public void handleMessage(Message msg) {
11281 switch (msg.what) {
11282 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11283 handleRegisterConnectivityDiagnosticsCallback(
11284 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11285 break;
11286 }
11287 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11288 handleUnregisterConnectivityDiagnosticsCallback(
11289 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11290 break;
11291 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011292 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011293 final ConnectivityReportEvent reportEvent =
11294 (ConnectivityReportEvent) msg.obj;
11295
Aaron Huang959d3642021-01-21 15:47:41 +080011296 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011297 break;
11298 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011299 case EVENT_DATA_STALL_SUSPECTED: {
11300 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011301 final Pair<Long, PersistableBundle> arg =
11302 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011303 if (nai == null) break;
11304
Aaron Huang959d3642021-01-21 15:47:41 +080011305 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011306 break;
11307 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011308 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011309 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011310 break;
11311 }
11312 default: {
11313 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11314 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011315 }
11316 }
11317 }
11318
11319 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11320 @VisibleForTesting
11321 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11322 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11323 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011324 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011325
11326 @VisibleForTesting
11327 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011328 @NonNull IConnectivityDiagnosticsCallback cb,
11329 @NonNull NetworkRequestInfo nri,
11330 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011331 mCb = cb;
11332 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011333 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011334 }
11335
11336 @Override
11337 public void binderDied() {
11338 log("ConnectivityDiagnosticsCallback IBinder died.");
11339 unregisterConnectivityDiagnosticsCallback(mCb);
11340 }
11341 }
11342
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011343 /**
11344 * Class used for sending information from {@link
11345 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11346 */
11347 private static class NetworkTestedResults {
11348 private final int mNetId;
11349 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011350 @Nullable private final String mRedirectUrl;
11351
11352 private NetworkTestedResults(
11353 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11354 mNetId = netId;
11355 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011356 mRedirectUrl = redirectUrl;
11357 }
11358 }
11359
11360 /**
11361 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11362 * ConnectivityDiagnosticsHandler}.
11363 */
11364 private static class ConnectivityReportEvent {
11365 private final long mTimestampMillis;
11366 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011367 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011368
Aaron Huang959d3642021-01-21 15:47:41 +080011369 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11370 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011371 mTimestampMillis = timestampMillis;
11372 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011373 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011374 }
11375 }
11376
Cody Kestingf1120be2020-08-03 18:01:40 -070011377 /**
11378 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11379 * ConnectivityDiagnosticsHandler}.
11380 */
11381 private static class ReportedNetworkConnectivityInfo {
11382 public final boolean hasConnectivity;
11383 public final boolean isNetworkRevalidating;
11384 public final int reporterUid;
11385 @NonNull public final NetworkAgentInfo nai;
11386
11387 private ReportedNetworkConnectivityInfo(
11388 boolean hasConnectivity,
11389 boolean isNetworkRevalidating,
11390 int reporterUid,
11391 @NonNull NetworkAgentInfo nai) {
11392 this.hasConnectivity = hasConnectivity;
11393 this.isNetworkRevalidating = isNetworkRevalidating;
11394 this.reporterUid = reporterUid;
11395 this.nai = nai;
11396 }
11397 }
11398
Cody Kesting73708bf2019-12-18 10:57:50 -080011399 private void handleRegisterConnectivityDiagnosticsCallback(
11400 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11401 ensureRunningOnConnectivityServiceThread();
11402
11403 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011404 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011405 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11406
James Mattis64b8b0f2020-11-24 17:40:49 -080011407 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11408 // confusing for these networks to change when an NRI is satisfied in another layer.
11409 if (nri.isMultilayerRequest()) {
11410 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11411 + "network requests.");
11412 }
11413
Cody Kesting73708bf2019-12-18 10:57:50 -080011414 // This means that the client registered the same callback multiple times. Do
11415 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011416 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011417 if (VDBG) log("Diagnostics callback is already registered");
11418
11419 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11420 // incremented when the NetworkRequestInfo is created as part of
11421 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011422 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011423 return;
11424 }
11425
Cody Kesting31f1ff62020-03-05 10:46:02 -080011426 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011427
11428 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011429 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011430 } catch (RemoteException e) {
11431 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011432 return;
11433 }
11434
11435 // Once registered, provide ConnectivityReports for matching Networks
11436 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11437 synchronized (mNetworkForNetId) {
11438 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11439 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011440 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11441 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011442 matchingNetworks.add(nai);
11443 }
11444 }
11445 }
11446 for (final NetworkAgentInfo nai : matchingNetworks) {
11447 final ConnectivityReport report = nai.getConnectivityReport();
11448 if (report == null) {
11449 continue;
11450 }
11451 if (!checkConnectivityDiagnosticsPermissions(
11452 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11453 continue;
11454 }
11455
11456 try {
11457 cb.onConnectivityReportAvailable(report);
11458 } catch (RemoteException e) {
11459 // Exception while sending the ConnectivityReport. Move on to the next network.
11460 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011461 }
11462 }
11463
11464 private void handleUnregisterConnectivityDiagnosticsCallback(
11465 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11466 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011467 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011468
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011469 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11470 mConnectivityDiagnosticsCallbacks.remove(iCb);
11471 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011472 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11473 return;
11474 }
11475
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011476 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011477
Cody Kesting70fa2b22020-12-02 12:16:56 -080011478 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11479 // (if the Binder died)
11480 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11481 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011482 return;
11483 }
11484
Cody Kesting46cb1672020-03-04 13:35:20 -080011485 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11486 // incremented when the NetworkRequestInfo is created as part of
11487 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011488 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011489
Cody Kesting31f1ff62020-03-05 10:46:02 -080011490 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011491 }
11492
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011493 private void handleNetworkTestedWithExtras(
11494 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11495 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011496 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011497 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011498 final ConnectivityReport report =
11499 new ConnectivityReport(
11500 reportEvent.mNai.network,
11501 reportEvent.mTimestampMillis,
11502 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011503 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011504 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011505 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011506
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011507 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011508 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011509 for (final IConnectivityDiagnosticsCallback cb : results) {
11510 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011511 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011512 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011513 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011514 }
11515 }
11516 }
11517
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011518 private void handleDataStallSuspected(
11519 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11520 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011521 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011522 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011523 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011524 new DataStallReport(
11525 nai.network,
11526 timestampMillis,
11527 detectionMethod,
11528 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011529 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011530 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011531 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011532 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011533 for (final IConnectivityDiagnosticsCallback cb : results) {
11534 try {
11535 cb.onDataStallSuspected(report);
11536 } catch (RemoteException ex) {
11537 loge("Error invoking onDataStallSuspected", ex);
11538 }
11539 }
11540 }
11541
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011542 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011543 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11544 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11545 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11546
11547 // If the Network is being re-validated as a result of this call to
11548 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11549 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011550 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011551 getMatchingPermissionedCallbacks(
11552 nai,
11553 reportedNetworkConnectivityInfo.isNetworkRevalidating
11554 ? Process.INVALID_UID
11555 : reportedNetworkConnectivityInfo.reporterUid);
11556
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011557 for (final IConnectivityDiagnosticsCallback cb : results) {
11558 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011559 cb.onNetworkConnectivityReported(
11560 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011561 } catch (RemoteException ex) {
11562 loge("Error invoking onNetworkConnectivityReported", ex);
11563 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011564
11565 // If the Network isn't re-validating, also provide the cached report. If there is no
11566 // cached report, the Network is still being validated and a report will be sent once
11567 // validation is complete. Note that networks which never undergo validation will still
11568 // have a cached ConnectivityReport with RESULT_SKIPPED.
11569 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11570 try {
11571 cb.onConnectivityReportAvailable(cachedReport);
11572 } catch (RemoteException ex) {
11573 loge("Error invoking onConnectivityReportAvailable", ex);
11574 }
11575 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011576 }
11577 }
11578
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011579 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011580 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11581 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011582 sanitized.setUids(null);
11583 sanitized.setAdministratorUids(new int[0]);
11584 sanitized.setOwnerUid(Process.INVALID_UID);
11585 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011586 }
11587
Cody Kestingf1120be2020-08-03 18:01:40 -070011588 /**
11589 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11590 *
11591 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11592 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011593 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011594 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011595 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011596 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011597 mConnectivityDiagnosticsCallbacks.entrySet()) {
11598 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11599 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011600
James Mattis64b8b0f2020-11-24 17:40:49 -080011601 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011602 if (!nai.satisfies(nri.mRequests.get(0))) {
11603 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011604 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011605
11606 // UID for this callback must either be:
11607 // - INVALID_UID (which sends callbacks to all UIDs), or
11608 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11609 // notified as a result)
11610 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11611 continue;
11612 }
11613
11614 if (!checkConnectivityDiagnosticsPermissions(
11615 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11616 continue;
11617 }
11618
11619 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011620 }
11621 return results;
11622 }
11623
Cody Kesting7474f672021-05-11 14:22:40 -070011624 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11625 @NonNull NetworkAgentInfo nai) {
11626 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11627 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11628 }
11629
Cody Kesting160ef392021-05-05 13:17:22 -070011630 private boolean hasLocationPermission(String packageName, int uid) {
11631 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11632 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11633 // call in a try-catch.
11634 try {
11635 if (!mLocationPermissionChecker.checkLocationPermission(
11636 packageName, null /* featureId */, uid, null /* message */)) {
11637 return false;
11638 }
11639 } catch (SecurityException e) {
11640 return false;
11641 }
11642
11643 return true;
11644 }
11645
11646 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11647 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011648 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011649 && virtual.networkCapabilities.getOwnerUid() == uid
11650 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11651 return true;
11652 }
11653 }
11654
11655 return false;
11656 }
11657
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011658 @VisibleForTesting
11659 boolean checkConnectivityDiagnosticsPermissions(
11660 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11661 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11662 return true;
11663 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011664 if (mAllowSysUiConnectivityReports
11665 && checkSystemBarServicePermission(callbackPid, callbackUid)) {
11666 return true;
11667 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011668
Cody Kesting160ef392021-05-05 13:17:22 -070011669 // Administrator UIDs also contains the Owner UID
11670 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11671 if (!CollectionUtils.contains(administratorUids, callbackUid)
11672 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011673 return false;
11674 }
11675
Cody Kesting7474f672021-05-11 14:22:40 -070011676 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11677 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011678 }
11679
Cody Kestingd199a9d2019-12-17 12:55:28 -080011680 @Override
11681 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011682 @NonNull IConnectivityDiagnosticsCallback callback,
11683 @NonNull NetworkRequest request,
11684 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011685 Objects.requireNonNull(callback, "callback must not be null");
11686 Objects.requireNonNull(request, "request must not be null");
11687 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11688
Cody Kesting73708bf2019-12-18 10:57:50 -080011689 if (request.legacyType != TYPE_NONE) {
11690 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11691 + " Please use NetworkCapabilities instead.");
11692 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011693 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011694 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011695
11696 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11697 // and administrator uids to be safe.
11698 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011699 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011700
11701 final NetworkRequest requestWithId =
11702 new NetworkRequest(
11703 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11704
11705 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11706 //
11707 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11708 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11709 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011710 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011711 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011712 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011713
11714 mConnectivityDiagnosticsHandler.sendMessage(
11715 mConnectivityDiagnosticsHandler.obtainMessage(
11716 ConnectivityDiagnosticsHandler
11717 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11718 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011719 }
11720
11721 @Override
11722 public void unregisterConnectivityDiagnosticsCallback(
11723 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011724 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011725 mConnectivityDiagnosticsHandler.sendMessage(
11726 mConnectivityDiagnosticsHandler.obtainMessage(
11727 ConnectivityDiagnosticsHandler
11728 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011729 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011730 0,
11731 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011732 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011733
Yan Yanfe96dde2022-12-05 23:00:01 +000011734 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11735 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11736 if (underlyingNetworks == null) return false;
11737
11738 for (Network network : underlyingNetworks) {
11739 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11740 return true;
11741 }
11742 }
11743 return false;
11744 }
11745
Cody Kestingf53a0752020-04-15 12:33:28 -070011746 @Override
11747 public void simulateDataStall(int detectionMethod, long timestampMillis,
11748 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011749 Objects.requireNonNull(network, "network must not be null");
11750 Objects.requireNonNull(extras, "extras must not be null");
11751
paulhu3ffffe72021-09-16 10:15:22 +080011752 enforceAnyPermissionOf(mContext,
11753 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011754 android.Manifest.permission.NETWORK_STACK);
11755 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011756 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11757 throw new SecurityException(
11758 "Data Stall simulation is only possible for test networks or networks built on"
11759 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011760 }
11761
11762 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011763 if (nai == null
11764 || (nai.creatorUid != mDeps.getCallingUid()
11765 && nai.creatorUid != Process.SYSTEM_UID)) {
11766 throw new SecurityException(
11767 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011768 }
11769
Cody Kesting652e3ec2020-05-21 12:08:21 -070011770 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11771 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11772 // Data Stall information as a DataStallReportParcelable and passing to
11773 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11774 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011775 final DataStallReportParcelable p = new DataStallReportParcelable();
11776 p.timestampMillis = timestampMillis;
11777 p.detectionMethod = detectionMethod;
11778
11779 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11780 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11781 }
11782 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11783 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11784 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11785 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11786 }
11787
Serik Beketayevec8ad212020-12-07 22:43:07 -080011788 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011789 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011790
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011791 /**
11792 * Class to hold the information for network activity change event from idle timers
11793 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11794 */
11795 private static final class NetworkActivityParams {
11796 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011797 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
11798 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011799 public final int label;
11800 public final long timestampNs;
11801 // Uid represents the uid that was responsible for waking the radio.
11802 // -1 for no uid and uid is -1 if isActive is false.
11803 public final int uid;
11804
11805 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11806 this.isActive = isActive;
11807 this.label = label;
11808 this.timestampNs = timestampNs;
11809 this.uid = uid;
11810 }
11811 }
11812
lucaslin66f44212021-02-23 01:12:55 +080011813 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11814 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011815 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011816 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011817 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11818 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011819 }
lucaslin37a16d92021-01-21 19:48:09 +080011820
11821 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011822 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011823 mHandler.post(() -> {
11824 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011825 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011826 }
11827 });
lucaslin37a16d92021-01-21 19:48:09 +080011828 }
11829
11830 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011831 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011832 mHandler.post(() -> {
11833 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011834 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011835 }
11836 });
lucaslin66f44212021-02-23 01:12:55 +080011837 }
11838 }
11839
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011840 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080011841 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11842
11843 /**
11844 * Class used for updating network activity tracking with netd and notify network activity
11845 * changes.
11846 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011847 @VisibleForTesting
11848 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011849 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011850 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011851 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011852 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011853 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11854 new RemoteCallbackList<>();
11855 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011856 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011857 // If there is no default network, default network is considered active to keep the existing
11858 // behavior. Initial value is used until first connect to the default network.
11859 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011860 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011861 // Key is netId. Value is configured idle timer information.
11862 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011863 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011864 // Store netIds of Wi-Fi networks whose idletimers report that they are active
11865 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
11866 // Store netIds of cellular networks whose idletimers report that they are active
11867 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011868
Chalard Jean46bfbf02022-02-02 00:56:25 +090011869 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011870 public final int timeout;
11871 public final int transportType;
11872
11873 IdleTimerParams(int timeout, int transport) {
11874 this.timeout = timeout;
11875 this.transportType = transport;
11876 }
11877 }
11878
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011879 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011880 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011881 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011882 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011883 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011884 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011885 }
11886
11887 private void ensureRunningOnConnectivityServiceThread() {
11888 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11889 throw new IllegalStateException("Not running on ConnectivityService thread: "
11890 + Thread.currentThread().getName());
11891 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011892 }
11893
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011894 /**
11895 * Update network activity and call BatteryStats to update radio power state if the
11896 * mobile or Wi-Fi activity is changed.
11897 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
11898 * mobile network is active since BatteryStatsService only maintains a single power state
11899 * for the mobile network.
11900 * The Wi-Fi network is also the same.
11901 *
11902 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
11903 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
11904 * transports.
11905 */
11906 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
11907 final boolean isActive, final int uid) {
11908 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
11909 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
11910 + transportType);
11911 return;
11912 }
11913 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
11914 ? mActiveWifiNetworks : mActiveCellularNetworks;
11915
11916 final boolean wasEmpty = activeNetworks.isEmpty();
11917 if (isActive) {
11918 activeNetworks.add(netId);
11919 } else {
11920 activeNetworks.remove(netId);
11921 }
11922
11923 if (wasEmpty != activeNetworks.isEmpty()) {
11924 updateRadioPowerState(isActive, transportType, uid);
11925 }
11926 }
11927
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011928 private void handleDefaultNetworkActivity(final int transportType,
11929 final boolean isActive, final long timestampNs) {
11930 mIsDefaultNetworkActive = isActive;
11931 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
11932 isActive, timestampNs);
11933 if (isActive) {
11934 reportNetworkActive();
11935 }
11936 }
11937
11938 private void handleReportNetworkActivityWithNetIdLabel(
11939 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011940 final int netId = activityParams.label;
11941 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011942 if (idleTimerParams == null) {
11943 // This network activity change is not tracked anymore
11944 // This can happen if netd callback post activity change event message but idle
11945 // timer is removed before processing this message.
11946 return;
11947 }
11948 // TODO: if a network changes transports, storing the transport type in the
11949 // IdleTimerParams is not correct. Consider getting it from the network's
11950 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011951 final int transportType = idleTimerParams.transportType;
11952 maybeUpdateRadioPowerState(netId, transportType,
11953 activityParams.isActive, activityParams.uid);
11954
11955 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
11956 // This activity change is not for the default network.
11957 return;
11958 }
11959
11960 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011961 activityParams.timestampNs);
11962 }
11963
11964 private void handleReportNetworkActivityWithTransportTypeLabel(
11965 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011966 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011967 // This activity change is not for the current default network.
11968 // This can happen if netd callback post activity change event message but
11969 // the default network is lost before processing this message.
11970 return;
11971 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011972 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
11973 activityParams.timestampNs);
11974 }
11975
11976 /**
11977 * Handle network activity change
11978 */
11979 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
11980 ensureRunningOnConnectivityServiceThread();
11981 if (mTrackMultiNetworkActivities) {
11982 handleReportNetworkActivityWithNetIdLabel(activityParams);
11983 } else {
11984 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080011985 }
11986 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011987
lucaslin1193a5d2021-01-21 02:04:15 +080011988 private void reportNetworkActive() {
11989 final int length = mNetworkActivityListeners.beginBroadcast();
11990 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11991 try {
11992 for (int i = 0; i < length; i++) {
11993 try {
11994 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11995 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011996 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011997 }
11998 }
11999 } finally {
12000 mNetworkActivityListeners.finishBroadcast();
12001 }
12002 }
12003
lucaslin1a8b4c62021-01-21 02:02:55 +080012004 // This is deprecated and only to support legacy use cases.
12005 private int transportTypeToLegacyType(int type) {
12006 switch (type) {
12007 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012008 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080012009 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012010 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080012011 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012012 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080012013 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012014 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080012015 default:
12016 loge("Unexpected transport in transportTypeToLegacyType: " + type);
12017 }
12018 return ConnectivityManager.TYPE_NONE;
12019 }
12020
12021 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12022 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12023 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12024 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12025 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12026 final long ident = Binder.clearCallingIdentity();
12027 try {
12028 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12029 RECEIVE_DATA_ACTIVITY_CHANGE,
12030 null /* resultReceiver */,
12031 null /* scheduler */,
12032 0 /* initialCode */,
12033 null /* initialData */,
12034 null /* initialExtra */);
12035 } finally {
12036 Binder.restoreCallingIdentity(ident);
12037 }
12038 }
12039
12040 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012041 * Get idle timer label
12042 */
12043 @VisibleForTesting
12044 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12045 final int netId, final int transportType) {
12046 return trackMultiNetworkActivities ? netId : transportType;
12047 }
12048
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012049 private boolean maybeCreateIdleTimer(
12050 String iface, int netId, int timeout, int transportType) {
12051 if (timeout <= 0 || iface == null) return false;
12052 try {
12053 final String label = Integer.toString(getIdleTimerLabel(
12054 mTrackMultiNetworkActivities, netId, transportType));
12055 mNetd.idletimerAddInterface(iface, timeout, label);
12056 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12057 return true;
12058 } catch (Exception e) {
12059 loge("Exception in createIdleTimer", e);
12060 return false;
12061 }
12062 }
12063
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012064 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012065 * Setup data activity tracking for the given network.
12066 *
12067 * Every {@code setupDataActivityTracking} should be paired with a
12068 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012069 *
12070 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012071 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012072 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012073 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012074 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012075 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012076
12077 final int timeout;
12078 final int type;
12079
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012080 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12081 // Do not track VPN network.
12082 return false;
12083 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012084 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12085 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012086 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012087 10);
12088 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12089 } else if (networkAgent.networkCapabilities.hasTransport(
12090 NetworkCapabilities.TRANSPORT_WIFI)) {
12091 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012092 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012093 15);
12094 type = NetworkCapabilities.TRANSPORT_WIFI;
12095 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012096 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012097 }
12098
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012099 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12100 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12101 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12102 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12103 // state only about a network that has an idletimer.
12104 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012105 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012106 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012107 }
12108
12109 /**
12110 * Remove data activity tracking when network disconnects.
12111 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012112 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12113 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 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12117
lucaslinb961efc2021-01-21 02:03:17 +080012118 if (iface == null) return;
12119
12120 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012121 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12122 // Do not track VPN network.
12123 return;
12124 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012125 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12126 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12127 type = NetworkCapabilities.TRANSPORT_WIFI;
12128 } else {
12129 return; // do not track any other networks
12130 }
12131
12132 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012133 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012134 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012135 if (params == null) {
12136 // IdleTimer is not added if the configured timeout is 0 or negative value
12137 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012138 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012139 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012140 final String label = Integer.toString(getIdleTimerLabel(
12141 mTrackMultiNetworkActivities, netId, params.transportType));
12142 // The call fails silently if no idle timer setup for this interface
12143 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012144 } catch (Exception e) {
12145 // You shall not crash!
12146 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012147 }
12148 }
12149
Motomu Utsumi6225d572023-05-29 15:08:57 +090012150 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12151 boolean hasIdleTimer) {
12152 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012153 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012154 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012155 // If only the default network is tracked, callbacks are called only when the
12156 // network has the idle timer.
12157 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012158 reportNetworkActive();
12159 }
12160 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012161 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012162 // If there is no default network, default network is considered active to keep the
12163 // existing behavior.
12164 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090012165 }
12166 }
12167
lucaslin1a8b4c62021-01-21 02:02:55 +080012168 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012169 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012170 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012171 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012172 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012173 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012174 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12175 // first connected and remove when the network is disconnected.
12176 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12177 // becomes the default network and remove when the network becomes no longer the default
12178 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012179 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012180 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012181 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012182 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012183 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012184 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012185 removeDataActivityTracking(oldNetwork);
12186 }
12187 }
lucaslinb961efc2021-01-21 02:03:17 +080012188
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012189 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012190 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12191 switch (transportType) {
12192 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012193 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012194 break;
12195 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012196 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012197 break;
12198 default:
12199 logw("Untracked transport type:" + transportType);
12200 }
12201 }
lucaslin1193a5d2021-01-21 02:04:15 +080012202
12203 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012204 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012205 }
12206
12207 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12208 mNetworkActivityListeners.register(l);
12209 }
12210
12211 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12212 mNetworkActivityListeners.unregister(l);
12213 }
lucaslin012f7a12021-01-21 02:04:35 +080012214
12215 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012216 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012217 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012218 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012219 pw.println("Idle timers:");
12220 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012221 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12222 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12223 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012224 pw.print(" timeout="); pw.print(params.timeout);
12225 pw.print(" type="); pw.println(params.transportType);
12226 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012227 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12228 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012229 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012230 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12231 // be accessed from handler thread, except dump(). As dump() is never called in
12232 // normal usage, it would be needlessly expensive to lock the collection only for
12233 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012234 // So catching the exception and logging.
12235 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012236 }
12237 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012238 }
James Mattis47db0582021-01-01 14:13:35 -080012239
Daniel Brightf9e945b2020-06-15 16:10:01 -070012240 /**
12241 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12242 *
12243 * @param socketInfo the socket information
12244 * @param callback the callback to register
12245 */
12246 @Override
12247 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12248 @NonNull final IQosCallback callback) {
12249 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12250 if (nai == null || nai.networkCapabilities == null) {
12251 try {
12252 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12253 } catch (final RemoteException ex) {
12254 loge("registerQosCallbackInternal: RemoteException", ex);
12255 }
12256 return;
12257 }
12258 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12259 }
12260
12261 /**
12262 * Register a {@link IQosCallback} with base {@link QosFilter}.
12263 *
12264 * @param filter the filter to register
12265 * @param callback the callback to register
12266 * @param nai the agent information related to the filter's network
12267 */
12268 @VisibleForTesting
12269 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12270 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012271 Objects.requireNonNull(filter, "filter must be non-null");
12272 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012273
12274 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012275 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12276 // on this network is unregistered when the app loses permission or b) no QoS
12277 // callbacks are sent for restricted networks unless the app currently has permission
12278 // to access restricted networks.
12279 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012280 }
12281 mQosCallbackTracker.registerCallback(callback, filter, nai);
12282 }
12283
12284 /**
12285 * Unregisters the given callback.
12286 *
12287 * @param callback the callback to unregister
12288 */
12289 @Override
12290 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012291 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012292 mQosCallbackTracker.unregisterCallback(callback);
12293 }
James Mattis47db0582021-01-01 14:13:35 -080012294
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012295 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12296 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12297 // Enterprise device can be fully managed like device owner and such use case
12298 // also should be supported. Calling app check for work profile and fully managed device
12299 // is already done in DevicePolicyManager.
12300 // This check is an extra caution to be sure device is fully managed or not.
12301 final UserManager um = mContext.getSystemService(UserManager.class);
12302 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12303 if (um.isManagedProfile(profile.getIdentifier())) {
12304 return true;
12305 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012306 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012307 return false;
12308 }
12309
James Mattis45d81842021-01-10 14:24:24 -080012310 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012311 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012312 *
12313 * See the documentation for the individual preferences for a description of the supported
12314 * behaviors.
12315 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012316 * @param profile If the device owner is set, any profile is allowed.
12317 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012318 * @param preferences the list of profile network preferences for the
12319 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012320 * @param listener an optional listener to listen for completion of the operation.
12321 */
12322 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012323 public void setProfileNetworkPreferences(
12324 @NonNull final UserHandle profile,
12325 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012326 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012327 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012328 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012329
12330 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012331 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12332 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12333 .build();
12334 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012335 }
12336
paulhu3ffffe72021-09-16 10:15:22 +080012337 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012338 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012339 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012340 }
12341 if (profile.getIdentifier() < 0) {
12342 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12343 + "UserHandle.CURRENT not supported)");
12344 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012345 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12346 throw new IllegalArgumentException("Profile must be a managed profile "
12347 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012348 }
paulhuaa0743d2021-05-26 21:56:03 +080012349
Chalard Jean0606fc82022-12-14 20:34:43 +090012350 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012351 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012352 for (final ProfileNetworkPreference preference : preferences) {
12353 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012354 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012355 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012356 switch (preference.getPreference()) {
12357 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12358 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012359 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012360 if (preference.getPreferenceEnterpriseId() != 0) {
12361 throw new IllegalArgumentException(
12362 "Invalid enterprise identifier in setProfileNetworkPreferences");
12363 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012364 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012365 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12366 blockingNonEnterprise = true;
12367 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012368 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12369 allowFallback = false;
12370 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012371 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012372 // This code is needed even though there is a check later on,
12373 // because isRangeAlreadyInPreferenceList assumes that every preference
12374 // has a UID list.
12375 if (hasDefaultPreference) {
12376 throw new IllegalArgumentException(
12377 "Default profile preference should not be set along with other "
12378 + "preference");
12379 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012380 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12381 throw new IllegalArgumentException(
12382 "Invalid enterprise identifier in setProfileNetworkPreferences");
12383 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012384 final Set<UidRange> uidRangeSet =
12385 getUidListToBeAppliedForNetworkPreference(profile, preference);
12386 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12387 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12388 } else {
12389 throw new IllegalArgumentException(
12390 "Overlapping uid range in setProfileNetworkPreferences");
12391 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012392 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012393 nc.addEnterpriseId(
12394 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012395 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12396 break;
12397 default:
12398 throw new IllegalArgumentException(
12399 "Invalid preference in setProfileNetworkPreferences");
12400 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012401 preferenceList.add(new ProfileNetworkPreferenceInfo(
12402 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012403 if (hasDefaultPreference && preferenceList.size() > 1) {
12404 throw new IllegalArgumentException(
12405 "Default profile preference should not be set along with other preference");
12406 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012407 }
12408 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012409 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012410 }
12411
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012412 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12413 @NonNull final UserHandle profile,
12414 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12415 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012416 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12417 profileNetworkPreference.getIncludedUids());
12418
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012419 if (uidRangeSet.size() > 0) {
12420 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12421 throw new IllegalArgumentException(
12422 "Allow uid range is outside the uid range of profile.");
12423 }
12424 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012425 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012426 profileNetworkPreference.getExcludedUids());
12427 if (disallowUidRangeSet.size() > 0) {
12428 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12429 throw new IllegalArgumentException(
12430 "disallow uid range is outside the uid range of profile.");
12431 }
12432 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12433 disallowUidRangeSet);
12434 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012435 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012436 uidRangeSet.add(profileUids);
12437 }
12438 }
12439 return uidRangeSet;
12440 }
12441
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012442 private boolean isEnterpriseIdentifierValid(
12443 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012444 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012445 return true;
12446 }
12447 return false;
12448 }
12449
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012450 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012451 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012452 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012453 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012454 // The NRI for a user should contain the request for capabilities.
12455 // If fallback to default network is needed then NRI should include
12456 // the request for the default network. Create an image of it to
12457 // have the correct UIDs in it (also a request can only be part of one NRI, because
12458 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012459 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12460 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012461 if (pref.allowFallback) {
12462 nrs.add(createDefaultInternetRequestForTransport(
12463 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12464 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012465 if (VDBG) {
12466 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12467 pref.capabilities.getUids()));
12468 }
12469
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012470 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012471 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012472 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012473 result.add(nri);
12474 }
12475 return result;
12476 }
12477
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012478 /**
12479 * Compare if the given UID range sets have the same UIDs.
12480 *
12481 */
12482 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012483 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012484 @NonNull Set<UidRange> uidRangeSet) {
12485 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12486 return false;
12487 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012488 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012489 if (UidRangeUtils.doesRangeSetOverlap(
12490 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12491 return true;
12492 }
12493 }
12494 return false;
12495 }
12496
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012497 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012498 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012499 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012500 /*
12501 * handleSetProfileNetworkPreference is always called for single user.
12502 * preferenceList only contains preferences for different uids within the same user
12503 * (enforced by getUidListToBeAppliedForNetworkPreference).
12504 * Clear all the existing preferences for the user before applying new preferences.
12505 *
12506 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012507 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12508 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012509 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12510 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012511
paulhu74128522021-09-28 02:29:03 +000012512 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12513 addPerAppDefaultNetworkRequests(
12514 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012515 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012516
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012517 // Finally, rematch.
12518 rematchAllNetworksAndRequests();
12519
12520 if (null != listener) {
12521 try {
12522 listener.onComplete();
12523 } catch (RemoteException e) {
12524 loge("Listener for setProfileNetworkPreference has died");
12525 }
12526 }
12527 }
12528
paulhu51f77dc2021-06-07 02:34:20 +000012529 @VisibleForTesting
12530 @NonNull
12531 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12532 @NonNull final Set<Integer> uids) {
12533 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12534 if (uids.size() == 0) {
12535 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12536 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12537 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12538 return nris;
12539 }
12540
12541 final List<NetworkRequest> requests = new ArrayList<>();
12542 // The NRI should be comprised of two layers:
12543 // - The request for the mobile network preferred.
12544 // - The request for the default network, for fallback.
12545 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012546 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012547 requests.add(createDefaultInternetRequestForTransport(
12548 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12549 final Set<UidRange> ranges = new ArraySet<>();
12550 for (final int uid : uids) {
12551 ranges.add(new UidRange(uid, uid));
12552 }
12553 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012554 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012555 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012556 return nris;
12557 }
12558
12559 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012560 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012561 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12562 addPerAppDefaultNetworkRequests(
12563 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012564 // Finally, rematch.
12565 rematchAllNetworksAndRequests();
12566 }
12567
Patrick Rohr2857ac42022-01-21 14:58:16 +010012568 private void handleIngressRateLimitChanged() {
12569 final long oldIngressRateLimit = mIngressRateLimit;
12570 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12571 mContext);
12572 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12573 if (canNetworkBeRateLimited(networkAgent)) {
12574 // If rate limit has previously been enabled, remove the old limit first.
12575 if (oldIngressRateLimit >= 0) {
12576 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12577 }
12578 if (mIngressRateLimit >= 0) {
12579 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12580 mIngressRateLimit);
12581 }
12582 }
12583 }
12584 }
12585
12586 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012587 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012588 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012589
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012590 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12591 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12592 // internet connectivity can be rate limited.
12593 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12594 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012595 return false;
12596 }
12597
12598 final String iface = networkAgent.linkProperties.getInterfaceName();
12599 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012600 // This may happen in tests, but if there is no interface then there is nothing that
12601 // can be rate limited.
12602 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012603 return false;
12604 }
12605 return true;
12606 }
12607
James Mattis45d81842021-01-10 14:24:24 -080012608 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012609 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12610 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012611 }
12612
12613 /**
12614 * Used by automotive devices to set the network preferences used to direct traffic at an
12615 * application level as per the given OemNetworkPreferences. An example use-case would be an
12616 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12617 * vehicle via a particular network.
12618 *
12619 * Calling this will overwrite the existing preference.
12620 *
James Mattisda32cfe2021-01-26 16:23:52 -080012621 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012622 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012623 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012624 */
James Mattis47db0582021-01-01 14:13:35 -080012625 @Override
James Mattis45d81842021-01-10 14:24:24 -080012626 public void setOemNetworkPreference(
12627 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012628 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012629
James Mattisfa270db2021-05-31 17:11:10 -070012630 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12631 // Only bypass the permission/device checks if this is a valid test request.
12632 if (isValidTestOemNetworkPreference(preference)) {
12633 enforceManageTestNetworksPermission();
12634 } else {
12635 enforceAutomotiveDevice();
12636 enforceOemNetworkPreferencesPermission();
12637 validateOemNetworkPreferences(preference);
12638 }
James Mattis45d81842021-01-10 14:24:24 -080012639
James Mattis45d81842021-01-10 14:24:24 -080012640 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12641 new Pair<>(preference, listener)));
12642 }
12643
James Mattisfa270db2021-05-31 17:11:10 -070012644 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012645 * Sets the specified UIDs to get/receive the VPN as the only default network.
12646 *
12647 * Calling this will overwrite the existing network preference for this session, and the
12648 * specified UIDs won't get any default network when no VPN is connected.
12649 *
12650 * @param session The VPN session which manages the passed UIDs.
12651 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12652 * setting for this session if the array is empty. Null is not allowed, the
12653 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12654 * @hide
12655 */
12656 @Override
12657 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12658 Objects.requireNonNull(ranges);
12659 enforceNetworkStackOrSettingsPermission();
12660 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12661 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12662 throw new IllegalArgumentException(
12663 "setVpnNetworkPreference: Passed UID ranges overlap");
12664 }
12665
12666 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12667 new VpnNetworkPreferenceInfo(session,
12668 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12669 }
12670
12671 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12672 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12673
12674 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12675 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12676
12677 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12678 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12679 // Finally, rematch.
12680 rematchAllNetworksAndRequests();
12681 }
12682
12683 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12684 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12685 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12686 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12687 final List<NetworkRequest> requests = new ArrayList<>();
12688 // Request VPN only, so other networks won't be the fallback options when VPN is not
12689 // connected temporarily.
12690 requests.add(createVpnRequest());
12691 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12692 setNetworkRequestUids(requests, uidRanges);
12693 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12694 }
12695 return nris;
12696 }
12697
12698 /**
James Mattisfa270db2021-05-31 17:11:10 -070012699 * Check the validity of an OEM network preference to be used for testing purposes.
12700 * @param preference the preference to validate
12701 * @return true if this is a valid OEM network preference test request.
12702 */
12703 private boolean isValidTestOemNetworkPreference(
12704 @NonNull final OemNetworkPreferences preference) {
12705 // Allow for clearing of an existing OemNetworkPreference used for testing.
12706 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12707 // changes after this check is complete. This is an unlikely scenario as calling of this API
12708 // is controlled by the OEM therefore the added complexity is not worth adding given those
12709 // circumstances. That said, it is an edge case to be aware of hence this comment.
12710 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12711 && isTestOemNetworkPreference(mOemNetworkPreferences);
12712 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12713 }
12714
12715 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12716 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12717 return prefMap.size() == 1
12718 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12719 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12720 }
12721
James Mattis45d81842021-01-10 14:24:24 -080012722 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12723 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12724 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012725 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12726 throw new IllegalArgumentException(
12727 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12728 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012729 }
12730 }
12731 }
12732
12733 private void handleSetOemNetworkPreference(
12734 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012735 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012736 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12737 if (DBG) {
12738 log("set OEM network preferences :" + preference.toString());
12739 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012740
James Mattiscb1e0362021-04-06 17:07:42 -070012741 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012742 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12743 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12744 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012745 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012746
12747 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012748 try {
12749 listener.onComplete();
12750 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012751 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012752 }
James Mattis45d81842021-01-10 14:24:24 -080012753 }
12754 }
12755
paulhu74128522021-09-28 02:29:03 +000012756 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012757 // Skip the requests which are set by other network preference. Because the uid range rules
12758 // should stay in netd.
12759 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012760 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012761 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012762 }
12763
James Mattis3ce3d3c2021-02-09 18:18:28 -080012764 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12765 ensureRunningOnConnectivityServiceThread();
12766 mDefaultNetworkRequests.addAll(nris);
12767 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12768 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012769 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012770 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12771 nrisToRegister.addAll(
12772 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12773 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012774 }
12775
12776 /**
12777 * All current requests that are tracking the default network need to be assessed as to whether
12778 * or not the current set of per-application default requests will be changing their default
12779 * network. If so, those requests will need to be updated so that they will send callbacks for
12780 * default network changes at the appropriate time. Additionally, those requests tracking the
12781 * default that were previously updated by this flow will need to be reassessed.
12782 * @return the nris which will need to be updated.
12783 */
12784 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12785 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12786 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12787 // same nri in the map's values for each of its NetworkRequest objects.
12788 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012789 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012790 // Include this nri if it is currently being tracked.
12791 if (isPerAppTrackedNri(nri)) {
12792 defaultCallbackRequests.add(nri);
12793 continue;
12794 }
12795 // We only track callbacks for requests tracking the default.
12796 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12797 continue;
12798 }
12799 // Include this nri if it will be tracked by the new per-app default requests.
12800 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012801 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012802 if (isNriGoingToBeTracked) {
12803 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012804 }
12805 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012806 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012807 }
12808
James Mattis3ce3d3c2021-02-09 18:18:28 -080012809 /**
12810 * Create nris for those network requests that are currently tracking the default network that
12811 * are being controlled by a per-application default.
12812 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12813 * foundation when creating the nri. Important items include the calling uid's original
12814 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12815 * requests are assumed to have already been validated as needing to be updated.
12816 * @return the Set of nris to use when registering network requests.
12817 */
12818 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12819 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12820 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12821 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12822 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012823 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012824
Chalard Jean9473c982021-07-29 20:03:04 +090012825 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012826 if (trackingNri == mDefaultRequest) {
12827 callbackRequestsToRegister.add(new NetworkRequestInfo(
12828 callbackRequest,
12829 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12830 continue;
12831 }
12832
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012833 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012834 callbackRequestsToRegister.add(new NetworkRequestInfo(
12835 callbackRequest,
12836 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012837 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012838 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012839 }
12840 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012841 }
12842
Chalard Jean17215832021-03-01 14:06:28 +090012843 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12844 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012845 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012846 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012847 }
12848 }
12849
James Mattis45d81842021-01-10 14:24:24 -080012850 /**
12851 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12852 */
12853 @VisibleForTesting
12854 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012855 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012856 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012857 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012858 final SparseArray<Set<Integer>> uids =
12859 createUidsFromOemNetworkPreferences(preference);
12860 for (int i = 0; i < uids.size(); i++) {
12861 final int key = uids.keyAt(i);
12862 final Set<Integer> value = uids.valueAt(i);
12863 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12864 // No need to add an nri without any requests.
12865 if (0 == nri.mRequests.size()) {
12866 continue;
12867 }
12868 nris.add(nri);
12869 }
12870
12871 return nris;
12872 }
12873
12874 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12875 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012876 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012877 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012878 final List<UserHandle> users =
12879 mContext.getSystemService(UserManager.class).getUserHandles(true);
12880 if (null == users || users.size() == 0) {
12881 if (VDBG || DDBG) {
12882 log("No users currently available for setting the OEM network preference.");
12883 }
James Mattisb6b6a432021-06-01 22:30:36 -070012884 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012885 }
James Mattis45d81842021-01-10 14:24:24 -080012886 for (final Map.Entry<String, Integer> entry :
12887 preference.getNetworkPreferences().entrySet()) {
12888 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012889 // Add the rules for all users as this policy is device wide.
12890 for (final UserHandle user : users) {
12891 try {
12892 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12893 if (!prefToUids.contains(pref)) {
12894 prefToUids.put(pref, new ArraySet<>());
12895 }
12896 prefToUids.get(pref).add(uid);
12897 } catch (PackageManager.NameNotFoundException e) {
12898 // Although this may seem like an error scenario, it is ok that uninstalled
12899 // packages are sent on a network preference as the system will watch for
12900 // package installations associated with this network preference and update
12901 // accordingly. This is done to minimize race conditions on app install.
12902 continue;
James Mattis45d81842021-01-10 14:24:24 -080012903 }
James Mattis45d81842021-01-10 14:24:24 -080012904 }
12905 }
James Mattisb6b6a432021-06-01 22:30:36 -070012906 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012907 }
12908
12909 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12910 @OemNetworkPreferences.OemNetworkPreference final int preference,
12911 @NonNull final Set<Integer> uids) {
12912 final List<NetworkRequest> requests = new ArrayList<>();
12913 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12914 switch (preference) {
12915 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12916 requests.add(createUnmeteredNetworkRequest());
12917 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012918 requests.add(createDefaultInternetRequestForTransport(
12919 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012920 break;
12921 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12922 requests.add(createUnmeteredNetworkRequest());
12923 requests.add(createOemPaidNetworkRequest());
12924 break;
12925 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12926 requests.add(createOemPaidNetworkRequest());
12927 break;
12928 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12929 requests.add(createOemPrivateNetworkRequest());
12930 break;
James Mattisfa270db2021-05-31 17:11:10 -070012931 case OEM_NETWORK_PREFERENCE_TEST:
12932 requests.add(createUnmeteredNetworkRequest());
12933 requests.add(createTestNetworkRequest());
12934 requests.add(createDefaultRequest());
12935 break;
12936 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12937 requests.add(createTestNetworkRequest());
12938 break;
James Mattis45d81842021-01-10 14:24:24 -080012939 default:
12940 // This should never happen.
12941 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12942 + " called with invalid preference of " + preference);
12943 }
12944
James Mattisfa270db2021-05-31 17:11:10 -070012945 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012946 for (final int uid : uids) {
12947 ranges.add(new UidRange(uid, uid));
12948 }
12949 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012950 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012951 }
12952
12953 private NetworkRequest createUnmeteredNetworkRequest() {
12954 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12955 .addCapability(NET_CAPABILITY_NOT_METERED)
12956 .addCapability(NET_CAPABILITY_VALIDATED);
12957 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12958 }
12959
12960 private NetworkRequest createOemPaidNetworkRequest() {
12961 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12962 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12963 .addCapability(NET_CAPABILITY_OEM_PAID)
12964 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12965 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12966 }
12967
12968 private NetworkRequest createOemPrivateNetworkRequest() {
12969 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12970 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12971 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12972 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12973 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12974 }
12975
12976 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012977 final NetworkCapabilities netcap = new NetworkCapabilities();
12978 netcap.addCapability(NET_CAPABILITY_INTERNET);
12979 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12980 return netcap;
12981 }
12982
12983 private NetworkRequest createTestNetworkRequest() {
12984 final NetworkCapabilities netcap = new NetworkCapabilities();
12985 netcap.clearAll();
12986 netcap.addTransportType(TRANSPORT_TEST);
12987 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012988 }
James Mattis47db0582021-01-01 14:13:35 -080012989 }
markchien738ad912021-12-09 18:15:45 +080012990
Ken Chen24330172023-10-20 13:02:14 +080012991 @TargetApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080012992 @Override
Junyu Laidf210362023-10-24 02:47:50 +000012993 public void setDataSaverEnabled(final boolean enable) {
12994 enforceNetworkStackOrSettingsPermission();
12995 try {
12996 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
12997 if (!ret) {
12998 throw new IllegalStateException("Error when changing iptables: " + enable);
12999 }
13000 } catch (RemoteException e) {
13001 // Lack of permission or binder errors.
13002 throw new IllegalStateException(e);
13003 }
Ken Chen24330172023-10-20 13:02:14 +080013004
13005 try {
13006 mBpfNetMaps.setDataSaverEnabled(enable);
13007 } catch (ServiceSpecificException | UnsupportedOperationException e) {
13008 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
13009 }
Junyu Laidf210362023-10-24 02:47:50 +000013010 }
13011
13012 @Override
markchien738ad912021-12-09 18:15:45 +080013013 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
13014 enforceNetworkStackOrSettingsPermission();
13015
13016 try {
13017 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013018 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013019 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013020 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013021 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013022 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013023 throw new IllegalStateException(e);
13024 }
13025 }
13026
13027 @Override
13028 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13029 enforceNetworkStackOrSettingsPermission();
13030
13031 try {
13032 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013033 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013034 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013035 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013036 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013037 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013038 throw new IllegalStateException(e);
13039 }
13040 }
markchiene1561fa2021-12-09 22:00:56 +080013041
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013042 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13043 throws PackageManager.NameNotFoundException {
13044 final PackageManager pm = mContext.getPackageManager();
13045 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13046 if (appId < Process.FIRST_APPLICATION_UID) {
13047 throw new RuntimeException("Can't set package firewall rule for system app "
13048 + packageName + " with appId " + appId);
13049 }
13050 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13051 final int uid = uh.getUid(appId);
13052 setUidFirewallRule(chain, uid, rule);
13053 }
13054 return appId;
13055 }
13056
markchiene1561fa2021-12-09 22:00:56 +080013057 @Override
markchien3c04e662022-03-22 16:29:56 +080013058 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013059 enforceNetworkStackOrSettingsPermission();
13060
markchien3c04e662022-03-22 16:29:56 +080013061 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13062 int firewallRule = getFirewallRuleType(chain, rule);
13063
13064 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13065 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13066 }
13067
markchiene1561fa2021-12-09 22:00:56 +080013068 try {
markchien3c04e662022-03-22 16:29:56 +080013069 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013070 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013071 throw new IllegalStateException(e);
13072 }
13073 }
markchien98a6f952022-01-13 23:43:53 +080013074
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013075 private int getPackageFirewallRule(final int chain, final String packageName)
13076 throws PackageManager.NameNotFoundException {
13077 final PackageManager pm = mContext.getPackageManager();
13078 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13079 return getUidFirewallRule(chain, appId);
13080 }
13081
Motomu Utsumi900b8062023-01-19 16:16:49 +090013082 @Override
13083 public int getUidFirewallRule(final int chain, final int uid) {
13084 enforceNetworkStackOrSettingsPermission();
13085 return mBpfNetMaps.getUidRule(chain, uid);
13086 }
13087
markchien3c04e662022-03-22 16:29:56 +080013088 private int getFirewallRuleType(int chain, int rule) {
13089 final int defaultRule;
13090 switch (chain) {
13091 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013092 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13093 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013094 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013095 defaultRule = FIREWALL_RULE_ALLOW;
13096 break;
13097 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13098 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13099 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13100 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013101 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013102 defaultRule = FIREWALL_RULE_DENY;
13103 break;
13104 default:
13105 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13106 }
13107 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13108
13109 return rule;
13110 }
13111
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013112 private void closeSocketsForFirewallChainLocked(final int chain)
13113 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013114 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013115 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13116 // So, close all non-system socket owned by uids that are not explicitly allowed
13117 Set<Range<Integer>> ranges = new ArraySet<>();
13118 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13119 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13120 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13121 } else {
13122 // Denylist means the firewall allows all by default, uids must be explicitly denied
13123 // So, close socket owned by uids that are explicitly denied
13124 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13125 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13126 }
13127 }
13128
markchien98a6f952022-01-13 23:43:53 +080013129 @Override
13130 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13131 enforceNetworkStackOrSettingsPermission();
13132
13133 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013134 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013135 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013136 throw new IllegalStateException(e);
13137 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013138
Chalard Jeandf29a852023-05-29 17:02:43 +090013139 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013140 try {
13141 closeSocketsForFirewallChainLocked(chain);
13142 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13143 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13144 }
13145 }
markchien98a6f952022-01-13 23:43:53 +080013146 }
13147
markchien00a0bed2022-01-13 23:46:13 +080013148 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013149 public boolean getFirewallChainEnabled(final int chain) {
13150 enforceNetworkStackOrSettingsPermission();
13151
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013152 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013153 }
13154
13155 @Override
markchien00a0bed2022-01-13 23:46:13 +080013156 public void replaceFirewallChain(final int chain, final int[] uids) {
13157 enforceNetworkStackOrSettingsPermission();
13158
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013159 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013160 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013161
13162 @Override
13163 public IBinder getCompanionDeviceManagerProxyService() {
13164 enforceNetworkStackPermission(mContext);
13165 return mCdmps;
13166 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013167
13168 @Override
13169 public IBinder getRoutingCoordinatorService() {
13170 enforceNetworkStackPermission(mContext);
13171 return mRoutingCoordinatorService;
13172 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013173}