blob: 9e5e03f7979c92a55c73d8c988ca5484f0f095b2 [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 Fasheh7501e762023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
Chalard Jeane0aaca52023-10-17 13:23:07 +090022import static android.content.pm.PackageManager.FEATURE_LEANBACK;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090023import static android.content.pm.PackageManager.FEATURE_WATCH;
24import static android.content.pm.PackageManager.FEATURE_WIFI;
25import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090026import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090027import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
29import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
34import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Junyu Lai38c75032023-12-04 07:52:19 +000035import static android.net.ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090036import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
37import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000038import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang25ef1712021-06-08 13:11:45 +080039import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070040import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080041import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
42import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
43import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090044import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090045import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090046import static android.net.ConnectivityManager.TYPE_MOBILE;
47import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
49import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
50import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
51import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
52import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
53import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
54import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
55import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070056import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090057import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070058import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090059import static android.net.ConnectivityManager.TYPE_WIFI;
60import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070061import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070062import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080063import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070066import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080067import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040068import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
75import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090077import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090079import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080080import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
81import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080082import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090083import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090084import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080085import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
86import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080087import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
88import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
89import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090090import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090091import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060092import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070093import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080094import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090095import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070096import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
97import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070098import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080099import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100100import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700101import static android.system.OsConstants.IPPROTO_TCP;
102import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -0600103
Junyu Lai155760b2023-10-05 14:51:00 +0800104import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
105import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
106import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
107import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
108import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Xiao Ma60142372022-07-16 17:30:20 +0900109import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800110import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800111import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
112import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
113import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900114import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900115
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800116import static java.util.Map.Entry;
117
Chalard Jean5b639762020-03-09 21:25:37 +0900118import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000119import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800120import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600121import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800122import android.annotation.TargetApi;
Mark Fasheh7501e762023-05-04 20:23:11 +0000123import android.app.ActivityManager;
124import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800125import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800126import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700127import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700128import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900129import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800130import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700131import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800132import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800133import android.content.ContentResolver;
134import android.content.Context;
135import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700136import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800137import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900138import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700139import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800140import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900141import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900142import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700143import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800144import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800145import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800146import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900147import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800148import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900149import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800150import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900151import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800152import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700153import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900154import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800155import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800157import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800158import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800159import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900160import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900161import android.net.INetworkMonitor;
162import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900163import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900164import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700165import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800166import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900167import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900168import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900169import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800170import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900171import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900172import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100173import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800174import android.net.NativeNetworkConfig;
175import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800176import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700177import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700178import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900179import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700180import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800181import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700182import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900183import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900184import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000185import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900186import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700187import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900188import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700189import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900190import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700191import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800192import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900193import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700194import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000195import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800196import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900197import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800198import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400199import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700200import android.net.QosCallbackException;
201import android.net.QosFilter;
202import android.net.QosSocketFilter;
203import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700204import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800205import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800206import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900207import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400208import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800209import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800210import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400211import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800212import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900213import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900214import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900215import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900216import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800217import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900218import android.net.networkstack.ModuleNetworkStackClient;
219import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900220import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800221import android.net.resolv.aidl.DnsHealthEventParcel;
222import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
223import android.net.resolv.aidl.Nat64PrefixEventParcel;
224import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900225import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900226import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800227import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800228import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800229import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700230import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000231import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700233import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700234import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800235import android.os.Looper;
236import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700237import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700238import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900239import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800240import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700241import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700242import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800243import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700244import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900245import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900246import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700247import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700248import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400249import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800250import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900251import android.stats.connectivity.MeteredState;
252import android.stats.connectivity.RequestType;
253import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900254import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700255import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700256import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700257import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800258import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900259import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000260import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600261import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900262import android.util.Pair;
Motomu Utsumia20f7602023-03-16 17:04:21 +0900263import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700264import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700265import android.util.SparseIntArray;
Tommy Webb34f81dc2023-02-20 14:10:55 -0500266import android.util.SparseLongArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900267import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800268
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800269import androidx.annotation.RequiresApi;
270
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900271import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400272import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400273import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700274import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900275import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900276import com.android.metrics.ConnectionDurationForTransports;
277import com.android.metrics.ConnectionDurationPerTransports;
278import com.android.metrics.ConnectivitySampleMetricsHelper;
279import com.android.metrics.ConnectivityStateSample;
280import com.android.metrics.NetworkCountForTransports;
281import com.android.metrics.NetworkCountPerTransports;
282import com.android.metrics.NetworkDescription;
283import com.android.metrics.NetworkList;
284import com.android.metrics.NetworkRequestCount;
285import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800286import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900287import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800288import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000289import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900290import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800291import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900292import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900293import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100294import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900295import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
296import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900297import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800298import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800299import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100300import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000301import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800302import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
303import com.android.networkstack.apishim.ConstantsShim;
304import com.android.networkstack.apishim.common.BroadcastOptionsShim;
305import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900306import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900307import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000308import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900309import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800310import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800311import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900312import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VAN6ca02962023-02-20 20:10:09 +0900313import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900314import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500315import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700316import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900317import com.android.server.connectivity.FullScore;
Junyu Laif8dba342023-10-12 17:01:03 +0800318import com.android.server.connectivity.HandlerUtils;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900319import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VAN6ca02962023-02-20 20:10:09 +0900320import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000321import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100322import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700323import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900324import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700325import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600326import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900327import com.android.server.connectivity.NetworkNotificationManager;
328import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900329import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900330import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900331import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700332import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900333import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900334import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700335import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900336import com.android.server.connectivity.RoutingCoordinatorService;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800337import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000338import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800339import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600340
Josh Gao461a1222020-06-16 15:58:11 -0700341import libcore.io.IoUtils;
342
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900343import org.xmlpull.v1.XmlPullParserException;
344
The Android Open Source Project28527d22009-03-03 19:31:44 -0800345import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100346import java.io.IOException;
Motomu Utsumia20f7602023-03-16 17:04:21 +0900347import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800348import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900349import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700350import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700351import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900352import java.net.InetSocketAddress;
Motomu Utsumia20f7602023-03-16 17:04:21 +0900353import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700354import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700355import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700356import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700357import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800358import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900359import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800360import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700361import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700362import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700363import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700364import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900365import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700366import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900367import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600368import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900369import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600370import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900371import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900372import java.util.concurrent.atomic.AtomicInteger;
Tommy Webb34f81dc2023-02-20 14:10:55 -0500373import java.util.stream.Collectors;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800374
375/**
376 * @hide
377 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800378public class ConnectivityService extends IConnectivityManager.Stub
379 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900380 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800381
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900382 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900383 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900384 private static final String NETWORK_ARG = "networks";
385 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800386 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900387
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900388 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900389 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
390 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800391
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900392 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700393
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100394 /**
395 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
396 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800397 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100398 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
399 * (preferably via runtime resource overlays).
400 */
401 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
402 "http://connectivitycheck.gstatic.com/generate_204";
403
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700404 // TODO: create better separation between radio types and network types
405
Robert Greenwalt2034b912009-08-12 16:08:25 -0700406 // how long to wait before switching back to a radio's default network
407 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
408 // system property that can override the above value
409 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
410 "android.telephony.apn-restore";
411
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900412 // How long to wait before putting up a "This network doesn't have an Internet connection,
413 // connect anyway?" dialog after the user selects a network that doesn't validate.
414 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
415
Chalard Jean5fb43c72022-09-08 19:03:14 +0900416 // How long to wait before considering that a network is bad in the absence of any form
417 // of connectivity (valid, partial, captive portal). If none has been detected after this
418 // delay, the stack considers this network bad, which may affect how it's handled in ranking
419 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900420 // Timeout in case the "actively prefer bad wifi" feature is on
421 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
422 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean3f0ff5b2023-06-05 19:26:17 +0900423 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900424
junyulai0ac374f2020-12-14 18:41:52 +0800425 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900426 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
427 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800428 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700429
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800430 // Delimiter used when creating the broadcast delivery group for sending
431 // CONNECTIVITY_ACTION broadcast.
432 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
433
he_won.hwang881307a2022-03-15 21:23:52 +0900434 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900435 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900436
Daniel Brightf9e945b2020-06-15 16:10:01 -0700437 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900438 @VisibleForTesting
439 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700440
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900441 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700442 @VisibleForTesting
443 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900444
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900445 @VisibleForTesting
446 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800447 @VisibleForTesting
448 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900449 // True if the cell radio of the device is capable of time-sharing.
450 @VisibleForTesting
451 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900452
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800453 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800454 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800455 private final int mReleasePendingIntentDelayMs;
456
Chalard Jean46bfbf02022-02-02 00:56:25 +0900457 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900458
Motomu Utsumif360aa62023-01-30 17:52:20 +0900459 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700460
Chalard Jean9473c982021-07-29 20:03:04 +0900461 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800462 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700463 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800464 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700465
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900466 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700467
junyulaif2c67e42018-08-07 19:50:45 +0800468 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000469 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
470 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800471 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900472 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800473
Tommy Webb34f81dc2023-02-20 14:10:55 -0500474 /** Map of UID to its bit-packed allowed transports. */
475 private SparseLongArray mUidAllowedTransports = new SparseLongArray();
476
477 /** Allowed UID ranges provided to Netd, tracked based on the netId to which they belong. */
478 @GuardedBy("mNetworkForNetId")
479 private Map<Integer, NativeUidRangeConfig> mNetIdToAllowlist =
480 new HashMap<Integer, NativeUidRangeConfig>();
481
482 /**
483 * UIDs that we wish to be denied access to networks based on certain policies, grouped by the
484 * netId to which they belong. Used to prevent affected UIDs from getting online through a VPN
485 * or from receiving incoming traffic when their active network is denied to them.
486 */
487 @GuardedBy("mNetworkForNetId")
488 private Map<Integer, List<Integer>> mNetIdToDisallowedUids = new HashMap<>();
489
490 private void setUidsAllowedTransports(@NonNull final int[] uids,
491 @NonNull final long[] allowedTransportsPacked) {
492 mHandler.post(() -> handleSetUidsAllowedTransports(uids, allowedTransportsPacked));
493 }
494
495 private void handleSetUidsAllowedTransports(@NonNull final int[] uids,
496 @NonNull final long[] allowedTransportsPacked) {
497 for (int i = 0; i < uids.length; i++) {
498 final int uid = uids[i];
499 final long transportsPacked = allowedTransportsPacked[i];
500 mUidAllowedTransports.put(uid, transportsPacked);
501 }
502 if (DDBG) Log.d(TAG, "setUidsAllowedTransports: Processing " + uids.length + " UIDs...");
503 for (final var nai : mNetworkAgentInfos) {
504 updateDisallowedUidsForNetwork(nai);
505 if (nai.isVPN()) {
506 // VPNs manage their own allowed UID ranges, so we handle them via denylist above.
507 continue;
508 }
509 for (final int uid : uids) {
510 if (nai.networkCapabilities.appliesToUid(uid)) {
511 updateAllowedUidsForNetwork(nai);
512 break;
513 }
514 }
515 }
516 if (DDBG) Log.d(TAG, "setUidsAllowedTransports: Processed " + uids.length + " UIDs.");
517 }
518
519 // The last UID denylist that we supplied to BPF.
520 // To support access across threads, do not modify after assignment.
521 private Set<Integer> mLastDisallowedUidsDenylist = Set.of();
522
523 /**
524 * Computes which policies apply to the given network to determine which UIDs should be
525 * prevented from accessing that network. Then, for each network with disallowed UIDs, checks
526 * whether the network is currently the active network for the UID, and if so, prevents the
527 * UID from accessing networks entirely via a denylist. Without this, UIDs are able to use VPNs
528 * even if their policy disallows it, because the VPN itself manages its allowed UID ranges.
529 * Additionally, this prevents incoming traffic for UIDs whose active network is disallowed.
530 *
531 * NOTE: UIDs with restricted networking permission are never disallowed.
532 */
533 private void updateDisallowedUidsForNetwork(@NonNull final NetworkAgentInfo nai) {
534 ensureRunningOnConnectivityServiceThread();
535
536 final var netId = nai.network.netId;
537 final var ourTag = "updateDisallowedUidsForNetwork(" + netId + "): ";
538 if (DDBG) Log.d(TAG, ourTag + "begin");
539 final var disallowedUids = getUidsDisallowedByPolicyForNetwork(nai);
540 final Set<Integer> prevDenylist;
541 final Set<Integer> newDenylist = new ArraySet<Integer>();
542 synchronized (mNetworkForNetId) {
543 prevDenylist = mLastDisallowedUidsDenylist;
544 if (mNetworkForNetId.contains(netId)) {
545 // Only store the disallowed UIDs if this network still exists.
546 mNetIdToDisallowedUids.put(netId, disallowedUids);
547 }
548 for (final var entry : mNetIdToDisallowedUids.entrySet()) {
549 final var entryNetId = entry.getKey();
550 final var entryDisallowedUids = entry.getValue();
551 entryDisallowedUids.forEach(uid -> {
552 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
553 // Skip denylist for UIDs with restricted networks permission.
554 return;
555 }
556 // Disallowing UIDs is only applicable if the network is the UID's active
557 // network. For us, a VPN that is still connecting should still be considered,
558 // because it is *about* to become the active network, and we are reacting
559 // early. If we do not include connecting VPNs, we get no result.
560 // Also, if we don't know the active network, denying is fine for now.
561 final var activeNetwork = getActiveNetworkOrConnectingVpnForUidInternal(
562 uid, true /* ignoreBlocked */);
563 if (activeNetwork == null || entryNetId == activeNetwork.netId) {
564 newDenylist.add(uid);
565 }
566 });
567 }
568 mLastDisallowedUidsDenylist = Collections.unmodifiableSet(newDenylist);
569 }
570 // NOTE: Setting UID rules individually is exponentially faster than replacing the whole
571 // firewall chain for some reason (<1ms vs 10+ms, even with few UIDs for the latter
572 // and hundreds for the former).
573 final var toAdd = newDenylist.stream().filter(uid -> !prevDenylist.contains(uid))
574 .collect(Collectors.toSet());
575 if (DDBG) {
576 synchronized (mNetworkForNetId) {
577 Log.d(TAG, ourTag + "Disallowed UIDs per netId: " + mNetIdToDisallowedUids);
578 }
579 Log.d(TAG, ourTag + "Prev denylist: " + prevDenylist);
580 Log.d(TAG, ourTag + "New denylist: " + newDenylist);
581 }
582 final var toRemove = prevDenylist.stream().filter(uid -> !newDenylist.contains(uid))
583 .collect(Collectors.toSet());
584 if (DDBG) Log.d(TAG, ourTag + "toAdd: " + toAdd + "; toRemove: " + toRemove);
585 if (toAdd.isEmpty() && toRemove.isEmpty()) {
586 // Nothing to do.
587 return;
588 }
589 boolean anyFailed = false;
590 for (final int uid : toAdd) {
591 try {
592 mBpfNetMaps.setUidRule(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1, uid,
593 FIREWALL_RULE_DENY);
594 } catch (ServiceSpecificException e) {
595 loge(ourTag + "Failed to add uid " + uid, e);
596 anyFailed = true;
597 break;
598 }
599 }
600 if (!anyFailed) {
601 for (final int uid : toRemove) {
602 try {
603 mBpfNetMaps.setUidRule(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1, uid,
604 FIREWALL_RULE_ALLOW);
605 } catch (ServiceSpecificException e) {
606 loge(ourTag + "Failed to remove uid " + uid, e);
607 anyFailed = true;
608 break;
609 }
610 }
611 }
612 if (anyFailed) {
613 // Should never happen, but just in case.
614 replaceFirewallChain(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1,
615 newDenylist.stream().mapToInt(Integer::intValue).toArray());
616 }
617 // Tell NPMS about the changes, primarily so the firewall icon can reflect them.
618 mPolicyManager.notifyDenylistChanged(toAdd.stream().mapToInt(Integer::intValue).toArray(),
619 toRemove.stream().mapToInt(Integer::intValue).toArray());
620 if (DDBG) Log.d(TAG, ourTag + "end");
621 }
622
623
624 /**
625 * Generates an allowlist configuration for Netd that reflects a network's allowed UIDs and
626 * includes a sub priority to allow the network to act as a default network for the UIDs
627 * if it is considered to be the default network overall. This default network handling is
628 * required, or else UIDs that do not make specific network requests will have no connectivity.
629 */
630 private NativeUidRangeConfig getAllowlistedNativeUidRangeConfigForNetwork(
631 @NonNull final NetworkAgentInfo nai) {
632 final int netId = nai.network.netId;
633 final var uidsAllowedByPolicy = getUidRangeParcelsAllowedByPolicyForNetwork(nai);
634 final boolean isDefault = isDefaultNetwork(nai);
635 final int subPriority = isDefault ? PREFERENCE_ORDER_LOWEST_WITH_DEFAULT
636 : PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT;
637 return new NativeUidRangeConfig(netId, uidsAllowedByPolicy, subPriority);
638 }
639
640 /**
641 * Updates our tracked configurations for Netd based on changes to default networks, and
642 * informs Netd if any changes need to be made to ensure that allowed UIDs do or do not utilize
643 * changed networks as their default network. This default network handling is required, or
644 * else UIDs that do not make specific network requests will have no connectivity or will
645 * have their traffic traverse the wrong network.
646 */
647 private void updateUidDefaultNetworkRules(@Nullable final NetworkAgentInfo newDefaultNetwork) {
648 final Integer defaultNetId = newDefaultNetwork == null ? null
649 : newDefaultNetwork.network.netId;
650 final var configs = new ArrayList<Pair<NativeUidRangeConfig, NativeUidRangeConfig>>();
651 final var networksForUpdateDisallowedUids = new ArrayList<NetworkAgentInfo>();
652 synchronized (mNetworkForNetId) {
653 for (final var config : mNetIdToAllowlist.values()) {
654 final var configIsDefault =
655 config.subPriority == PREFERENCE_ORDER_LOWEST_WITH_DEFAULT;
656 final int subPriority;
657 if (configIsDefault && !Objects.equals(config.netId, defaultNetId)) {
658 // Remove and replace any existing rules with a subPriority for default.
659 subPriority = PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT;
660 } else if (!configIsDefault && Objects.equals(config.netId, defaultNetId)) {
661 // Remove and replace any existing rules with a subPriority for default.
662 subPriority = PREFERENCE_ORDER_LOWEST_WITH_DEFAULT;
663 } else {
664 continue;
665 }
666 final var newConfig =
667 new NativeUidRangeConfig(config.netId, config.uidRanges, subPriority);
668 mNetIdToAllowlist.put(newConfig.netId, newConfig);
669 configs.add(new Pair<>(config, newConfig));
670 final var nai = mNetworkForNetId.get(config.netId);
671 if (nai != null) {
672 networksForUpdateDisallowedUids.add(nai);
673 }
674 }
675 }
676 for (final var pair : configs) {
677 try {
678 mNetd.networkAddUidRangesParcel(pair.second);
679 mNetd.networkRemoveUidRangesParcel(pair.first);
680 } catch (RemoteException | ServiceSpecificException e) {
681 loge("updateUidDefaultNetworkRules: Exception while updating", e);
682 }
683 }
684 for (final var nai : networksForUpdateDisallowedUids) {
685 updateDisallowedUidsForNetwork(nai);
686 }
687 }
688
689 /**
690 * Generates and stores an allowlist configuration based on the policies that apply to the
691 * given network, and sends this configuration to Netd. Uses the same methods for adding UID
692 * range-based IP rules as is used by VPNs or by restricted networks which manually specify
693 * their allowed UIDs, ensuring absent UIDs cannot be routed there. {@see updateAllowedUids}
694 */
695 private void updateAllowedUidsForNetwork(@NonNull final NetworkAgentInfo nai) {
696 if (!nai.networkInfo.isConnected()) {
697 // Network is not connected, so we cannot currently update allowed UIDs.
698 // If we try, Netd responds with: "Machine is not on the network (code 64)"
699 return;
700 }
701 final int netId = nai.network.netId;
702 final var ourTag = "updateAllowedUidsForNetwork(" + netId + "): ";
703 if (DDBG) Log.d(TAG, ourTag + "begin");
704 final var config = getAllowlistedNativeUidRangeConfigForNetwork(nai);
705 final NativeUidRangeConfig lastConfig;
706 synchronized (mNetworkForNetId) {
707 lastConfig = mNetIdToAllowlist.get(netId);
708 mNetIdToAllowlist.put(netId, config);
709 }
710 try {
711 if (config.uidRanges != null && config.uidRanges.length > 0) {
712 mNetd.networkAddUidRangesParcel(config);
713 }
714 if (lastConfig != null && lastConfig.uidRanges != null
715 && lastConfig.uidRanges.length > 0) {
716 mNetd.networkRemoveUidRangesParcel(lastConfig);
717 }
718 } catch (Exception e) {
719 loge(ourTag + "Exception encountered", e);
720 }
721 if (DDBG) Log.d(TAG, ourTag + "end");
722 }
723
724 private static final long TRANSPORT_VPN_FLAG = 1 << TRANSPORT_VPN;
725
726 /**
727 * Returns true if all of the provided transports are allowed, or if transports represent
728 * a VPN and VPNs are allowed. Otherwise, returns false.
729 */
730 private static boolean areTransportsAllowed(final long transports,
731 final long allowedTransports) {
732 // TODO: In the future, we may want to provide a way to restrict VPN access based on
733 // its other transports, e.g. to block apps from using mobile data even if that data
734 // is over a VPN. This is possible by removing or extending the check below.
735 if ((transports & TRANSPORT_VPN_FLAG) != 0) {
736 // For a VPN, all that matters is VPN access, nothing else.
737 return (allowedTransports & TRANSPORT_VPN_FLAG) != 0;
738 }
739 return (allowedTransports & transports) == transports;
740 }
741
742 /**
743 * Returns a list of UIDs that are policy-restricted based on the provided network and its
744 * capabilities. Networks that are restricted by the system choose their own allowed UIDs,
745 * so we do not disallow any UIDs for those networks.
746 */
747 private List<Integer> getUidsDisallowedByPolicyForNetwork(
748 @NonNull final NetworkAgentInfo nai) {
749 final var ourTag = "getUidsDisallowedByPolicyForNetwork(" + nai.network.netId + "): ";
750 final var uids = new ArrayList<Integer>();
751 if (!nai.networkInfo.isConnectedOrConnecting()) {
752 // Network is not connected so nothing needs to be disallowed.
753 if (DDBG) Log.d(TAG, ourTag + "not connected, so empty");
754 return uids;
755 }
756 final NetworkCapabilities nc = nai.networkCapabilities;
757 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
758 // We do not want to meddle with networks that are already considered restricted.
759 // These will have their own allowed UIDs.
760 if (DDBG) Log.d(TAG, ourTag + "restricted, so empty");
761 return uids;
762 }
763 final long packedTransports = BitUtils.packBits(nc.getTransportTypes());
764 if (packedTransports == 0L) {
765 // If we are not supplied with transports to check, nothing is allowed.
766 if (DDBG) Log.d(TAG, ourTag + "transports == 0L, so empty");
767 return uids;
768 }
769 final int size = mUidAllowedTransports.size();
770 int lastUid = 0;
771 for (int i = 0; i < size; i++) {
772 int uid = mUidAllowedTransports.keyAt(i);
773 long allowedTransports = mUidAllowedTransports.valueAt(i);
774 if (!nc.appliesToUid(uid)) continue;
775 if (!areTransportsAllowed(packedTransports, allowedTransports)) {
776 uids.add(uid);
777 }
778 }
779 return uids;
780 }
781
782 /**
783 * Returns an array of UidRangeParcel representing all possible UIDs that are not restricted
784 * by policy, based on the provided network and its capabilities.
785 */
786 private UidRangeParcel[] getUidRangeParcelsAllowedByPolicyForNetwork(
787 @NonNull final NetworkAgentInfo nai) {
788 final var uids = getUidsDisallowedByPolicyForNetwork(nai);
789 final var ranges = new ArrayList<UidRangeParcel>();
790 int lastUid = 0;
791 for (final Integer uid : uids) {
792 if (uid != lastUid) {
793 ranges.add(new UidRangeParcel(lastUid, uid - 1));
794 }
795 lastUid = uid + 1;
796 }
797 ranges.add(new UidRangeParcel(lastUid, Integer.MAX_VALUE));
798 return ranges.toArray(new UidRangeParcel[0]);
799 }
800
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900801 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900802 private final ConnectivityResources mResources;
Maciej Żenczykowskif310a142023-06-05 07:29:28 +0000803 private final int mWakeUpMark;
804 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000805 // The Context is created for UserHandle.ALL.
806 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900807 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900808 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700809 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700810 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800811
Chenbo Feng15416292018-11-08 17:36:21 -0800812 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800813 protected IDnsResolver mDnsResolver;
814 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800815 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700816 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900817 private final NetworkStatsManager mStatsManager;
818 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800819 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700820
Benedict Wong493e04b2018-11-09 14:45:34 -0800821 /**
822 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
823 * instances.
824 */
825 @GuardedBy("mTNSLock")
826 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800827 private final CompanionDeviceManagerProxyService mCdmps;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900828 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800829
830 private final Object mTNSLock = new Object();
831
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700832 private String mCurrentTcpBufferSizes;
833
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900834 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000835 new Class[] {
836 ConnectivityService.class,
837 NetworkAgent.class,
838 NetworkAgentInfo.class,
839 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900840
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500841 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400842 // Tear down networks that have no chance (e.g. even if validated) of becoming
843 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500844 // all networks have been rematched against all NetworkRequests.
845 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400846 // Don't reap networks. This should be passed when some networks have not yet been
847 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500848 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900849 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500850
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900851 private enum UnneededFor {
852 LINGER, // Determine whether this network is unneeded and should be lingered.
853 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
854 }
855
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700856 /**
paulhuaa0743d2021-05-26 21:56:03 +0800857 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800858 * should have priority. The order is passed to netd which will use it together
859 * with UID ranges to generate the corresponding IP rule. This serves to
860 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800861 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800862 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000863 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800864 *
paulhu48291862021-07-14 14:53:57 +0800865 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
866 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800867 */
paulhu48291862021-07-14 14:53:57 +0800868 // Used when sending to netd to code for "no order".
869 static final int PREFERENCE_ORDER_NONE = 0;
870 // Order for requests that don't code for a per-app preference. As it is
871 // out of the valid range, the corresponding order should be
872 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800873 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800874 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800875 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800876 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
877 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800878 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800879 static final int PREFERENCE_ORDER_OEM = 10;
880 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800881 // See {@link #setProfileNetworkPreference}.
882 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800883 static final int PREFERENCE_ORDER_PROFILE = 20;
884 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800885 // better scores are connected.
886 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800887 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800888 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Tommy Webb34f81dc2023-02-20 14:10:55 -0500889 // Lowest subpriority that still adds default network rules.
890 static final int PREFERENCE_ORDER_LOWEST_WITH_DEFAULT = 998;
Chalard Jeane6c95272022-01-25 21:04:21 +0900891 // Preference order that signifies the network shouldn't be set as a default network for
892 // the UIDs, only give them access to it. TODO : replace this with a boolean
893 // in NativeUidRangeConfig
894 @VisibleForTesting
895 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
896 // Bound for the lowest valid preference order.
897 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800898
899 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700900 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700901 * from one net to another. Clear happens when we get a new
902 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
903 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700904 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700905 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700906
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700907 /**
908 * used internally to reload global proxy settings
909 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700910 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700911
Robert Greenwalt34848c02011-03-25 13:09:25 -0700912 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400913 * PAC manager has received new port.
914 */
Aaron Huang25ef1712021-06-08 13:11:45 +0800915 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400916
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700917 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900918 * used internally when registering NetworkProviders
919 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700920 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900921 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700922
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700923 /**
924 * used internally when registering NetworkAgents
925 * obj = Messenger
926 */
927 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
928
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700929 /**
930 * used to add a network request
931 * includes a NetworkRequestInfo
932 */
933 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
934
935 /**
936 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900937 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700938 * cancel it.
939 * includes a NetworkRequestInfo
940 */
941 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
942
943 /**
944 * used to add a network listener - no request
945 * includes a NetworkRequestInfo
946 */
947 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
948
949 /**
950 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400951 * arg1 = UID of caller
952 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700953 */
954 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
955
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700956 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900957 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700958 * obj = Messenger
959 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900960 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700961
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700962 /**
963 * used internally to expire a wakelock when transitioning
964 * from one net to another. Expire happens when we fail to find
965 * a new network (typically after 1 minute) -
966 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
967 * a replacement network.
968 */
969 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
970
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700971 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800972 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400973 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800974 */
975 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
976
977 /**
978 * used to remove a pending intent and its associated network request.
979 * arg1 = UID of caller
980 * obj = PendingIntent
981 */
982 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
983
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900984 /**
985 * used to specify whether a network should be used even if unvalidated.
986 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
987 * arg2 = whether to remember this choice in the future (1 or 0)
988 * obj = network
989 */
990 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
991
992 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700993 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900994 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700995 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900996
Paul Jensenc8873fc2015-06-17 14:15:39 -0400997 /**
998 * used to add a network listener with a pending intent
999 * obj = NetworkRequestInfo
1000 */
1001 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
1002
Hugo Benichid6b510a2017-04-06 17:22:18 +09001003 /**
1004 * used to specify whether a network should not be penalized when it becomes unvalidated.
1005 */
1006 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
1007
1008 /**
Cody Kestingf1120be2020-08-03 18:01:40 -07001009 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +09001010 */
Cody Kestingf1120be2020-08-03 18:01:40 -07001011 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +09001012
Erik Kline31b4a9e2018-01-11 21:07:29 +09001013 // Handle changes in Private DNS settings.
1014 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
1015
dalyk1720e542018-03-05 12:42:22 -05001016 // Handle private DNS validation status updates.
1017 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
1018
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001019 /**
1020 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
1021 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001022 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
1023 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
1024 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001025 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001026 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001027
1028 /**
1029 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
1030 * config was resolved.
1031 * obj = PrivateDnsConfig
1032 * arg2 = netid
1033 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001034 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001035
1036 /**
1037 * Request ConnectivityService display provisioning notification.
1038 * arg1 = Whether to make the notification visible.
1039 * arg2 = NetID.
1040 * obj = Intent to be launched when notification selected by user, null if !arg1.
1041 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001042 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001043
1044 /**
lucaslin2240ef62019-03-12 13:08:03 +08001045 * Used to specify whether a network should be used even if connectivity is partial.
1046 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
1047 * false)
1048 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
1049 * obj = network
1050 */
lucaslin444d43a2020-02-20 16:56:59 +08001051 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +08001052
1053 /**
lucasline117e2e2019-10-22 18:27:33 +08001054 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
1055 * Both of the arguments are bitmasks, and the value of bits come from
1056 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09001057 * arg1 = unused
1058 * arg2 = netId
1059 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +08001060 */
lucaslin444d43a2020-02-20 16:56:59 +08001061 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +08001062
1063 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09001064 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
1065 * arg1 = unused
1066 * arg2 = netId
1067 * obj = captive portal data
1068 */
lucaslin444d43a2020-02-20 16:56:59 +08001069 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09001070
1071 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001072 * Used by setRequireVpnForUids.
1073 * arg1 = whether the specified UID ranges are required to use a VPN.
1074 * obj = Array of UidRange objects.
1075 */
1076 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
1077
1078 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001079 * Used internally when setting the default networks for OemNetworkPreferences.
1080 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -08001081 */
1082 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
1083
1084 /**
lucaslin1193a5d2021-01-21 02:04:15 +08001085 * Used to indicate the system default network becomes active.
1086 */
1087 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
1088
1089 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001090 * Used internally when setting a network preference for a user profile.
1091 * obj = Pair<ProfileNetworkPreference, Listener>
1092 */
1093 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
1094
1095 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00001096 * Event to specify that reasons for why an uid is blocked changed.
1097 * arg1 = uid
1098 * arg2 = blockedReasons
1099 */
1100 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
1101
1102 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +09001103 * Event to register a new network offer
1104 * obj = NetworkOffer
1105 */
1106 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
1107
1108 /**
1109 * Event to unregister an existing network offer
1110 * obj = INetworkOfferCallback
1111 */
1112 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
1113
1114 /**
paulhu51f77dc2021-06-07 02:34:20 +00001115 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
1116 */
1117 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
1118
1119 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08001120 * Event to set temporary allow bad wifi within a limited time to override
1121 * {@code config_networkAvoidBadWifi}.
1122 */
1123 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
1124
1125 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001126 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
1127 */
1128 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
1129
1130 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +09001131 * The initial evaluation period is over for this network.
1132 *
1133 * If no form of connectivity has been found on this network (valid, partial, captive portal)
1134 * then the stack will now consider it to have been determined bad.
1135 */
1136 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
1137
1138 /**
Hansen Kurli55396972022-10-28 03:31:17 +00001139 * Used internally when the user does not want the network from captive portal app.
1140 * obj = Network
1141 */
1142 private static final int EVENT_USER_DOES_NOT_WANT = 58;
1143
1144 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001145 * Event to set VPN as preferred network for specific apps.
1146 * obj = VpnNetworkPreferenceInfo
1147 */
1148 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
1149
1150 /**
chiachangwange0192a72023-02-06 13:25:01 +00001151 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
1152 */
1153 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
1154
1155 /**
Mark Fasheh7501e762023-05-04 20:23:11 +00001156 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
1157 */
1158 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
1159
1160 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001161 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
1162 * should be shown.
1163 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001164 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001165
1166 /**
1167 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
1168 * should be hidden.
1169 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001170 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001171
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08001172 /**
1173 * The maximum alive time to allow bad wifi configuration for testing.
1174 */
1175 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
1176
Patrick Rohr2857ac42022-01-21 14:58:16 +01001177 /**
chiachangwange0192a72023-02-06 13:25:01 +00001178 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
1179 * testing.
1180 */
1181 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
1182
1183 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001184 * The priority of the tc police rate limiter -- smaller value is higher priority.
1185 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
1186 */
1187 private static final short TC_PRIO_POLICE = 1;
1188
1189 /**
1190 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
1191 */
1192 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -07001193 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +01001194
Hugo Benichi47011212017-03-30 10:46:05 +09001195 private static String eventName(int what) {
1196 return sMagicDecoderRing.get(what, Integer.toString(what));
1197 }
1198
paulhua10d8212020-11-10 15:32:56 +08001199 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +09001200 final DnsResolverServiceManager dsm = context.getSystemService(
1201 DnsResolverServiceManager.class);
1202 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +08001203 }
1204
Cody Kesting73708bf2019-12-18 10:57:50 -08001205 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001206 @VisibleForTesting
1207 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001208 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07001209 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001210 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07001211 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -08001212 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
1213 @VisibleForTesting
1214 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
1215
Erik Kline32120082017-12-13 19:40:49 +09001216 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +09001217 @VisibleForTesting
1218 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001219
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001220 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001221 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001222
Chalard Jean46bfbf02022-02-02 00:56:25 +09001223 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001224 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001225
Chalard Jean5d70ba42018-06-07 16:44:04 +09001226 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
1227 // the world when it changes.
Aaron Huang58f949a2021-06-08 04:34:24 +08001228 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -04001229
Erik Kline05f2b402015-04-30 12:58:40 +09001230 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001231
Chalard Jean46bfbf02022-02-02 00:56:25 +09001232 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -04001233
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001234 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +09001235 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001236
Valentin Iftime9fa35092019-09-24 13:32:13 +02001237 private Set<String> mWolSupportedInterfaces;
1238
Roshan Pius08c94fb2020-01-16 12:17:17 -08001239 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08001240 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001241 private final AppOpsManager mAppOpsManager;
1242
1243 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -04001244
chiachangwang3d60bac2023-01-17 14:38:08 +00001245 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +09001246 private final QosCallbackTracker mQosCallbackTracker;
1247 private final NetworkNotificationManager mNotifier;
1248 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001249
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001250 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +08001251 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001252
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09001253 // Sequence number for NetworkProvider IDs.
1254 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
1255 NetworkProvider.FIRST_PROVIDER_ID);
1256
Erik Klineedf878b2015-07-09 18:24:03 +09001257 // NetworkRequest activity String log entries.
1258 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
1259 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
1260
Hugo Benichid159fdd2016-07-11 11:05:12 +09001261 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +09001262 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +09001263 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
1264
Hugo Benichi47011212017-03-30 10:46:05 +09001265 private static final int MAX_WAKELOCK_LOGS = 20;
1266 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +09001267 private int mTotalWakelockAcquisitions = 0;
1268 private int mTotalWakelockReleases = 0;
1269 private long mTotalWakelockDurationMs = 0;
1270 private long mMaxWakelockDurationMs = 0;
1271 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +09001272
Hugo Benichi208c0102016-07-28 17:53:06 +09001273 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +09001274
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07001275 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +09001276 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07001277
Erik Kline95ecfee2016-10-02 18:02:14 +09001278 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001279 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +09001280
Lorenzo Colitti389a8142018-01-24 17:35:07 +09001281 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -08001282 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
1283 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -08001284
Patrick Rohr2857ac42022-01-21 14:58:16 +01001285 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
1286 // configured via {@link
1287 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
1288 // Only the handler thread is allowed to access this field.
1289 private long mIngressRateLimit = -1;
1290
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001291 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
1292 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +09001293 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001294 @GuardedBy("mSelfCertifiedCapabilityCache")
1295 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
1296 mSelfCertifiedCapabilityCache = new HashMap<>();
1297
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001298 // Flag to enable the feature of closing frozen app sockets.
1299 private final boolean mDestroyFrozenSockets;
1300
1301 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
1302 private final boolean mDelayDestroyFrozenSockets;
1303
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001304 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
1305 private final boolean mAllowSysUiConnectivityReports;
1306
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001307 // Uids that ConnectivityService is pending to close sockets of.
1308 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
1309
Robert Greenwalt802c1102014-06-02 15:32:02 -07001310 /**
1311 * Implements support for the legacy "one network per network type" model.
1312 *
1313 * We used to have a static array of NetworkStateTrackers, one for each
1314 * network type, but that doesn't work any more now that we can have,
1315 * for example, more that one wifi network. This class stores all the
1316 * NetworkAgentInfo objects that support a given type, but the legacy
1317 * API will only see the first one.
1318 *
1319 * It serves two main purposes:
1320 *
1321 * 1. Provide information about "the network for a given type" (since this
1322 * API only supports one).
1323 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
1324 * the first network for a given type changes, or if the default network
1325 * changes.
1326 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001327 @VisibleForTesting
1328 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001329
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09001330 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001331 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001332
Robert Greenwalt802c1102014-06-02 15:32:02 -07001333 /**
1334 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1335 * Each list holds references to all NetworkAgentInfos that are used to
1336 * satisfy requests for that network type.
1337 *
1338 * This array is built out at startup such that an unsupported network
1339 * doesn't get an ArrayList instance, making this a tristate:
1340 * unsupported, supported but not active and active.
1341 *
1342 * The actual lists are populated when we scan the network types that
1343 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001344 *
1345 * Threading model:
1346 * - addSupportedType() is only called in the constructor
1347 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1348 * They are therefore not thread-safe with respect to each other.
1349 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1350 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001351 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001352 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001353 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001354 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001355 @NonNull
1356 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001357
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001358 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1359 // an entry have no timer (equivalent to -1). Lazily loaded.
1360 @NonNull
1361 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1362
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001363 LegacyTypeTracker(@NonNull ConnectivityService service) {
1364 mService = service;
1365 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001366 }
1367
Chiachang Wang3bc52762021-11-25 14:17:57 +08001368 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1369 // addressed.
1370 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001371 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1372 final PackageManager pm = ctx.getPackageManager();
1373 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1374 addSupportedType(TYPE_WIFI);
1375 }
1376 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1377 addSupportedType(TYPE_WIFI_P2P);
1378 }
1379 if (tm.isDataCapable()) {
1380 // Telephony does not have granular support for these types: they are either all
1381 // supported, or none is supported
1382 addSupportedType(TYPE_MOBILE);
1383 addSupportedType(TYPE_MOBILE_MMS);
1384 addSupportedType(TYPE_MOBILE_SUPL);
1385 addSupportedType(TYPE_MOBILE_DUN);
1386 addSupportedType(TYPE_MOBILE_HIPRI);
1387 addSupportedType(TYPE_MOBILE_FOTA);
1388 addSupportedType(TYPE_MOBILE_IMS);
1389 addSupportedType(TYPE_MOBILE_CBS);
1390 addSupportedType(TYPE_MOBILE_IA);
1391 addSupportedType(TYPE_MOBILE_EMERGENCY);
1392 }
1393 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1394 addSupportedType(TYPE_BLUETOOTH);
1395 }
1396 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1397 // TYPE_PROXY is only used on Wear
1398 addSupportedType(TYPE_PROXY);
1399 }
1400 // Ethernet is often not specified in the configs, although many devices can use it via
1401 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001402 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001403 addSupportedType(TYPE_ETHERNET);
1404 }
1405
1406 // Always add TYPE_VPN as a supported type
1407 addSupportedType(TYPE_VPN);
1408 }
1409
1410 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001411 if (mTypeLists[type] != null) {
1412 throw new IllegalStateException(
1413 "legacy list for type " + type + "already initialized");
1414 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001415 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001416 }
1417
Robert Greenwalt802c1102014-06-02 15:32:02 -07001418 public boolean isTypeSupported(int type) {
1419 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1420 }
1421
1422 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001423 synchronized (mTypeLists) {
1424 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1425 return mTypeLists[type].get(0);
1426 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001427 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001428 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001429 }
1430
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001431 public int getRestoreTimerForType(int type) {
1432 synchronized (mTypeLists) {
1433 if (mRestoreTimers == null) {
1434 mRestoreTimers = loadRestoreTimers();
1435 }
1436 return mRestoreTimers.getOrDefault(type, -1);
1437 }
1438 }
1439
1440 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1441 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001442 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001443 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1444 for (final String config : configs) {
1445 final String[] splits = TextUtils.split(config, ",");
1446 if (splits.length != 2) {
1447 logwtf("Invalid restore timer token count: " + config);
1448 continue;
1449 }
1450 try {
1451 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1452 } catch (NumberFormatException e) {
1453 logwtf("Invalid restore timer number format: " + config, e);
1454 }
1455 }
1456 return ret;
1457 }
1458
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001459 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001460 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001461 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001462 log("Sending " + state
1463 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001464 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001465 }
1466 }
1467
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001468 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1469 // network type, to preserve previous behaviour.
1470 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1471 if (vpnNai != mService.getLegacyLockdownNai()) return;
1472
1473 if (vpnNai.declaredUnderlyingNetworks == null
1474 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1475 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1476 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1477 return;
1478 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001479 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001480 vpnNai.declaredUnderlyingNetworks[0]);
1481 if (underlyingNai == null) return;
1482
1483 final int type = underlyingNai.networkInfo.getType();
1484 final DetailedState state = DetailedState.CONNECTED;
1485 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1486 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1487 }
1488
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001489 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001490 public void add(int type, NetworkAgentInfo nai) {
1491 if (!isTypeSupported(type)) {
1492 return; // Invalid network type.
1493 }
1494 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1495
1496 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1497 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001498 return;
1499 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001500 synchronized (mTypeLists) {
1501 list.add(nai);
1502 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001503
Chalard Jean5b409c72021-02-04 13:12:59 +09001504 // Send a broadcast if this is the first network of its type or if it's the default.
1505 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001506
1507 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1508 // to preserve previous behaviour.
1509 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001510 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001511 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1512 mService.sendLegacyNetworkBroadcast(nai, state, type);
1513 }
1514
1515 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1516 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001517 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001518 }
1519
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001520 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001521 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001522 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1523 if (list == null || list.isEmpty()) {
1524 return;
1525 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001526 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001527
Hugo Benichi389633f2016-06-21 09:48:07 +09001528 synchronized (mTypeLists) {
1529 if (!list.remove(nai)) {
1530 return;
1531 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001532 }
1533
Lorenzo Colitti49767722015-05-01 00:30:10 +09001534 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001535 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1536 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001537 }
1538
1539 if (!list.isEmpty() && wasFirstNetwork) {
1540 if (DBG) log("Other network available for type " + type +
1541 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001542 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001543 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001544 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001545 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001546 }
1547 }
1548
1549 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001550 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1551 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001552 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001553 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001554 }
1555 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001556
Chalard Jean46bfbf02022-02-02 00:56:25 +09001557 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001558 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001559 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001560 final DetailedState state = nai.networkInfo.getDetailedState();
1561 for (int type = 0; type < mTypeLists.length; type++) {
1562 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001563 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001564 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001565 if (isFirst || contains && isDefault) {
1566 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001567 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001568 }
1569 }
1570 }
1571
Robert Greenwalt94e22142014-07-30 16:31:24 -07001572 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001573 pw.println("mLegacyTypeTracker:");
1574 pw.increaseIndent();
1575 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001576 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001577 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001578 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001579 pw.println();
1580 pw.println("Current state:");
1581 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001582 synchronized (mTypeLists) {
1583 for (int type = 0; type < mTypeLists.length; type++) {
1584 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1585 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001586 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001587 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001588 }
1589 }
1590 pw.decreaseIndent();
1591 pw.decreaseIndent();
1592 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001593 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001594 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001595 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001596
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001597 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001598 /**
1599 * Helper class which parses out priority arguments and dumps sections according to their
1600 * priority. If priority arguments are omitted, function calls the legacy dump command.
1601 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001602 private class LocalPriorityDump {
1603 private static final String PRIORITY_ARG = "--dump-priority";
1604 private static final String PRIORITY_ARG_HIGH = "HIGH";
1605 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001606 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001607
1608 LocalPriorityDump() {}
1609
1610 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Laif8dba342023-10-12 17:01:03 +08001611 if (!HandlerUtils.runWithScissors(mHandler, () -> {
1612 doDump(fd, pw, new String[]{DIAG_ARG});
1613 doDump(fd, pw, new String[]{SHORT_ARG});
1614 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1615 pw.println("dumpHigh timeout");
1616 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001617 }
1618
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001619 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Laif8dba342023-10-12 17:01:03 +08001620 if (!HandlerUtils.runWithScissors(mHandler, () -> doDump(fd, pw, args),
1621 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1622 pw.println("dumpNormal timeout");
1623 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001624 }
1625
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001626 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1627 if (args == null) {
1628 dumpNormal(fd, pw, args);
1629 return;
1630 }
1631
1632 String priority = null;
1633 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1634 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1635 argIndex++;
1636 priority = args[argIndex];
1637 }
1638 }
1639
1640 if (PRIORITY_ARG_HIGH.equals(priority)) {
1641 dumpHigh(fd, pw);
1642 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1643 dumpNormal(fd, pw, args);
1644 } else {
1645 // ConnectivityService publishes binder service using publishBinderService() with
1646 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001647 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1648 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001649 // TODO: Integrate into signal dump.
1650 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001651 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001652 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001653 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001654
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001655 /**
1656 * Dependencies of ConnectivityService, for injection in tests.
1657 */
1658 @VisibleForTesting
1659 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001660 public int getCallingUid() {
1661 return Binder.getCallingUid();
1662 }
1663
Chalard Jean03552c42023-05-29 17:02:43 +09001664 public boolean isAtLeastS() {
1665 return SdkLevel.isAtLeastS();
1666 }
1667
1668 public boolean isAtLeastT() {
1669 return SdkLevel.isAtLeastT();
1670 }
1671
1672 public boolean isAtLeastU() {
1673 return SdkLevel.isAtLeastU();
1674 }
1675
Chalard Jeaneb663892023-10-07 15:17:07 +09001676 public boolean isAtLeastV() {
1677 return SdkLevel.isAtLeastV();
1678 }
1679
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001680 /**
1681 * Get system properties to use in ConnectivityService.
1682 */
1683 public MockableSystemProperties getSystemProperties() {
1684 return new MockableSystemProperties();
1685 }
1686
1687 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001688 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1689 */
1690 public ConnectivityResources getResources(@NonNull Context ctx) {
1691 return new ConnectivityResources(ctx);
1692 }
1693
1694 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001695 * Create a HandlerThread to use in ConnectivityService.
1696 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001697 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1698 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001699 }
1700
1701 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001702 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001703 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001704 public NetworkStackClientBase getNetworkStack() {
1705 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001706 }
1707
1708 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001709 * @see ProxyTracker
1710 */
1711 public ProxyTracker makeProxyTracker(@NonNull Context context,
1712 @NonNull Handler connServiceHandler) {
Aaron Huang25ef1712021-06-08 13:11:45 +08001713 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001714 }
1715
1716 /**
1717 * @see NetIdManager
1718 */
1719 public NetIdManager makeNetIdManager() {
1720 return new NetIdManager();
1721 }
1722
1723 /**
1724 * @see NetworkUtils#queryUserAccess(int, int)
1725 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001726 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1727 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001728 }
1729
1730 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001731 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1732 * requires CAP_NET_ADMIN, which the unit tests do not have.
1733 */
1734 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1735 InetSocketAddress remote) {
1736 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1737 }
1738
1739 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001740 * @see MultinetworkPolicyTracker
1741 */
1742 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1743 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1744 return new MultinetworkPolicyTracker(c, h, r);
1745 }
1746
Aaron Huang330a4c02020-10-27 03:36:19 +08001747 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001748 * @see AutomaticOnOffKeepaliveTracker
1749 */
1750 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1751 @NonNull Context c, @NonNull Handler h) {
1752 return new AutomaticOnOffKeepaliveTracker(c, h);
1753 }
1754
1755 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001756 * @see BatteryStatsManager
1757 */
1758 public void reportNetworkInterfaceForTransports(Context context, String iface,
1759 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001760 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001761 context.getSystemService(BatteryStatsManager.class);
1762 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1763 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001764
1765 public boolean getCellular464XlatEnabled() {
1766 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1767 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001768
1769 /**
1770 * @see PendingIntent#intentFilterEquals
1771 */
1772 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1773 return a.intentFilterEquals(b);
1774 }
1775
1776 /**
1777 * @see LocationPermissionChecker
1778 */
1779 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1780 return new LocationPermissionChecker(context);
1781 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001782
1783 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001784 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001785 *
1786 * This method returns null in versions before T, where carrier privilege
1787 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001788 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001789 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001790 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1791 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jean03552c42023-05-29 17:02:43 +09001792 if (isAtLeastT()) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09001793 return new CarrierPrivilegeAuthenticator(context, tm);
1794 } else {
1795 return null;
1796 }
1797 }
1798
1799 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001800 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001801 */
Motomu Utsumi6f4d8062023-04-21 12:35:22 +09001802 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001803 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001804 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001805
1806 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001807 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1808 */
1809 public boolean isFeatureNotChickenedOut(Context context, String name) {
1810 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
Chalard Jean0a2a2002019-11-29 16:41:50 +09001811 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001812
1813 /**
1814 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001815 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001816 * @return BpfNetMaps implementation.
1817 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001818 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1819 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001820 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001821
1822 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001823 * @see ClatCoordinator
1824 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001825 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001826 public ClatCoordinator getClatCoordinator(INetd netd) {
1827 return new ClatCoordinator(
1828 new ClatCoordinator.Dependencies() {
1829 @NonNull
1830 public INetd getNetd() {
1831 return netd;
1832 }
1833 });
1834 }
1835
1836 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001837 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1838 */
1839 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1840 final InterfaceParams params = InterfaceParams.getByName(iface);
1841 if (params == null) {
1842 // the interface might have disappeared.
1843 logw("Failed to get interface params for interface " + iface);
1844 return;
1845 }
1846 try {
1847 // converting rateInBytesPerSecond from long to int is safe here because the
1848 // setting's range is limited to INT_MAX.
1849 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001850 Log.i(TAG,
1851 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001852 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1853 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1854 } catch (IOException e) {
1855 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1856 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1857 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1858 + ") failure: ", e);
1859 }
1860 }
1861
1862 /**
1863 * Wraps {@link TcUtils#tcFilterDelDev}
1864 */
1865 public void disableIngressRateLimit(String iface) {
1866 final InterfaceParams params = InterfaceParams.getByName(iface);
1867 if (params == null) {
1868 // the interface might have disappeared.
1869 logw("Failed to get interface params for interface " + iface);
1870 return;
1871 }
1872 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001873 Log.i(TAG,
1874 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001875 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1876 } catch (IOException e) {
1877 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1878 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1879 }
1880 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001881
1882 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001883 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1884 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001885 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001886 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001887 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001888 }
1889
1890 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001891 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1892 */
1893 // TODO: when available in all active branches:
1894 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1895 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1896 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1897 return BroadcastOptionsShimImpl.newInstance(options);
1898 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001899
1900 /**
1901 * Wrapper method for
1902 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1903 *
1904 * @param changeId The ID of the compatibility change in question.
1905 * @param packageName The package name of the app in question.
1906 * @param user The user that the operation is done for.
1907 * @return {@code true} if the change is enabled for the specified package.
1908 */
1909 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1910 @NonNull final UserHandle user) {
1911 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1912 }
Motomu Utsumia20f7602023-03-16 17:04:21 +09001913
1914 /**
Chalard Jean03552c42023-05-29 17:02:43 +09001915 * As above but with a UID.
1916 * @see CompatChanges#isChangeEnabled(long, int)
1917 */
1918 public boolean isChangeEnabled(final long changeId, final int uid) {
1919 return CompatChanges.isChangeEnabled(changeId, uid);
1920 }
1921
1922 /**
Motomu Utsumia20f7602023-03-16 17:04:21 +09001923 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1924 *
1925 * @param ranges target uid ranges
1926 * @param exemptUids uids to skip close socket
1927 */
1928 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1929 @NonNull final Set<Integer> exemptUids)
1930 throws SocketException, InterruptedIOException, ErrnoException {
1931 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1932 }
Motomu Utsumied1848c2023-03-28 18:08:12 +09001933
1934 /**
1935 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1936 *
1937 * @param ownerUids target uids to close sockets
1938 */
1939 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1940 throws SocketException, InterruptedIOException, ErrnoException {
1941 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1942 }
Chalard Jean1f2b50f2023-05-15 17:26:13 +09001943
1944 /**
1945 * Schedule the evaluation timeout.
1946 *
1947 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1948 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1949 * of these events happen, this time will run out, after which the network is considered
1950 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1951 * on this network and considers it won't provide connectivity. In particular, that means
1952 * it's when the system prefers it to cell if it's wifi and configuration says it should
1953 * prefer bad wifi to cell.
1954 */
1955 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1956 @NonNull final Network network, final long delayMs) {
1957 handler.sendMessageDelayed(
1958 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1959 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001960 }
1961
junyulaie7c7d2a2021-01-26 15:29:15 +08001962 public ConnectivityService(Context context) {
1963 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001964 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1965 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001966 }
1967
1968 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001969 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1970 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001971 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001972
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001973 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001974 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001975 mSystemProperties = mDeps.getSystemProperties();
1976 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001977 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001978 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001979 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1980 // Pass limit - 1 to maintain backward compatibility.
1981 // TODO: Remove the workaround.
1982 mNetworkRequestCounter =
1983 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1984 mSystemNetworkRequestCounter =
1985 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001986
Hugo Benichi208c0102016-07-28 17:53:06 +09001987 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001988 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1989 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001990 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001991 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001992 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001993 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1994 mDefaultNetworkRequests.add(mDefaultRequest);
1995 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001996
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001997 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001998 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001999
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002000 // The default WiFi request is a background request so that apps using WiFi are
2001 // migrated to a better network (typically ethernet) when one comes up, instead
2002 // of staying on WiFi forever.
2003 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
2004 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
2005
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002006 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
2007 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
2008 NetworkRequest.Type.BACKGROUND_REQUEST);
2009
Chalard Jean0702f982021-09-16 21:50:07 +09002010 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
2011 // TODO: Consider making the timer customizable.
2012 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
2013 mCellularRadioTimesharingCapable =
2014 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
2015
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00002016 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
2017 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
2018
2019 if (SdkLevel.isAtLeastU()) {
2020 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
2021 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
2022 final int defaultUMarkMask = 0x80000000; // u32
2023
2024 if ((mark == 0) || (mask == 0)) {
2025 // simply treat unset/disabled as the default U value
2026 mark = defaultUMarkMask;
2027 mask = defaultUMarkMask;
2028 }
2029 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
2030 // invalid device overlay settings
2031 throw new IllegalArgumentException(
2032 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
2033 }
2034 }
2035
2036 mWakeUpMark = mark;
2037 mWakeUpMask = mask;
2038
Paul Hu51f816b2022-08-11 14:43:47 +00002039 mNetd = netd;
2040 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Chalard Jean96ff9542023-11-02 14:24:47 +09002041 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Paul Hu51f816b2022-08-11 14:43:47 +00002042 mPermissionMonitor =
2043 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09002044 mHandlerThread.start();
2045 mHandler = new InternalHandler(mHandlerThread.getLooper());
2046 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08002047 mConnectivityDiagnosticsHandler =
2048 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07002049
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08002050 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08002051 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08002052
junyulaie7c7d2a2021-01-26 15:29:15 +08002053 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08002054 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00002055 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09002056 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09002057
Wink Saville32506bc2013-06-29 21:10:57 -07002058 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002059 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09002060 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09002061 mCarrierPrivilegeAuthenticator =
2062 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002063
Tommy Webb34f81dc2023-02-20 14:10:55 -05002064 // Enable the OEM denylist chain. {@see mNetIdToDisallowedUids}
2065 try {
2066 mBpfNetMaps.setChildChain(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1, true);
2067 } catch (ServiceSpecificException e) {
2068 logwtf("Could not enable fw_oem_deny_1 chain", e);
2069 }
2070
Sudheer Shanka9967d462021-03-18 19:09:25 +00002071 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08002072 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
2073 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00002074 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002075
2076 final PowerManager powerManager = (PowerManager) context.getSystemService(
2077 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002078 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08002079 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002080
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002081 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
2082 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002083 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002084 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002085 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002086 mProtectedNetworks.add(p);
2087 } else {
2088 if (DBG) loge("Ignoring protectedNetwork " + p);
2089 }
2090 }
2091
soma, kawata29444ae2019-05-23 09:30:40 +09002092 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
2093
James Mattis02220e22021-03-13 19:27:21 -08002094 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09002095 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08002096 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08002097 final IntentFilter userIntentFilter = new IntentFilter();
2098 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
2099 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
2100 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
2101 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08002102
James Mattis02220e22021-03-13 19:27:21 -08002103 // Listen to package add/removes for netd
2104 final IntentFilter packageIntentFilter = new IntentFilter();
2105 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
2106 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2107 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
2108 packageIntentFilter.addDataScheme("package");
2109 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09002110 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08002111
Junyu Lai38c75032023-12-04 07:52:19 +00002112 // This is needed for pre-V devices to propagate the data saver status
2113 // to the BPF map. This isn't supported before Android T because BPF maps are
2114 // unsupported, and it's also unnecessary on Android V and later versions,
2115 // as the platform code handles data saver bit updates. Additionally, checking
2116 // the initial data saver status here is superfluous because the intent won't
2117 // be sent until the system is ready.
2118 if (mDeps.isAtLeastT() && !mDeps.isAtLeastV()) {
2119 final IntentFilter dataSaverIntentFilter =
2120 new IntentFilter(ACTION_RESTRICT_BACKGROUND_CHANGED);
2121 mUserAllContext.registerReceiver(mDataSaverReceiver, dataSaverIntentFilter,
2122 null /* broadcastPermission */, mHandler);
2123 }
2124
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09002125 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
2126 // But reading the trunk stable flags from mainline modules is not supported yet.
2127 // So enabling this feature on V+ release.
2128 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
2129 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
2130 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07002131
Chalard Jean46bfbf02022-02-02 00:56:25 +09002132 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08002133 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002134 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08002135 } catch (RemoteException | ServiceSpecificException e) {
2136 loge("Error registering event listener :" + e);
2137 }
2138
Erik Kline05f2b402015-04-30 12:58:40 +09002139 mSettingsObserver = new SettingsObserver(mContext, mHandler);
2140 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002141
chiachangwang7c17c282023-02-02 05:58:59 +00002142 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08002143 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07002144 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09002145
2146 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08002147 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09002148 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
2149 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08002150 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09002151 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
2152 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09002153
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09002154 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09002155 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09002156 mNetworkRanker =
2157 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
2158
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09002159 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09002160
Chiachang Wangc1215d32020-10-20 15:38:58 +08002161 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002162 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08002163
Chalard Jean28018572020-12-21 18:36:52 +09002164 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
2165 // request that doesn't allow fallback to the default network. It should never be visible
2166 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
2167 // arguments like the handler or the DnsResolver.
2168 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08002169 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08002170 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08002171 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09002172 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09002173 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09002174 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
2175 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07002176
2177 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09002178 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
2179 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
2180 // Even if it could, running on S would at least require mocking out the BPF map,
2181 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
2182 // the bpf syscall. http://aosp/1907693
Chalard Jean03552c42023-05-29 17:02:43 +09002183 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09002184 mDscpPolicyTracker = new DscpPolicyTracker();
2185 }
Tyler Wear72388212021-09-09 14:49:02 -07002186 } catch (ErrnoException e) {
2187 loge("Unable to create DscpPolicyTracker");
2188 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01002189
2190 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
2191 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08002192
Chalard Jean03552c42023-05-29 17:02:43 +09002193 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08002194 mCdmps = new CompanionDeviceManagerProxyService(context);
2195 } else {
2196 mCdmps = null;
2197 }
Mark Fasheh7501e762023-05-04 20:23:11 +00002198
Chalard Jean2fb66f12023-08-25 12:50:37 +09002199 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
2200
Motomu Utsumi188bfd32023-05-30 14:38:04 +09002201 mDestroyFrozenSockets = mDeps.isAtLeastU()
2202 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
2203 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
2204 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09002205 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
2206 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09002207 if (mDestroyFrozenSockets) {
Mark Fasheh7501e762023-05-04 20:23:11 +00002208 final UidFrozenStateChangedCallback frozenStateChangedCallback =
2209 new UidFrozenStateChangedCallback() {
2210 @Override
2211 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
2212 if (uids.length != frozenStates.length) {
2213 Log.wtf(TAG, "uids has length " + uids.length
2214 + " but frozenStates has length " + frozenStates.length);
2215 return;
2216 }
2217
2218 final UidFrozenStateChangedArgs args =
2219 new UidFrozenStateChangedArgs(uids, frozenStates);
2220
2221 mHandler.sendMessage(
2222 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
2223 }
2224 };
2225
2226 final ActivityManager activityManager =
2227 mContext.getSystemService(ActivityManager.class);
2228 activityManager.registerUidFrozenStateChangedCallback(
2229 (Runnable r) -> r.run(), frozenStateChangedCallback);
2230 }
Yuyang Huang41557552023-11-28 12:47:22 +09002231
2232 if (mDeps.isFeatureNotChickenedOut(mContext, LOG_BPF_RC)) {
2233 mHandler.post(BpfLoaderRcUtils::checkBpfLoaderRc);
2234 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002235 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002236
Xiao Ma0a171c02022-01-23 16:14:51 +00002237 /**
2238 * Check whether or not the device supports Ethernet transport.
2239 */
2240 public static boolean deviceSupportsEthernet(final Context context) {
2241 final PackageManager pm = context.getPackageManager();
2242 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
2243 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
2244 }
2245
Chalard Jean46adcf32018-04-18 20:18:38 +09002246 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002247 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
2248 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09002249 }
2250
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002251 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
2252 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09002253 final NetworkCapabilities netCap = new NetworkCapabilities();
2254 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002255 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09002256 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002257 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09002258 return netCap;
2259 }
2260
James Mattis45d81842021-01-10 14:24:24 -08002261 private NetworkRequest createDefaultRequest() {
2262 return createDefaultInternetRequestForTransport(
2263 TYPE_NONE, NetworkRequest.Type.REQUEST);
2264 }
2265
lucaslin3ba7cc22022-12-19 02:35:33 +00002266 private NetworkRequest createVpnRequest() {
2267 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
2268 .withoutDefaultCapabilities()
2269 .addTransportType(TRANSPORT_VPN)
2270 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
2271 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
2272 .build();
2273 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2274 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
2275 }
2276
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09002277 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002278 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09002279 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09002280 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002281 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08002282 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08002283 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09002284 netCap.addTransportType(transportType);
2285 }
James Mattis45d81842021-01-10 14:24:24 -08002286 return createNetworkRequest(type, netCap);
2287 }
2288
2289 private NetworkRequest createNetworkRequest(
2290 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002291 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09002292 }
2293
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002294 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
2295 NetworkRequest.Type type) {
2296 final NetworkCapabilities netCap = new NetworkCapabilities();
2297 netCap.clearAll();
2298 netCap.addCapability(capability);
2299 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2300 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
2301 }
2302
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002303 // Used only for testing.
2304 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07002305 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002306 // changing ContentResolver to make registerContentObserver non-final).
2307 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
2308 // by subclassing SettingsObserver.
2309 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002310 void updateAlwaysOnNetworks() {
2311 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002312 }
2313
Erik Kline9a62f012018-03-21 07:18:33 -07002314 // See FakeSettingsProvider comment above.
2315 @VisibleForTesting
2316 void updatePrivateDnsSettings() {
2317 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
2318 }
2319
paulhu51f77dc2021-06-07 02:34:20 +00002320 @VisibleForTesting
2321 void updateMobileDataPreferredUids() {
2322 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
2323 }
2324
Patrick Rohr2857ac42022-01-21 14:58:16 +01002325 @VisibleForTesting
2326 void updateIngressRateLimit() {
2327 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
2328 }
2329
Aaron Huang58f949a2021-06-08 04:34:24 +08002330 @VisibleForTesting
2331 void simulateUpdateProxyInfo(@Nullable final Network network,
2332 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang25ef1712021-06-08 13:11:45 +08002333 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang58f949a2021-06-08 04:34:24 +08002334 new Pair<>(network, proxyInfo)).sendToTarget();
2335 }
2336
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002337 private void handleAlwaysOnNetworkRequest(
2338 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002339 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002340 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002341 handleAlwaysOnNetworkRequest(networkRequest, enable);
2342 }
2343
2344 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002345 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002346 if (enable == isEnabled) {
2347 return; // Nothing to do.
2348 }
2349
2350 if (enable) {
2351 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002352 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002353 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002354 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002355 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002356 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2357 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002358 }
2359 }
2360
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002361 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002362 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2363 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2364 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2365 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002366 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2367 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002368 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002369 }
2370
paulhu51f77dc2021-06-07 02:34:20 +00002371 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002372 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002373 private void registerSettingsCallbacks() {
2374 // Watch for global HTTP proxy changes.
2375 mSettingsObserver.observe(
2376 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2377 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2378
Chalard Jean46bfbf02022-02-02 00:56:25 +09002379 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002380 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002381 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002382 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2383
Chalard Jean46bfbf02022-02-02 00:56:25 +09002384 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002385 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002386 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002387 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002388
2389 // Watch for mobile data preferred uids changes.
2390 mSettingsObserver.observe(
2391 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2392 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002393
2394 // Watch for ingress rate limit changes.
2395 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002396 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002397 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2398 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002399 }
2400
Erik Kline31b4a9e2018-01-11 21:07:29 +09002401 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002402 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2403 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002404 }
2405 }
2406
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002407 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002408 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2409 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002410 return mNextNetworkRequestId++;
2411 }
2412
junyulai74f9a8b2018-06-13 15:00:37 +08002413 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002414 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002415 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002416 if (network == null) {
2417 return null;
2418 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002419 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002420 }
2421
2422 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002423 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002424 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002425 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002426 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002427
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002428 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002429 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002430 private NetworkAgentInfo getVpnForUid(int uid) {
2431 synchronized (mNetworkForNetId) {
2432 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2433 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002434 if (nai.isVPN() && nai.everConnected()
2435 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002436 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002437 }
2438 }
2439 }
2440 return null;
2441 }
2442
Chalard Jean46bfbf02022-02-02 00:56:25 +09002443 @Nullable
Tommy Webb34f81dc2023-02-20 14:10:55 -05002444 private NetworkAgentInfo getConnectedOrConnectingVpnForUid(int uid) {
2445 synchronized (mNetworkForNetId) {
2446 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2447 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
2448 if (nai.isVPN()
2449 && (nai.everConnected() || nai.networkInfo.isConnectedOrConnecting())
2450 && nai.networkCapabilities.appliesToUid(uid)) {
2451 return nai;
2452 }
2453 }
2454 }
2455 return null;
2456 }
2457
2458 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002459 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002460 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002461 final NetworkAgentInfo nai = getVpnForUid(uid);
2462 if (nai != null) return nai.declaredUnderlyingNetworks;
2463 return null;
2464 }
2465
Lorenzo Colittia7574052021-01-19 01:33:05 +09002466 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002467 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002468
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002469 final Network[] networks = getVpnUnderlyingNetworks(uid);
2470 if (networks != null) {
2471 // getUnderlyingNetworks() returns:
2472 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2473 // empty array => the VPN explicitly said "no default network".
2474 // non-empty array => the VPN specified one or more default networks; we use the
2475 // first one.
2476 if (networks.length > 0) {
2477 nai = getNetworkAgentInfoForNetwork(networks[0]);
2478 } else {
2479 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002480 }
2481 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002482 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002483 }
2484
2485 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002486 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002487 */
paulhu7aeba372020-12-30 00:42:19 +08002488 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2489 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002490 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002491 if (ignoreBlocked) {
2492 return false;
2493 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05002494 if (isUidCurrentlyDisallowedByPolicy(uid)) return true;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002495 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002496 final long ident = Binder.clearCallingIdentity();
2497 try {
2498 final boolean metered = nc == null ? true : nc.isMetered();
2499 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2500 } finally {
2501 Binder.restoreCallingIdentity(ident);
2502 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002503 }
2504
Tommy Webb34f81dc2023-02-20 14:10:55 -05002505 /** Check if UID is currently disallowed general network access based on policies. */
2506 private boolean isUidCurrentlyDisallowedByPolicy(int uid) {
2507 return mLastDisallowedUidsDenylist.contains(uid);
2508 }
2509
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002510 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002511 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2512 return;
2513 }
Hugo Benichi47011212017-03-30 10:46:05 +09002514 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002515 synchronized (mBlockedAppUids) {
2516 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002517 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002518 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002519 blocked = false;
2520 } else {
2521 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002522 }
2523 }
Hugo Benichi47011212017-03-30 10:46:05 +09002524 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2525 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2526 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002527 }
2528
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002529 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002530 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2531 return;
2532 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002533 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002534 final int requestId = nri.getActiveRequest() != null
2535 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002536 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002537 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002538 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002539 }
2540
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002541 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002542 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002543 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002544 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002545 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002546 @NonNull
2547 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2548 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002549 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2550 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2551 // but only exists if an app asks about them or requests them. Ensure the requesting app
2552 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002553 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002554 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2555 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2556 null /* extraInfo */);
2557 }
2558 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002559 return filtered;
2560 }
2561
2562 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2563 boolean ignoreBlocked) {
2564 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2565 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002566 }
2567
2568 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002569 * Return NetworkInfo for the active (i.e., connected) network interface.
2570 * It is assumed that at most one network is active at a time. If more
2571 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002572 * @return the info for the active network, or {@code null} if none is
2573 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002574 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002575 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002576 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002577 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002578 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002579 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002580 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2581 if (nai == null) return null;
2582 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2583 maybeLogBlockedNetworkInfo(networkInfo, uid);
2584 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002585 }
2586
Paul Jensen1f567382015-02-13 14:18:39 -05002587 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002588 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002589 public Network getActiveNetwork() {
2590 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002591 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002592 }
2593
2594 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002595 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002596 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002597 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002598 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002599 }
2600
Chalard Jean46bfbf02022-02-02 00:56:25 +09002601 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002602 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Tommy Webb34f81dc2023-02-20 14:10:55 -05002603 return getActiveNetworkForUidInternal(getVpnForUid(uid), uid, ignoreBlocked);
2604 }
2605
2606 private Network getActiveNetworkOrConnectingVpnForUidInternal(final int uid,
2607 boolean ignoreBlocked) {
2608 return getActiveNetworkForUidInternal(
2609 getConnectedOrConnectingVpnForUid(uid), uid, ignoreBlocked);
2610 }
2611
2612 private Network getActiveNetworkForUidInternal(final NetworkAgentInfo vpnNai,
2613 final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002614 if (vpnNai != null) {
2615 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2616 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2617 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002618 }
Paul Jensen1f567382015-02-13 14:18:39 -05002619 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002620
James Mattis2516da32021-01-31 17:06:19 -08002621 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002622 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2623 ignoreBlocked)) {
2624 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002625 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002626 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002627 }
2628
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002629 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002630 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002631 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002632 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002633 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2634 if (nai == null) return null;
2635 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002636 }
2637
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002638 /** Returns a NetworkInfo object for a network that doesn't exist. */
2639 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2640 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2641 getNetworkTypeName(networkType), "" /* subtypeName */);
2642 info.setIsAvailable(true);
2643 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2644 // background data is restricted.
2645 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2646 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2647 ? DetailedState.BLOCKED
2648 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002649 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2650 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002651 return info;
2652 }
2653
Lorenzo Colittia7574052021-01-19 01:33:05 +09002654 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002655 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2656 return null;
2657 }
2658 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002659 if (nai == null) {
2660 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002661 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002662 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2663 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002664 }
2665
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002666 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002667 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002668 public NetworkInfo getNetworkInfo(int networkType) {
2669 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002670 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002671 if (getVpnUnderlyingNetworks(uid) != null) {
2672 // A VPN is active, so we may need to return one of its underlying networks. This
2673 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002674 // getNetworkAgentInfoForUid.
2675 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2676 if (nai == null) return null;
2677 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2678 if (networkInfo.getType() == networkType) {
2679 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002680 }
2681 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002682 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002683 }
2684
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002685 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002686 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002687 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002688 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002689 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002690 if (nai == null) return null;
2691 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002692 }
2693
2694 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002695 public NetworkInfo[] getAllNetworkInfo() {
2696 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002697 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002698 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2699 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002700 NetworkInfo info = getNetworkInfo(networkType);
2701 if (info != null) {
2702 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002703 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002704 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002705 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002706 }
2707
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002708 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002709 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002710 public Network getNetworkForType(int networkType) {
2711 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002712 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2713 return null;
2714 }
2715 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2716 if (nai == null) {
2717 return null;
2718 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002719 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002720 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2721 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002722 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002723 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002724 }
2725
2726 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002727 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002728 public Network[] getAllNetworks() {
2729 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002730 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002731 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002732 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002733 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002734 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002735 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002736 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002737 }
2738
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002739 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002740 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002741 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002742 // The basic principle is: if an app's traffic could possibly go over a
2743 // network, without the app doing anything multinetwork-specific,
2744 // (hence, by "default"), then include that network's capabilities in
2745 // the array.
2746 //
2747 // In the normal case, app traffic only goes over the system's default
2748 // network connection, so that's the only network returned.
2749 //
2750 // With a VPN in force, some app traffic may go into the VPN, and thus
2751 // over whatever underlying networks the VPN specifies, while other app
2752 // traffic may go over the system default network (e.g.: a split-tunnel
2753 // VPN, or an app disallowed by the VPN), so the set of networks
2754 // returned includes the VPN's underlying networks and the system
2755 // default.
2756 enforceAccessPermission();
2757
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002758 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002759
James Mattis2516da32021-01-31 17:06:19 -08002760 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2761 if (!nri.isBeingSatisfied()) {
2762 continue;
2763 }
2764 final NetworkAgentInfo nai = nri.getSatisfier();
2765 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2766 if (null != nc
2767 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2768 && !result.containsKey(nai.network)) {
2769 result.put(
2770 nai.network,
2771 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002772 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002773 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2774 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002775 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002776 }
2777
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002778 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002779 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002780 if (null != networks) {
2781 for (final Network network : networks) {
2782 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2783 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002784 result.put(
2785 network,
2786 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002787 nc,
2788 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002789 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002790 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002791 }
2792 }
2793 }
2794
2795 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2796 out = result.values().toArray(out);
2797 return out;
2798 }
2799
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002800 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2801 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2802 // can call sampleConnectivityState and make the checks on it.
2803 @NonNull
2804 private StatsEvent sampleConnectivityStateToStatsEvent() {
2805 final ConnectivityStateSample sample = sampleConnectivityState();
2806 return ConnectivityStatsLog.buildStatsEvent(
2807 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2808 sample.getNetworkCountPerTransports().toByteArray(),
2809 sample.getConnectionDurationPerTransports().toByteArray(),
2810 sample.getNetworkRequestCount().toByteArray(),
2811 sample.getNetworks().toByteArray());
2812 }
2813
2814 /**
2815 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2816 *
2817 * This is used for metrics. These snapshots will be sampled and constitute a base for
2818 * statistics about connectivity state of devices.
2819 */
2820 @VisibleForTesting
2821 @NonNull
2822 public ConnectivityStateSample sampleConnectivityState() {
2823 ensureRunningOnConnectivityServiceThread();
2824 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2825 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2826 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2827 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2828 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2829 return builder.build();
2830 }
2831
2832 private static NetworkCountPerTransports sampleNetworkCount(
2833 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2834 final SparseIntArray countPerTransports = new SparseIntArray();
2835 for (final NetworkAgentInfo nai : nais) {
2836 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2837 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2838 }
2839 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2840 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2841 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2842 c.setTransportTypes(countPerTransports.keyAt(i));
2843 c.setNetworkCount(countPerTransports.valueAt(i));
2844 builder.addNetworkCountForTransports(c);
2845 }
2846 return builder.build();
2847 }
2848
2849 private static ConnectionDurationPerTransports sampleConnectionDuration(
2850 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2851 final ConnectionDurationPerTransports.Builder builder =
2852 ConnectionDurationPerTransports.newBuilder();
2853 for (final NetworkAgentInfo nai : nais) {
2854 final ConnectionDurationForTransports.Builder c =
2855 ConnectionDurationForTransports.newBuilder();
2856 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2857 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2858 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2859 // Add millisPerSecond/2 to round up or down to the nearest value
2860 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2861 builder.addConnectionDurationForTransports(c);
2862 }
2863 return builder.build();
2864 }
2865
2866 private static NetworkRequestCount sampleNetworkRequestCount(
2867 @NonNull final Collection<NetworkRequestInfo> nris) {
2868 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2869 final SparseIntArray countPerType = new SparseIntArray();
2870 for (final NetworkRequestInfo nri : nris) {
2871 final int type;
2872 if (Process.SYSTEM_UID == nri.mAsUid) {
2873 // The request is filed "as" the system, so it's the system on its own behalf.
2874 type = RequestType.RT_SYSTEM.getNumber();
2875 } else if (Process.SYSTEM_UID == nri.mUid) {
2876 // The request is filed by the system as some other app, so it's the system on
2877 // behalf of an app.
2878 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2879 } else {
2880 // Not the system, so it's an app requesting on its own behalf.
2881 type = RequestType.RT_APP.getNumber();
2882 }
2883 countPerType.put(type, countPerType.get(type, 0));
2884 }
2885 for (int i = countPerType.size() - 1; i >= 0; --i) {
2886 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2887 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2888 r.setRequestCount(countPerType.valueAt(i));
2889 builder.addRequestCountForType(r);
2890 }
2891 return builder.build();
2892 }
2893
2894 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2895 final NetworkList.Builder builder = NetworkList.newBuilder();
2896 for (final NetworkAgentInfo nai : nais) {
2897 final NetworkCapabilities nc = nai.networkCapabilities;
2898 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2899 d.setTransportTypes((int) nc.getTransportTypesInternal());
2900 final MeteredState meteredState;
2901 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2902 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2903 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2904 meteredState = MeteredState.METERED_NO;
2905 } else {
2906 meteredState = MeteredState.METERED_YES;
2907 }
2908 d.setMeteredState(meteredState);
2909 final ValidatedState validatedState;
2910 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2911 validatedState = ValidatedState.VS_PORTAL;
2912 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2913 validatedState = ValidatedState.VS_PARTIAL;
2914 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2915 validatedState = ValidatedState.VS_VALID;
2916 } else {
2917 validatedState = ValidatedState.VS_INVALID;
2918 }
2919 d.setValidatedState(validatedState);
2920 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2921 d.setCapabilities(nc.getCapabilitiesInternal());
2922 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2923 builder.addNetworkDescription(d);
2924 }
2925 return builder.build();
2926 }
2927
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002928 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002929 public boolean isNetworkSupported(int networkType) {
2930 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002931 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002932 }
2933
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002934 /**
2935 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002936 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002937 * @return the ip properties for the active network, or {@code null} if
2938 * none is active
2939 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002940 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002941 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002942 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002943 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002944 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2945 if (nai == null) return null;
2946 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002947 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002948 }
2949
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002950 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002951 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002952 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002953 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002954 final LinkProperties lp = getLinkProperties(nai);
2955 if (lp == null) return null;
2956 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002957 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002958 }
2959
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002960 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002961 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002962 public LinkProperties getLinkProperties(Network network) {
2963 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002964 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2965 if (lp == null) return null;
2966 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002967 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002968 }
2969
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002970 @Nullable
2971 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002972 if (nai == null) {
2973 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002974 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002975 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002976 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002977 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002978 }
2979
lucaslinc582d502022-01-27 09:07:00 +08002980 @Override
2981 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002982 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002983 @NonNull String packageName, @Nullable String callingAttributionTag) {
2984 Objects.requireNonNull(packageName);
2985 Objects.requireNonNull(lp);
2986 enforceNetworkStackOrSettingsPermission();
2987 if (!checkAccessPermission(-1 /* pid */, uid)) {
2988 return null;
2989 }
2990 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2991 }
2992
Qingxi Lib2748102020-01-08 12:51:49 -08002993 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2994 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2995 }
2996
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002997 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002998 if (nai == null) return null;
2999 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003000 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003001 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003002 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003003 }
3004
3005 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08003006 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
3007 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003008 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09003009 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08003010 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08003011 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08003012 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08003013 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09003014 }
3015
lucaslinc582d502022-01-27 09:07:00 +08003016 @Override
lucaslind2b06132022-03-02 10:56:57 +08003017 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
3018 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
3019 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08003020 Objects.requireNonNull(nc);
3021 Objects.requireNonNull(packageName);
3022 enforceNetworkStackOrSettingsPermission();
3023 if (!checkAccessPermission(-1 /* pid */, uid)) {
3024 return null;
3025 }
3026 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
3027 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
3028 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
3029 callingAttributionTag);
3030 }
3031
lucaslin69e1aa92022-03-22 18:15:09 +08003032 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
3033 if (nc.getUnderlyingNetworks() != null
3034 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
3035 nc.setUnderlyingNetworks(null);
3036 }
3037 }
3038
Chalard Jean53017782022-11-24 17:13:44 +09003039 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
3040 return Process.SYSTEM_UID == uid
Chalard Jean53017782022-11-24 17:13:44 +09003041 || checkAnyPermissionOf(mContext, pid, uid,
3042 android.Manifest.permission.NETWORK_FACTORY);
3043 }
3044
Qingxi Libb8da982020-01-17 17:54:27 -08003045 @VisibleForTesting
3046 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09003047 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08003048 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
3049 // this would be expensive (one more permission check every time any NC callback is
3050 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
3051 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
3052 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09003053 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09003054 if (!checkSettingsPermission(callerPid, callerUid)) {
3055 newNc.setUids(null);
3056 newNc.setSSID(null);
3057 }
Etan Cohen107ae952018-12-30 17:59:59 -08003058 if (newNc.getNetworkSpecifier() != null) {
3059 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
3060 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08003061 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
3062 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07003063 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
3064 newNc.setAdministratorUids(new int[0]);
3065 }
Chalard Jean53017782022-11-24 17:13:44 +09003066 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09003067 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08003068 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07003069 }
lucaslin69e1aa92022-03-22 18:15:09 +08003070 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08003071
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09003072 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09003073 }
3074
Roshan Pius98f59ec2021-02-23 08:47:39 -08003075 /**
3076 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08003077 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08003078 * NetworkCapabilities.
3079 * Note: This wrapper does not support any sort of invalidation and thus must not be
3080 * persistent or long-lived. It may only be used for the time necessary to
3081 * compute the redactions required by one particular NetworkCallback or
3082 * synchronous call.
3083 */
3084 private class RedactionPermissionChecker {
3085 private final int mCallingPid;
3086 private final int mCallingUid;
3087 @NonNull private final String mCallingPackageName;
3088 @Nullable private final String mCallingAttributionTag;
3089
3090 private Boolean mHasLocationPermission = null;
3091 private Boolean mHasLocalMacAddressPermission = null;
3092 private Boolean mHasSettingsPermission = null;
3093
3094 RedactionPermissionChecker(int callingPid, int callingUid,
3095 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
3096 mCallingPid = callingPid;
3097 mCallingUid = callingUid;
3098 mCallingPackageName = callingPackageName;
3099 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08003100 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08003101
3102 private boolean hasLocationPermissionInternal() {
3103 final long token = Binder.clearCallingIdentity();
3104 try {
3105 return mLocationPermissionChecker.checkLocationPermission(
3106 mCallingPackageName, mCallingAttributionTag, mCallingUid,
3107 null /* message */);
3108 } finally {
3109 Binder.restoreCallingIdentity(token);
3110 }
3111 }
3112
3113 /**
3114 * Returns whether the app holds location permission or not (might return cached result
3115 * if the permission was already checked before).
3116 */
3117 public boolean hasLocationPermission() {
3118 if (mHasLocationPermission == null) {
3119 // If there is no cached result, perform the check now.
3120 mHasLocationPermission = hasLocationPermissionInternal();
3121 }
3122 return mHasLocationPermission;
3123 }
3124
3125 /**
3126 * Returns whether the app holds local mac address permission or not (might return cached
3127 * result if the permission was already checked before).
3128 */
3129 public boolean hasLocalMacAddressPermission() {
3130 if (mHasLocalMacAddressPermission == null) {
3131 // If there is no cached result, perform the check now.
3132 mHasLocalMacAddressPermission =
3133 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
3134 }
3135 return mHasLocalMacAddressPermission;
3136 }
3137
3138 /**
3139 * Returns whether the app holds settings permission or not (might return cached
3140 * result if the permission was already checked before).
3141 */
3142 public boolean hasSettingsPermission() {
3143 if (mHasSettingsPermission == null) {
3144 // If there is no cached result, perform the check now.
3145 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
3146 }
3147 return mHasSettingsPermission;
3148 }
3149 }
3150
3151 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
3152 @NetworkCapabilities.NetCapability long redaction) {
3153 return (redactions & redaction) != 0;
3154 }
3155
3156 /**
3157 * Use the provided |applicableRedactions| to check the receiving app's
3158 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
3159 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
3160 * before being sent to the corresponding app.
3161 */
3162 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
3163 @NetworkCapabilities.RedactionType long applicableRedactions,
3164 @NonNull RedactionPermissionChecker redactionPermissionChecker,
3165 boolean includeLocationSensitiveInfo) {
3166 long redactions = applicableRedactions;
3167 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
3168 if (includeLocationSensitiveInfo
3169 && redactionPermissionChecker.hasLocationPermission()) {
3170 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
3171 }
3172 }
3173 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
3174 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
3175 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
3176 }
3177 }
3178 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
3179 if (redactionPermissionChecker.hasSettingsPermission()) {
3180 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
3181 }
3182 }
3183 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08003184 }
3185
Qingxi Lib2748102020-01-08 12:51:49 -08003186 @VisibleForTesting
3187 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08003188 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08003189 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08003190 int callingPid, int callingUid, @NonNull String callingPkgName,
3191 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08003192 if (nc == null) {
3193 return null;
3194 }
Roshan Pius9ed14622020-12-28 09:01:49 -08003195 // Avoid doing location permission check if the transport info has no location sensitive
3196 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08003197 final RedactionPermissionChecker redactionPermissionChecker =
3198 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
3199 callingAttributionTag);
3200 final long redactions = retrieveRequiredRedactions(
3201 nc.getApplicableRedactions(), redactionPermissionChecker,
3202 includeLocationSensitiveInfo);
3203 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08003204 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08003205 // TODO : calling UID is redacted because apps should generally not know what UID is
3206 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08003207 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08003208 newNc.setOwnerUid(INVALID_UID);
3209 return newNc;
3210 }
Benedict Wongbf004e92020-06-08 11:55:38 -07003211 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
3212 if (nc.hasTransport(TRANSPORT_VPN)) {
3213 // Owner UIDs already checked above. No need to re-check.
3214 return newNc;
3215 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08003216 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
3217 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08003218 // compatibility for older apps.
3219 if (!includeLocationSensitiveInfo
3220 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08003221 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08003222 newNc.setOwnerUid(INVALID_UID);
3223 return newNc;
3224 }
Roshan Pius9ed14622020-12-28 09:01:49 -08003225 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08003226 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08003227 newNc.setOwnerUid(INVALID_UID);
3228 }
Qingxi Lib2748102020-01-08 12:51:49 -08003229 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08003230 }
3231
lucaslinc582d502022-01-27 09:07:00 +08003232 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003233 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
3234 LinkProperties lp, int callerPid, int callerUid) {
3235 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08003236 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
3237 // this would be expensive (one more permission check every time any LP callback is
3238 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
3239 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
3240 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003241
3242 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
3243 final boolean needsSanitization =
3244 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
3245 if (!needsSanitization) {
3246 return new LinkProperties(lp);
3247 }
3248
3249 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09003250 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003251 }
3252
3253 final LinkProperties newLp = new LinkProperties(lp);
3254 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
3255 // object gets parceled.
3256 newLp.setCaptivePortalApiUrl(null);
3257 newLp.setCaptivePortalData(null);
3258 return newLp;
3259 }
3260
Roshan Pius08c94fb2020-01-16 12:17:17 -08003261 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
3262 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09003263 // There is no need to track the effective UID of the request here. If the caller
3264 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09003265 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09003266 // Unprivileged apps can only pass in null or their own UID.
3267 if (nc.getUids() == null) {
3268 // If the caller passes in null, the callback will also match networks that do not
3269 // apply to its UID, similarly to what it would see if it called getAllNetworks.
3270 // In this case, redact everything in the request immediately. This ensures that the
3271 // app is not able to get any redacted information by filing an unredacted request
3272 // and observing whether the request matches something.
3273 if (nc.getNetworkSpecifier() != null) {
3274 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
3275 }
3276 } else {
3277 nc.setSingleUid(callerUid);
3278 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09003279 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08003280 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07003281 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08003282
3283 // Clear owner UID; this can never come from an app.
3284 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003285 }
3286
Chalard Jean38354d12018-03-20 19:13:57 +09003287 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003288 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09003289 nc.addCapability(NET_CAPABILITY_FOREGROUND);
3290 }
3291 }
3292
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09003293 @Override
3294 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
3295 enforceAccessPermission();
3296 final int callerUid = Binder.getCallingUid();
3297 final long token = Binder.clearCallingIdentity();
3298 try {
3299 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
3300 } finally {
3301 Binder.restoreCallingIdentity(token);
3302 }
3303 }
3304
junyulaiebd15162021-03-03 12:09:05 +08003305 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09003306 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07003307 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08003308 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08003309 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08003310
Serik Beketayev05130302021-01-15 16:47:25 -08003311 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08003312 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08003313 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
3314 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08003315 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08003316 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08003317 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08003318 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
3319 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07003320 }
3321 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09003322 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07003323 }
3324
Jeff Sharkey66fa9682011-08-02 17:22:34 -07003325 @Override
junyulaiebd15162021-03-03 12:09:05 +08003326 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08003327 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08003328 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08003329 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08003330
3331 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
3332 for (Network network : getAllNetworks()) {
3333 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09003334 final boolean includeNetwork = (nai != null) && nai.isCreated();
3335 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08003336 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
3337 // NetworkCapabilities, which may contain UIDs of apps to which the
3338 // network applies. Should the UIDs be cleared so as not to leak or
3339 // interfere ?
3340 result.add(nai.getNetworkStateSnapshot());
3341 }
3342 }
3343 return result;
3344 }
3345
3346 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003347 public boolean isActiveNetworkMetered() {
3348 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003349
Qingxi Lib2748102020-01-08 12:51:49 -08003350 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06003351 if (caps != null) {
3352 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3353 } else {
3354 // Always return the most conservative value
3355 return true;
3356 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07003357 }
3358
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003359 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09003360 * Ensures that the system cannot call a particular method.
3361 */
3362 private boolean disallowedBecauseSystemCaller() {
3363 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07003364 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
3365 // for devices launched with Q and above. However, existing devices upgrading to Q and
3366 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003367 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07003368 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003369 log("This method exists only for app backwards compatibility"
3370 + " and must not be called by system services.");
3371 return true;
3372 }
3373 return false;
3374 }
3375
paulhub2c28682021-08-18 18:35:54 +08003376 private int getAppUid(final String app, final UserHandle user) {
3377 final PackageManager pm =
3378 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
3379 final long token = Binder.clearCallingIdentity();
3380 try {
3381 return pm.getPackageUid(app, 0 /* flags */);
3382 } catch (PackageManager.NameNotFoundException e) {
3383 return -1;
3384 } finally {
3385 Binder.restoreCallingIdentity(token);
3386 }
3387 }
3388
3389 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
3390 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
3391 if (getAppUid(packageName, user) != callingUid) {
3392 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
3393 }
3394 }
3395
Lorenzo Colitti23862912018-09-28 11:31:55 +09003396 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003397 * Ensure that a network route exists to deliver traffic to the specified
3398 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003399 * @param networkType the type of the network over which traffic to the
3400 * specified host is to be routed
3401 * @param hostAddress the IP address of the host to which the route is
3402 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003403 * @return {@code true} on success, {@code false} on failure
3404 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003405 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003406 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3407 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003408 if (disallowedBecauseSystemCaller()) {
3409 return false;
3410 }
paulhub2c28682021-08-18 18:35:54 +08003411 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003412 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003413 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003414 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003415 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003416
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003417 InetAddress addr;
3418 try {
3419 addr = InetAddress.getByAddress(hostAddress);
3420 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003421 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003422 return false;
3423 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003424
The Android Open Source Project28527d22009-03-03 19:31:44 -08003425 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003426 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003427 return false;
3428 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003429
3430 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3431 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003432 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003433 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3434 } else {
3435 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3436 }
3437 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003438 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003439
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003440 DetailedState netState;
3441 synchronized (nai) {
3442 netState = nai.networkInfo.getDetailedState();
3443 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003444
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003445 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003446 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003447 log("requestRouteToHostAddress on down network "
3448 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003449 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003450 }
3451 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003452 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003453
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003454 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003455 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003456 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003457 LinkProperties lp;
3458 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003459 synchronized (nai) {
3460 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003461 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003462 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003463 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003464 if (DBG) {
3465 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3466 }
Wink Saville32506bc2013-06-29 21:10:57 -07003467 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003468 } finally {
3469 Binder.restoreCallingIdentity(token);
3470 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003471 }
3472
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003473 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003474 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003475 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003476 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003477 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003478 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003479 if (bestRoute.getGateway().equals(addr)) {
3480 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003481 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003482 } else {
3483 // if we will connect to this through another route, add a direct route
3484 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003485 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003486 }
3487 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003488 if (DBG) log("Adding legacy route " + bestRoute +
3489 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003490
3491 final String dst = bestRoute.getDestinationLinkAddress().toString();
3492 final String nextHop = bestRoute.hasGateway()
3493 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003494 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003495 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3496 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003497 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003498 return false;
3499 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003500 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003501 }
3502
paulhu7c0a2e62021-01-08 00:51:49 +08003503 class DnsResolverUnsolicitedEventCallback extends
3504 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003505 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003506 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003507 try {
3508 mHandler.sendMessage(mHandler.obtainMessage(
3509 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003510 new PrivateDnsValidationUpdate(event.netId,
3511 InetAddresses.parseNumericAddress(event.ipAddress),
3512 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003513 } catch (IllegalArgumentException e) {
3514 loge("Error parsing ip address in validation event");
3515 }
3516 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003517
3518 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003519 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3520 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003521 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3522 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3523 // event callback for certain nai. e.g. cellular. Register here to pass to
3524 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003525 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003526 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3527 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003528 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003529 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003530 }
3531 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003532
3533 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003534 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3535 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3536 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003537 }
dalyk1720e542018-03-05 12:42:22 -05003538
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003539 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003540 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003541 return this.VERSION;
3542 }
3543
3544 @Override
3545 public String getInterfaceHash() {
3546 return this.HASH;
3547 }
paulhu7c0a2e62021-01-08 00:51:49 +08003548 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003549
3550 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003551 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3552 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003553
paulhu7c0a2e62021-01-08 00:51:49 +08003554 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003555 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003556 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003557 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003558 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003559 }
3560 }
3561
Sudheer Shanka9967d462021-03-18 19:09:25 +00003562 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003563 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003564 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003565 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3566 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003567 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05003568
3569 @Override
3570 public void onUidsAllowedTransportsChanged(int[] uids, long[] allowedTransports) {
3571 setUidsAllowedTransports(uids, allowedTransports);
3572 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003573 };
3574
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003575 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003576 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003577 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003578 }
3579
Mark Fasheh7501e762023-05-04 20:23:11 +00003580 static final class UidFrozenStateChangedArgs {
3581 final int[] mUids;
3582 final int[] mFrozenStates;
3583
3584 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3585 mUids = uids;
3586 mFrozenStates = frozenStates;
3587 }
3588 }
3589
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003590 /**
3591 * Check if the cell network is idle.
3592 * @return true if the cell network state is idle
3593 * false if the cell network state is active or unknown
3594 */
3595 private boolean isCellNetworkIdle() {
3596 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3597 if (defaultNai == null
3598 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3599 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3600 // cell network is not the default network, cell network state is unknown.
3601 // TODO(b/279380356): Track cell network state when the cell is not the default network
3602 return false;
3603 }
3604
3605 return !mNetworkActivityTracker.isDefaultNetworkActive();
3606 }
3607
Mark Fasheh7501e762023-05-04 20:23:11 +00003608 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003609 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7501e762023-05-04 20:23:11 +00003610
3611 for (int i = 0; i < uids.length; i++) {
3612 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003613 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003614 } else {
3615 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7501e762023-05-04 20:23:11 +00003616 }
3617 }
3618
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003619 if (ownerUids.isEmpty()) {
3620 return;
3621 }
3622
3623 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3624 // Delay closing sockets to avoid waking the cell modem up.
3625 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3626 // than waking cell modem up.
3627 mPendingFrozenUids.addAll(ownerUids);
3628 } else {
Mark Fasheh7501e762023-05-04 20:23:11 +00003629 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003630 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003631 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7501e762023-05-04 20:23:11 +00003632 loge("Exception in socket destroy: " + e);
3633 }
3634 }
3635 }
3636
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003637 private void closePendingFrozenSockets() {
3638 ensureRunningOnConnectivityServiceThread();
3639
3640 try {
3641 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3642 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3643 loge("Failed to close pending frozen app sockets: " + e);
3644 }
3645 mPendingFrozenUids.clear();
3646 }
3647
3648 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3649 mNetworkActivityTracker.handleReportNetworkActivity(params);
3650
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003651 final boolean isCellNetworkActivity;
3652 if (mTrackMultiNetworkActivities) {
3653 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3654 // nai could be null if netd receives a netlink message and calls the network
3655 // activity change callback after the network is unregistered from ConnectivityService.
3656 isCellNetworkActivity = nai != null
3657 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3658 } else {
3659 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3660 }
3661
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003662 if (mDelayDestroyFrozenSockets
3663 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003664 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003665 && !mPendingFrozenUids.isEmpty()) {
3666 closePendingFrozenSockets();
3667 }
3668 }
3669
3670 /**
3671 * If the cellular network is no longer the default network, close pending frozen sockets.
3672 *
3673 * @param newNetwork new default network
3674 * @param oldNetwork old default network
3675 */
3676 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3677 NetworkAgentInfo oldNetwork) {
3678 final boolean isOldNetworkCellular = oldNetwork != null
3679 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3680 final boolean isNewNetworkCellular = newNetwork != null
3681 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3682
3683 if (isOldNetworkCellular
3684 && !isNewNetworkCellular
3685 && !mPendingFrozenUids.isEmpty()) {
3686 closePendingFrozenSockets();
3687 }
3688 }
3689
3690 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3691 pw.println("CloseFrozenAppSockets:");
3692 pw.increaseIndent();
3693 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3694 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3695 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3696 pw.decreaseIndent();
3697 }
3698
Junyu Lai155760b2023-10-05 14:51:00 +08003699 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3700 pw.println("Bpf Program Status:");
3701 pw.increaseIndent();
3702 try {
3703 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003704 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003705 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003706 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003707 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003708 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003709 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003710 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003711 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003712 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003713 } catch (IOException e) {
3714 pw.println(" IOException");
3715 }
3716 pw.decreaseIndent();
3717 }
3718
Mark Fasheh7501e762023-05-04 20:23:11 +00003719 @VisibleForTesting
3720 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003721 @VisibleForTesting
3722 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3723 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003724
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003725 @VisibleForTesting
3726 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3727 "allow_sysui_connectivity_reports";
3728
Yuyang Huang41557552023-11-28 12:47:22 +09003729 public static final String LOG_BPF_RC = "log_bpf_rc_force_disable";
Mark Fasheh7501e762023-05-04 20:23:11 +00003730
Paul Jensen83f5d572014-08-29 09:54:01 -04003731 private void enforceInternetPermission() {
3732 mContext.enforceCallingOrSelfPermission(
3733 android.Manifest.permission.INTERNET,
3734 "ConnectivityService");
3735 }
3736
The Android Open Source Project28527d22009-03-03 19:31:44 -08003737 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003738 mContext.enforceCallingOrSelfPermission(
3739 android.Manifest.permission.ACCESS_NETWORK_STATE,
3740 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003741 }
3742
lucaslinc582d502022-01-27 09:07:00 +08003743 private boolean checkAccessPermission(int pid, int uid) {
3744 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3745 == PERMISSION_GRANTED;
3746 }
3747
paulhua6ee2122021-02-22 15:40:43 +08003748 /**
3749 * Performs a strict and comprehensive check of whether a calling package is allowed to
3750 * change the state of network, as the condition differs for pre-M, M+, and
3751 * privileged/preinstalled apps. The caller is expected to have either the
3752 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3753 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3754 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3755 * permission and cannot be revoked. See http://b/23597341
3756 *
3757 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3758 * of this app will be updated to the current time.
3759 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003760 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003761 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3762 == PackageManager.PERMISSION_GRANTED) {
3763 return;
3764 }
3765
3766 if (callingPkg == null) {
3767 throw new SecurityException("Calling package name is null.");
3768 }
3769
3770 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3771 final int uid = mDeps.getCallingUid();
3772 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3773 callingPkg, callingAttributionTag, null /* message */);
3774
3775 if (mode == AppOpsManager.MODE_ALLOWED) {
3776 return;
3777 }
3778
3779 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3780 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3781 return;
3782 }
3783
3784 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3785 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3786 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003787 }
3788
Charles He9369e612017-05-15 17:07:18 +01003789 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003790 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003791 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003792 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003793 }
3794
Quang Luong98858d62023-02-11 00:25:24 +00003795 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003796 enforceAnyPermissionOf(mContext,
3797 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003798 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003799 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3800 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3801 }
3802
paulhu8e96a752019-08-12 16:25:11 +08003803 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003804 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003805 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003806 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003807 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003808 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003809 }
3810
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003811 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003812 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003813 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003814 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003815 android.Manifest.permission.NETWORK_SETTINGS,
3816 android.Manifest.permission.NETWORK_FACTORY,
3817 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3818 }
3819
3820 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003821 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003822 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003823 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003824 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3825 android.Manifest.permission.NETWORK_FACTORY,
3826 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3827 }
3828
lucaslin69e1aa92022-03-22 18:15:09 +08003829 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3830 return PERMISSION_GRANTED == mContext.checkPermission(
3831 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3832 || PERMISSION_GRANTED == mContext.checkPermission(
3833 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3834 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003835 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003836 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003837 }
3838
Chalard Jean9a396cc2018-02-21 18:43:54 +09003839 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003840 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003841 android.Manifest.permission.NETWORK_SETTINGS,
3842 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003843 }
3844
3845 private boolean checkSettingsPermission(int pid, int uid) {
3846 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003847 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3848 || PERMISSION_GRANTED == mContext.checkPermission(
3849 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003850 }
3851
paulhu8e96a752019-08-12 16:25:11 +08003852 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003853 enforceNetworkStackPermissionOr(mContext,
3854 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003855 }
3856
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003857 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003858 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003859 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003860 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003861 }
3862
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003863 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003864 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003865 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3866 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003867 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003868 }
3869
James Mattis8378aec2021-01-26 14:05:36 -08003870 private void enforceOemNetworkPreferencesPermission() {
3871 mContext.enforceCallingOrSelfPermission(
3872 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3873 "ConnectivityService");
3874 }
3875
James Mattisfa270db2021-05-31 17:11:10 -07003876 private void enforceManageTestNetworksPermission() {
3877 mContext.enforceCallingOrSelfPermission(
3878 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3879 "ConnectivityService");
3880 }
3881
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003882 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003883 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003884 android.Manifest.permission.NETWORK_STACK,
3885 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003886 }
3887
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003888 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003889 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003890 android.Manifest.permission.NETWORK_STACK,
3891 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3892 }
3893
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003894 private boolean checkSystemBarServicePermission(int pid, int uid) {
3895 return checkAnyPermissionOf(mContext, pid, uid,
3896 android.Manifest.permission.STATUS_BAR_SERVICE);
3897 }
3898
paulhu1a407652019-03-22 16:35:06 +08003899 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003900 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003901 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003902 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3903 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003904 }
3905
Paul Hu8fc2a552022-05-04 18:44:42 +08003906 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3907 boolean checkUidsAllowedList) {
3908 if (PermissionUtils.checkAnyPermissionOf(mContext,
3909 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3910 return true;
3911 }
3912
3913 // fallback to ConnectivityInternalPermission
3914 // TODO: Remove this fallback check after all apps have declared
3915 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3916 if (PermissionUtils.checkAnyPermissionOf(mContext,
3917 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3918 return true;
3919 }
3920
3921 // Check whether uid is in allowed on restricted networks list.
3922 if (checkUidsAllowedList
3923 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3924 return true;
3925 }
3926 return false;
3927 }
3928
3929 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3930 final int callingUid = mDeps.getCallingUid();
3931 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3932 throw new SecurityException("ConnectivityService: user " + callingUid
3933 + " has no permission to access restricted network.");
3934 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003935 }
3936
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003937 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003938 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003939 }
3940
Roshan Pius98f59ec2021-02-23 08:47:39 -08003941 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3942 return PERMISSION_GRANTED == mContext.checkPermission(
3943 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3944 }
3945
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003946 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003947 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003948 }
3949
3950 private void sendInetConditionBroadcast(NetworkInfo info) {
3951 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3952 }
3953
Wink Saville4f0de1e2011-08-04 15:01:58 -07003954 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003955 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003956 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003957 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003958 if (info.isFailover()) {
3959 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3960 info.setFailover(false);
3961 }
3962 if (info.getReason() != null) {
3963 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3964 }
3965 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003966 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3967 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003968 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003969 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003970 return intent;
3971 }
3972
3973 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3974 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3975 }
3976
Michael Groover73f69482023-01-27 11:01:25 -06003977 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3978 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003979 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3980 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003981 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003982 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003983 if (!mSystemReady
3984 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003985 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003986 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003987 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003988 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003989 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003990 }
3991
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003992 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003993 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003994 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003995 final NetworkInfo ni = intent.getParcelableExtra(
3996 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003997 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3998 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003999 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08004000 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08004001 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08004002 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07004003 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00004004 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07004005 } finally {
4006 Binder.restoreCallingIdentity(ident);
4007 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04004008 }
4009 }
4010
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08004011 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
4012 NetworkInfo info) {
4013 // Delivery group policy APIs are only available on U+.
Chalard Jean03552c42023-05-29 17:02:43 +09004014 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08004015
4016 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
4017 try {
4018 // This allows us to discard older broadcasts still waiting to be delivered
4019 // which have the same namespace and key.
4020 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
4021 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
4022 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07004023 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08004024 } catch (UnsupportedApiLevelException e) {
4025 Log.wtf(TAG, "Using unsupported API" + e);
4026 }
4027 }
4028
4029 @VisibleForTesting
4030 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
4031 final StringBuilder sb = new StringBuilder();
4032 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
4033 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
4034 sb.append(info.getExtraInfo());
4035 return sb.toString();
4036 }
4037
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09004038 /**
Aaron Huang96011892020-06-27 07:18:23 +08004039 * Called by SystemServer through ConnectivityManager when the system is ready.
4040 */
4041 @Override
4042 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004043 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08004044 throw new SecurityException("Calling Uid is not system uid.");
4045 }
4046 systemReadyInternal();
4047 }
4048
4049 /**
4050 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09004051 */
4052 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08004053 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004054 // Load flags after PackageManager is ready to query module version
4055 mFlags.loadFlags(mDeps, mContext);
4056
Aaron Huang9a57acf2020-12-08 10:03:29 +08004057 // Since mApps in PermissionMonitor needs to be populated first to ensure that
4058 // listening network request which is sent by MultipathPolicyTracker won't be added
4059 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
4060 // be called after PermissionMonitor#startMonitoring().
4061 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
4062 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
4063 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00004064 final ConditionVariable startMonitoringDone = new ConditionVariable();
4065 mHandler.post(() -> {
4066 mPermissionMonitor.startMonitoring();
4067 startMonitoringDone.open();
4068 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09004069 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08004070 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004071
Hugo Benichie5220992017-04-26 14:53:28 +09004072 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04004073 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08004074 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07004075 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08004076 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04004077 }
4078 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07004079
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07004080 // Create network requests for always-on networks.
4081 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00004082
4083 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09004084 // Note that updating can be skipped here if the list is empty only because no uid
4085 // rules are applied before system ready. Normally, the empty uid list means to clear
4086 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00004087 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
4088 updateMobileDataPreferredUids();
4089 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09004090
4091 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jean03552c42023-05-29 17:02:43 +09004092 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09004093 mBpfNetMaps.setPullAtomCallback(mContext);
4094 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09004095 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
4096 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00004097 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
4098 // have permission problem. While CV#block() is unbounded in time and can in principle block
4099 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
4100 // could have blocked forever too.
4101 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08004102 }
4103
The Android Open Source Project28527d22009-03-03 19:31:44 -08004104 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08004105 * Start listening for default data network activity state changes.
4106 */
4107 @Override
4108 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08004109 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08004110 }
4111
4112 /**
4113 * Stop listening for default data network activity state changes.
4114 */
4115 @Override
4116 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08004117 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08004118 }
4119
4120 /**
4121 * Check whether the default network radio is currently active.
4122 */
4123 @Override
4124 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08004125 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08004126 }
4127
4128 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09004129 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09004130 * and set it on it's iface.
4131 */
Junyu Lai970963e2022-10-25 15:46:47 +08004132 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004133 final String iface = newLp.getInterfaceName();
4134 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00004135 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09004136 // Silently ignore unset MTU value.
4137 return;
4138 }
Hansen Kurli04252032022-12-07 11:21:49 +00004139 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
4140 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
4141 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004142 return;
4143 }
Hansen Kurli04252032022-12-07 11:21:49 +00004144 // Cannot set MTU without interface name
4145 if (TextUtils.isEmpty(iface)) {
4146 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004147 return;
4148 }
sy.yun4aa73922013-09-02 05:24:09 +09004149
Hansen Kurli04252032022-12-07 11:21:49 +00004150 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
4151 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07004152 return;
4153 }
4154
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004155 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004156 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08004157 mNetd.interfaceSetMtu(iface, mtu);
4158 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08004159 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004160 }
4161 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07004162
Chenbo Feng15416292018-11-08 17:36:21 -08004163 @VisibleForTesting
4164 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04004165
Junyu Lai970963e2022-10-25 15:46:47 +08004166 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07004167 String[] values = null;
4168 if (tcpBufferSizes != null) {
4169 values = tcpBufferSizes.split(",");
4170 }
4171
4172 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07004173 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07004174 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
4175 values = tcpBufferSizes.split(",");
4176 }
4177
4178 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
4179
4180 try {
Aaron Huang6616df32020-10-30 22:04:25 +08004181 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07004182
Chenbo Feng15416292018-11-08 17:36:21 -08004183 String rmemValues = String.join(" ", values[0], values[1], values[2]);
4184 String wmemValues = String.join(" ", values[3], values[4], values[5]);
4185 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07004186 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08004187 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07004188 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07004189 }
4190 }
4191
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07004192 @Override
4193 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09004194 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07004195 NETWORK_RESTORE_DELAY_PROP_NAME);
4196 if(restoreDefaultNetworkDelayStr != null &&
4197 restoreDefaultNetworkDelayStr.length() != 0) {
4198 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01004199 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07004200 } catch (NumberFormatException e) {
4201 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004202 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07004203 // if the system property isn't set, use the value for the apn type
4204 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
4205
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09004206 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
4207 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07004208 }
4209 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08004210 }
4211
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004212 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09004213 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004214 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09004215 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08004216 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004217 // Start gathering diagnostic information.
4218 netDiags.add(new NetworkDiagnostics(
4219 nai.network,
4220 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08004221 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004222 DIAG_TIME_MS));
4223 }
4224
4225 for (NetworkDiagnostics netDiag : netDiags) {
4226 pw.println();
4227 netDiag.waitForMeasurements();
4228 netDiag.dump(pw);
4229 }
4230 }
4231
The Android Open Source Project28527d22009-03-03 19:31:44 -08004232 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004233 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
4234 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08004235 if (!checkDumpPermission(mContext, TAG, writer)) return;
4236
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08004237 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07004238 }
4239
lucaslin99473f62020-12-10 15:10:54 +08004240 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
4241 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4242 != PackageManager.PERMISSION_GRANTED) {
4243 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004244 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08004245 + " due to missing android.permission.DUMP permission");
4246 return false;
4247 } else {
4248 return true;
4249 }
4250 }
4251
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08004252 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004253 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004254
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004255 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004256 dumpNetworkDiagnostics(pw);
4257 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004258 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004259 dumpNetworks(pw);
4260 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004261 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004262 dumpNetworkRequests(pw);
4263 return;
Ken Chene6d511f2022-01-25 11:10:42 +08004264 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
4265 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
4266 dumpTrafficController(pw, fd, verbose);
4267 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004268 }
Erik Kline9647f382015-06-05 17:47:34 +09004269
Junyu Lai0da479b2022-04-20 15:06:29 +08004270 pw.println("NetworkProviders for:");
4271 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004272 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08004273 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004274 }
Junyu Lai0da479b2022-04-20 15:06:29 +08004275 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004276 pw.println();
4277
Chalard Jean5b409c72021-02-04 13:12:59 +09004278 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004279 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09004280 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004281 pw.println("none");
4282 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09004283 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08004284 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08004285 pw.println();
4286
James Mattis8b298a02021-06-01 22:34:04 -07004287 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08004288 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07004289 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08004290 pw.decreaseIndent();
4291 pw.println();
4292
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004293 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004294 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004295 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004296 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004297 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08004298
junyulaif2c67e42018-08-07 19:50:45 +08004299 pw.println("Status for known UIDs:");
4300 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00004301 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08004302 for (int i = 0; i < size; i++) {
4303 // Don't crash if the array is modified while dumping in bugreports.
4304 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00004305 final int uid = mUidBlockedReasons.keyAt(i);
4306 final int blockedReasons = mUidBlockedReasons.valueAt(i);
4307 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00004308 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08004309 } catch (ArrayIndexOutOfBoundsException e) {
4310 pw.println(" ArrayIndexOutOfBoundsException");
4311 } catch (ConcurrentModificationException e) {
4312 pw.println(" ConcurrentModificationException");
4313 }
4314 }
4315 pw.println();
4316 pw.decreaseIndent();
4317
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004318 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004319 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004320 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004321 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004322 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004323
Junyu Lai0da479b2022-04-20 15:06:29 +08004324 pw.println("Network Offers:");
4325 pw.increaseIndent();
4326 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
4327 pw.println(offerInfo.offer);
4328 }
4329 pw.decreaseIndent();
4330 pw.println();
4331
Robert Greenwalt94e22142014-07-30 16:31:24 -07004332 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07004333
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004334 pw.println();
markchien5e866652019-09-30 14:40:57 +08004335 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07004336
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004337 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004338 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004339
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004340 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004341 dumpCloseFrozenAppSockets(pw);
4342
4343 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08004344 dumpBpfProgramStatus(pw);
4345
Chalard Jean53017782022-11-24 17:13:44 +09004346 if (null != mCarrierPrivilegeAuthenticator) {
4347 pw.println();
4348 mCarrierPrivilegeAuthenticator.dump(pw);
4349 }
4350
Junyu Lai155760b2023-10-05 14:51:00 +08004351 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004352
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004353 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004354 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09004355 pw.println("mNetworkRequestInfoLogs (most recent first):");
4356 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004357 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09004358 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09004359
4360 pw.println();
4361 pw.println("mNetworkInfoBlockingLogs (most recent first):");
4362 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004363 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09004364 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09004365
4366 pw.println();
4367 pw.println("NetTransition WakeLock activity (most recent first):");
4368 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004369 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
4370 pw.println("total releases: " + mTotalWakelockReleases);
4371 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
4372 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
4373 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
4374 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4375 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
4376 }
James Mattiscb1e0362021-04-06 17:07:42 -07004377 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004378
4379 pw.println();
4380 pw.println("bandwidth update requests (by uid):");
4381 pw.increaseIndent();
4382 synchronized (mBandwidthRequests) {
4383 for (int i = 0; i < mBandwidthRequests.size(); i++) {
4384 pw.println("[" + mBandwidthRequests.keyAt(i)
4385 + "]: " + mBandwidthRequests.valueAt(i));
4386 }
4387 }
4388 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004389 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004390
James Mattiscb1e0362021-04-06 17:07:42 -07004391 pw.println();
4392 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4393 pw.increaseIndent();
4394 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004395 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004396 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004397
4398 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004399
4400 pw.println();
4401 pw.println("Permission Monitor:");
4402 pw.increaseIndent();
4403 mPermissionMonitor.dump(pw);
4404 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004405
4406 pw.println();
4407 pw.println("Legacy network activity:");
4408 pw.increaseIndent();
4409 mNetworkActivityTracker.dump(pw);
4410 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08004411 }
4412
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004413 private void dumpNetworks(IndentingPrintWriter pw) {
4414 for (NetworkAgentInfo nai : networksSortedById()) {
4415 pw.println(nai.toString());
4416 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004417 pw.println("Nat464Xlat:");
4418 pw.increaseIndent();
4419 nai.dumpNat464Xlat(pw);
4420 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004421 pw.println(String.format(
4422 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4423 nai.numForegroundNetworkRequests(),
4424 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4425 nai.numBackgroundNetworkRequests(),
4426 nai.numNetworkRequests()));
4427 pw.increaseIndent();
4428 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4429 pw.println(nai.requestAt(i).toString());
4430 }
4431 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004432 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004433 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004434 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004435 pw.decreaseIndent();
4436 pw.decreaseIndent();
4437 }
4438 }
4439
James Mattis8b298a02021-06-01 22:34:04 -07004440 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4441 if (!mProfileNetworkPreferences.isEmpty()) {
4442 pw.println("Profile preferences:");
4443 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004444 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004445 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004446 }
James Mattis8b298a02021-06-01 22:34:04 -07004447 if (!mOemNetworkPreferences.isEmpty()) {
4448 pw.println("OEM preferences:");
4449 pw.increaseIndent();
4450 pw.println(mOemNetworkPreferences);
4451 pw.decreaseIndent();
4452 }
4453 if (!mMobileDataPreferredUids.isEmpty()) {
4454 pw.println("Mobile data preferred UIDs:");
4455 pw.increaseIndent();
4456 pw.println(mMobileDataPreferredUids);
4457 pw.decreaseIndent();
4458 }
James Mattis45d81842021-01-10 14:24:24 -08004459
James Mattis8b298a02021-06-01 22:34:04 -07004460 pw.println("Default requests:");
4461 pw.increaseIndent();
4462 dumpPerAppDefaultRequests(pw);
4463 pw.decreaseIndent();
4464 }
4465
4466 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004467 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4468 if (mDefaultRequest == defaultRequest) {
4469 continue;
4470 }
4471
James Mattis8b298a02021-06-01 22:34:04 -07004472 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4473 final String networkOutput;
4474 if (null == satisfier) {
4475 networkOutput = "null";
4476 } else if (mNoServiceNetwork.equals(satisfier)) {
4477 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004478 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004479 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004480 }
James Mattis8b298a02021-06-01 22:34:04 -07004481 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4482 ? "" : " asUid: " + defaultRequest.mAsUid;
4483 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4484 + defaultRequest.mPid + asUidString + "]";
4485 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4486 + " Preference order: " + defaultRequest.mPreferenceOrder
4487 + " Tracked UIDs: " + defaultRequest.getUids();
4488 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004489 }
4490 }
4491
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004492 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004493 NetworkRequestInfo[] infos = null;
4494 while (infos == null) {
4495 try {
4496 infos = requestsSortedById();
4497 } catch (ConcurrentModificationException e) {
4498 // mNetworkRequests should only be accessed from handler thread, except dump().
4499 // As dump() is never called in normal usage, it would be needlessly expensive
4500 // to lock the collection only for its benefit. Instead, retry getting the
4501 // requests if ConcurrentModificationException is thrown during dump().
4502 }
4503 }
4504 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004505 pw.println(nri.toString());
4506 }
4507 }
4508
Ken Chene6d511f2022-01-25 11:10:42 +08004509 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4510 boolean verbose) {
4511 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004512 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004513 } catch (ServiceSpecificException e) {
4514 pw.println(e.getMessage());
4515 } catch (IOException e) {
4516 loge("Dump BPF maps failed, " + e);
4517 }
4518 }
4519
Chalard Jean524f0b12021-10-25 21:11:56 +09004520 private void dumpAllRequestInfoLogsToLogcat() {
4521 try (PrintWriter logPw = new PrintWriter(new Writer() {
4522 @Override
4523 public void write(final char[] cbuf, final int off, final int len) {
4524 // This method is called with 0-length and 1-length arrays for empty strings
4525 // or strings containing only the DEL character.
4526 if (len <= 1) return;
4527 Log.e(TAG, new String(cbuf, off, len));
4528 }
4529 @Override public void flush() {}
4530 @Override public void close() {}
4531 })) {
4532 mNetworkRequestInfoLogs.dump(logPw);
4533 }
4534 }
4535
Hugo Benichia480ba52018-09-03 08:19:02 +09004536 /**
4537 * Return an array of all current NetworkAgentInfos sorted by network id.
4538 */
4539 private NetworkAgentInfo[] networksSortedById() {
4540 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004541 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004542 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004543 return networks;
4544 }
4545
4546 /**
4547 * Return an array of all current NetworkRequest sorted by request id.
4548 */
James Mattis258ea3c2020-11-15 15:04:40 -08004549 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004550 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004551 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004552 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004553 // Sort the array based off the NRI containing the min requestId in its requests.
4554 Arrays.sort(requests,
4555 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4556 Comparator.comparingInt(req -> req.requestId)).requestId
4557 )
4558 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004559 return requests;
4560 }
4561
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004562 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004563 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004564 if (officialNai != null && officialNai.equals(nai)) return true;
4565 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004566 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004567 " - " + nai);
4568 }
4569 return false;
4570 }
4571
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004572 private boolean isDisconnectRequest(Message msg) {
4573 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4574 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4575 return info.getState() == NetworkInfo.State.DISCONNECTED;
4576 }
4577
Robert Greenwalt2034b912009-08-12 16:08:25 -07004578 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004579 private class NetworkStateTrackerHandler extends Handler {
4580 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004581 super(looper);
4582 }
4583
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004584 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004585 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4586 final NetworkAgentInfo nai = arg.first;
4587 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004588 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004589 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004590 }
4591 return;
4592 }
4593
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004594 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004595 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004596 return;
4597 }
4598
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004599 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004600 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004601 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4602 if (!nai.respectsNcStructuralConstraints(proposed)) {
4603 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4604 + nai.networkCapabilities + " -> " + proposed);
4605 disconnectAndDestroyNetwork(nai);
4606 return;
4607 }
4608 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004609 final NetworkCapabilities sanitized =
4610 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004611 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004612 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004613 break;
4614 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004615 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004616 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004617 processLinkPropertiesFromAgent(nai, newLp);
4618 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004619 break;
4620 }
4621 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004622 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004623 updateNetworkInfo(nai, info);
4624 break;
4625 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004626 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4627 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004628 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004629 break;
4630 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004631 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004632 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004633 break;
4634 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004635 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004636 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004637 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004638 // Note that if the NAI had been connected, this would affect the
4639 // score, and therefore would require re-mixing the score and performing
4640 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004641 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004642 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4643 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004644 // Mark the network as temporarily accepting partial connectivity so that it
4645 // will be validated (and possibly become default) even if it only provides
4646 // partial internet access. Note that if user connects to partial connectivity
4647 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4648 // out of wifi coverage) and if the same wifi is available again, the device
4649 // will auto connect to this wifi even though the wifi has "no internet".
4650 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004651 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004652 break;
4653 }
junyulai011b1f12019-01-03 18:50:15 +08004654 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004655 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004656 break;
4657 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004658 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004659 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004660 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004661
4662 if (isLegacyLockdownNai(nai)
4663 && (underlying == null || underlying.size() != 1)) {
4664 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4665 + " must have exactly one underlying network: " + underlying);
4666 }
4667
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004668 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4669 nai.declaredUnderlyingNetworks = (underlying != null)
4670 ? underlying.toArray(new Network[0]) : null;
4671
4672 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4673 if (DBG) {
4674 log(nai.toShortString() + " changed underlying networks to "
4675 + Arrays.toString(nai.declaredUnderlyingNetworks));
4676 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004677 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004678 notifyIfacesChangedForNetworkStats();
4679 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004680 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004681 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004682 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4683 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4684 nai.teardownDelayMs = msg.arg1;
4685 } else {
4686 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4687 }
Chalard Jean550b5212021-03-05 23:07:53 +09004688 break;
4689 }
4690 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4691 nai.setLingerDuration((int) arg.second);
4692 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004693 }
Tyler Wear72388212021-09-09 14:49:02 -07004694 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4695 DscpPolicy policy = (DscpPolicy) arg.second;
4696 if (mDscpPolicyTracker != null) {
4697 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4698 }
4699 break;
4700 }
4701 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4702 if (mDscpPolicyTracker != null) {
4703 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4704 }
4705 break;
4706 }
4707 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4708 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004709 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004710 }
4711 break;
4712 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004713 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09004714 if (!nai.everConnected()) {
4715 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4716 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004717 teardownUnneededNetwork(nai);
4718 break;
4719 }
4720
4721 if (nai.isDestroyed()) {
4722 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4723 + ", ignoring");
4724 break;
4725 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004726
4727 final int timeoutMs = (int) arg.second;
4728 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4729 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4730 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4731 }
4732
4733 // Marking a network awaiting replacement is used to ensure that any requests
4734 // satisfied by the network do not switch to another network until a
4735 // replacement is available or the wait for a replacement times out.
4736 // If the network is inactive (i.e., nascent or lingering), then there are no
4737 // such requests, and there is no point keeping it. Just tear it down.
4738 // Note that setLingerDuration(0) cannot be used to do this because the network
4739 // could be nascent.
4740 nai.clearInactivityState();
4741 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4742 Log.d(TAG, nai.toShortString()
4743 + " marked awaiting replacement is unneeded, tearing down instead");
4744 teardownUnneededNetwork(nai);
4745 break;
4746 }
4747
4748 Log.d(TAG, "Marking " + nai.toShortString()
4749 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4750 destroyNativeNetwork(nai);
4751
4752 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4753 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4754 // consider the fact that the network could already have disconnected or been
4755 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4756 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4757 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4758 mKeepaliveTracker.handleStopAllKeepalives(nai,
4759 SocketKeepalive.ERROR_INVALID_NETWORK);
4760
4761 nai.updateScoreForNetworkAgentUpdate();
4762 // This rematch is almost certainly not going to result in any changes, because
4763 // the destroyed flag is only just above the "current satisfier wins"
4764 // tie-breaker. But technically anything that affects scoring should rematch.
4765 rematchAllNetworksAndRequests();
Jean Chalard01a7d322023-06-27 08:54:23 +00004766 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004767 break;
4768 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004769 }
4770 }
4771
4772 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004773 final int netId = msg.arg2;
4774 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004775 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004776 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004777 switch (msg.what) {
4778 default:
4779 return false;
lucasline117e2e2019-10-22 18:27:33 +08004780 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004781 if (nai == null) {
4782 break;
4783 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004784 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4785 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004786 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004787 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004788 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004789 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004790 if (probePrivateDnsCompleted) {
4791 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4792 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004793 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004794 }
4795 // Only show the notification when the private DNS is broken and the
4796 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004797 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004798 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4799 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004800 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004801 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4802 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4803 // private DNS is broken, it means this network is being reevaluated.
4804 // Either probing private DNS is not necessary any more or it hasn't been
4805 // done yet. In either case, the networkCapabilities should be updated to
4806 // reflect the new status.
4807 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004808 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004809 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004810 }
4811 break;
4812 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004813 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004814 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4815
Erik Kline31b4a9e2018-01-11 21:07:29 +09004816 if (nai == null) break;
4817
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004818 handleNetworkTested(nai, results.mTestResult,
4819 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004820 break;
4821 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004822 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004823 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004824 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004825 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004826 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004827 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004828 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4829 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004830 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004831 if (nai == null) {
4832 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4833 break;
4834 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004835 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004836 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004837 (PendingIntent) msg.obj,
4838 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004839 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004840 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004841 break;
4842 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004843 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004844 if (nai == null) break;
4845
Erik Kline9a62f012018-03-21 07:18:33 -07004846 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004847 break;
4848 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004849 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004850 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004851 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004852 break;
4853 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004854 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004855 return true;
4856 }
4857
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004858 private void handleNetworkTested(
4859 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004860 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4861 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004862 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004863
4864 // If there is any kind of working networking, then the NAI has been evaluated
4865 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4866 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004867 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004868 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004869 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4870 // any callback that receives onAvailable for that rematch receives an extra caps
4871 // callback. To prevent that, update the score in the agent so the updates below won't
4872 // see an update to both caps and score at the same time.
4873 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004874 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4875
he_won.hwang881307a2022-03-15 21:23:52 +09004876 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4877 // Assume the validation failure is due to a temporary failure after roaming
4878 // and ignore it. NetworkMonitor will continue to retry validation. If it
4879 // continues to fail after the block timeout expires, the network will be
4880 // marked unvalidated. If it succeeds, then validation state will not change.
4881 return;
4882 }
4883
Chalard Jean254bd162022-08-25 13:04:51 +09004884 final boolean wasValidated = nai.isValidated();
4885 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004886 final boolean wasPortal = nai.captivePortalDetected();
4887 nai.setPartialConnectivity(partial);
4888 nai.setCaptivePortalDetected(portal);
4889 nai.updateScoreForNetworkAgentUpdate();
4890 final boolean partialConnectivityChanged = (wasPartial != partial);
4891 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004892
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004893 if (DBG) {
4894 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4895 ? " with redirect to " + redirectUrl
4896 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004897 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004898 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004899 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004900 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004901 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004902 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004903 if (valid) {
4904 handleFreshlyValidatedNetwork(nai);
4905 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4906 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004907 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004908 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004909 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004910 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004911 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004912 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004913 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004914 NotificationType.PRIVATE_DNS_BROKEN);
4915 // If network becomes valid, the hasShownBroken should be reset for
4916 // that network so that the notification will be fired when the private
4917 // DNS is broken again.
4918 nai.networkAgentConfig.hasShownBroken = false;
4919 }
4920 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004921 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004922 } else if (portalChanged) {
4923 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004924 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004925 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4926 nai.onPreventAutomaticReconnect();
4927 teardownUnneededNetwork(nai);
4928 return;
4929 } else {
4930 updateCapabilitiesForNetwork(nai);
4931 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004932 } else if (becameEvaluated) {
4933 // If valid or partial connectivity changed, updateCapabilities* has
4934 // done the rematch.
4935 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004936 }
4937 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004938
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004939 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004940 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004941 nai.onValidationStatusChanged(
4942 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4943 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004944
4945 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004946 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004947 // immediately. Re-notify partial connectivity silently if no internet
4948 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004949 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004950 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004951 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4952 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004953 }
4954
Chalard Jean254bd162022-08-25 13:04:51 +09004955 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004956 handleNetworkUnvalidated(nai);
4957 }
4958 }
4959
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004960 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4961 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4962 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4963 // Do not avoid captive portal when network is wear proxy.
4964 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4965 }
4966
Calvin Ondada1452016-10-11 15:10:46 -07004967 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004968 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4969 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004970 }
4971
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004972 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4973 switch (msg.what) {
4974 default:
4975 return false;
4976 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4977 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4978 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4979 handleLingerComplete(nai);
4980 }
4981 break;
4982 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004983 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4984 handleNetworkAgentRegistered(msg);
4985 break;
4986 }
4987 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4988 handleNetworkAgentDisconnected(msg);
4989 break;
4990 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004991 }
4992 return true;
4993 }
4994
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004995 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004996 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004997 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004998 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004999 maybeHandleNetworkAgentMessage(msg);
5000 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005001 }
5002 }
5003
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005004 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09005005 private final int mNetId;
5006 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005007
5008 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005009 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005010 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005011 }
5012
5013 @Override
5014 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
5015 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09005016 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005017 }
5018
5019 @Override
5020 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005021 // Legacy version of notifyNetworkTestedWithExtras.
5022 // Would only be called if the system has a NetworkStack module older than the
5023 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08005024 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005025 }
5026
5027 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005028 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09005029 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
5030 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005031 final Message msg = mTrackerHandler.obtainMessage(
5032 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09005033 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005034 new NetworkTestedResults(
5035 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08005036 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005037
5038 // Invoke ConnectivityReport generation for this Network test event.
5039 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
5040 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005041
Cody Kestingf1120be2020-08-03 18:01:40 -07005042 // NetworkMonitor reports the network validation result as a bitmask while
5043 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
5044 // logical value for ConnectivityDiagnostics.
5045 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
5046 p.result);
5047
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005048 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07005049 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005050 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
5051 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
5052
Aaron Huang959d3642021-01-21 15:47:41 +08005053 ConnectivityReportEvent reportEvent =
5054 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
5055 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09005056 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005057 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005058 }
5059
5060 @Override
5061 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
5062 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
5063 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09005064 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005065 }
5066
5067 @Override
lucasline117e2e2019-10-22 18:27:33 +08005068 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
5069 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
5070 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09005071 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08005072 }
5073
5074 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09005075 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
5076 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
5077 EVENT_CAPPORT_DATA_CHANGED,
5078 0, mNetId, data));
5079 }
5080
5081 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09005082 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005083 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09005084 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005085
5086 final PendingIntent pendingIntent;
5087 // Only the system server can register notifications with package "android"
5088 final long token = Binder.clearCallingIdentity();
5089 try {
paulhu7746e4e2020-06-09 19:07:03 +08005090 pendingIntent = PendingIntent.getBroadcast(
5091 mContext,
5092 0 /* requestCode */,
5093 intent,
5094 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005095 } finally {
5096 Binder.restoreCallingIdentity(token);
5097 }
5098 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
5099 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09005100 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005101 }
5102
5103 @Override
5104 public void hideProvisioningNotification() {
5105 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09005106 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005107 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09005108
5109 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09005110 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07005111 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08005112 }
5113
5114 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09005115 public int getInterfaceVersion() {
5116 return this.VERSION;
5117 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09005118
5119 @Override
5120 public String getInterfaceHash() {
5121 return this.HASH;
5122 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005123 }
5124
Cody Kestingf1120be2020-08-03 18:01:40 -07005125 /**
5126 * Converts the given NetworkMonitor-specific validation result bitmask to a
5127 * ConnectivityDiagnostics-specific validation result int.
5128 */
5129 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
5130 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
5131 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
5132 }
5133 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
5134 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
5135 }
5136 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
5137 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
5138 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
5139 }
5140
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07005141 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07005142 log("Data stall detected with methods: " + p.detectionMethod);
5143
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07005144 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07005145 int detectionMethod = 0;
5146 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
5147 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
5148 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
5149 }
5150 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
5151 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
5152 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
5153 p.tcpMetricsCollectionPeriodMillis);
5154 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07005155 }
5156
Cody Kestingf53a0752020-04-15 12:33:28 -07005157 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07005158 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08005159 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07005160
5161 // NetworkStateTrackerHandler currently doesn't take any actions based on data
5162 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
5163 // the cost of going through two handlers.
5164 mConnectivityDiagnosticsHandler.sendMessage(msg);
5165 }
5166
Cody Kestingb37958e2020-05-15 10:36:01 -07005167 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
5168 return (p.detectionMethod & detectionMethod) != 0;
5169 }
5170
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09005171 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
5172 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07005173 }
5174
Erik Klinea73af002018-06-26 18:53:43 +09005175 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
5176 if (nai == null) return;
5177 // If the Private DNS mode is opportunistic, reprogram the DNS servers
5178 // in order to restart a validation pass from within netd.
5179 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00005180 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005181 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09005182 }
5183 }
5184
Erik Kline31b4a9e2018-01-11 21:07:29 +09005185 private void handlePrivateDnsSettingsChanged() {
5186 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
5187
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005188 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07005189 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09005190 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05005191 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
5192 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005193 }
5194 }
5195
Erik Kline9a62f012018-03-21 07:18:33 -07005196 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
5197 // Private DNS only ever applies to networks that might provide
5198 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09005199 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09005200
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005201 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07005202 // schedule DNS resolutions. If a DNS resolution is required the
5203 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005204 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07005205
5206 // With Private DNS bypass support, we can proceed to update the
5207 // Private DNS config immediately, even if we're in strict mode
5208 // and have not yet resolved the provider name into a set of IPs.
5209 updatePrivateDns(nai, cfg);
5210 }
5211
5212 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
5213 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08005214 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09005215 }
5216
dalyk1720e542018-03-05 12:42:22 -05005217 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
5218 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
5219 if (nai == null) {
5220 return;
5221 }
5222 mDnsManager.updatePrivateDnsValidation(update);
5223 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
5224 }
5225
paulhu7c0a2e62021-01-08 00:51:49 +08005226 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005227 int prefixLength) {
5228 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
5229 if (nai == null) return;
5230
paulhu7c0a2e62021-01-08 00:51:49 +08005231 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
5232 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005233
5234 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08005235 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005236 try {
paulhu7c0a2e62021-01-08 00:51:49 +08005237 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005238 prefixLength);
5239 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08005240 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005241 return;
5242 }
5243 }
5244
Lorenzo Colittid523d142020-04-01 20:16:30 +09005245 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09005246 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
5247 }
5248
Hai Shalome58bdc62021-01-11 18:45:34 -08005249 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09005250 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08005251 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09005252 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
5253 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
5254 }
5255
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005256 /**
junyulai2b6f0c22021-02-03 20:15:30 +08005257 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005258 * @param nai the agent info to update
5259 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08005260 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005261 */
junyulai2b6f0c22021-02-03 20:15:30 +08005262 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
5263 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
5264 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005265 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08005266 // one lingered request, set inactive.
5267 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08005268 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08005269 if (DBG) log("Unsetting inactive " + nai.toShortString());
5270 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005271 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08005272 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005273 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08005274 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
5275 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005276 }
junyulai2b6f0c22021-02-03 20:15:30 +08005277 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005278 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005279 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005280 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005281 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05005282 }
5283
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005284 private void handleNetworkAgentRegistered(Message msg) {
5285 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
5286 if (!mNetworkAgentInfos.contains(nai)) {
5287 return;
5288 }
5289
5290 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
5291 if (VDBG) log("NetworkAgent registered");
5292 } else {
5293 loge("Error connecting NetworkAgent");
5294 mNetworkAgentInfos.remove(nai);
5295 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005296 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005297 synchronized (mNetworkForNetId) {
5298 mNetworkForNetId.remove(nai.network.getNetId());
Tommy Webb34f81dc2023-02-20 14:10:55 -05005299 mNetIdToAllowlist.remove(nai.network.getNetId());
5300 mNetIdToDisallowedUids.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005301 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05005302 updateDisallowedUidsForNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005303 mNetIdManager.releaseNetId(nai.network.getNetId());
5304 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09005305 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005306 }
5307 }
5308 }
Paul Jensend5f53392014-11-25 15:26:53 -05005309
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09005310 @VisibleForTesting
5311 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jean2e50cc92023-06-27 19:16:00 +09005312 // The feature of creating the networks immediately was slated for U, but race conditions
5313 // detected late required this was flagged off.
5314 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
5315 // in NetworkAgentTest.
5316 return false;
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09005317 }
5318
5319 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
5320 @NonNull NetworkInfo.State state) {
5321 if (nai.isCreated()) return false;
5322 if (state == NetworkInfo.State.CONNECTED) return true;
5323 if (state != NetworkInfo.State.CONNECTING) {
5324 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti38560562023-06-07 11:34:05 +09005325 if (shouldCreateNetworksImmediately()) {
5326 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
5327 }
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09005328 return false;
5329 }
5330 return nai.isVPN() || shouldCreateNetworksImmediately();
5331 }
5332
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005333 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09005334 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005335 }
5336
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005337 @VisibleForTesting
5338 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09005339 // T+ devices should use unregisterAfterReplacement.
Chalard Jean03552c42023-05-29 17:02:43 +09005340 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005341
5342 // If the network never roamed, return false. The check below is not sufficient if time
5343 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
5344 if (nai.lastRoamTime == 0) return false;
5345
he_won.hwang881307a2022-03-15 21:23:52 +09005346 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
5347 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005348 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09005349 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09005350 final long currentTimeMs = SystemClock.elapsedRealtime();
5351 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09005352 if (timeSinceLastRoam <= blockTimeOut) {
5353 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
5354 return true;
5355 }
5356 }
5357 return false;
5358 }
5359
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005360 private void handleNetworkAgentDisconnected(Message msg) {
5361 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07005362 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005363 }
5364
Chalard Jeand9fffc32018-05-11 20:19:20 +09005365 // Destroys a network, remove references to it from the internal state managed by
5366 // ConnectivityService, free its interfaces and clean up.
5367 // Must be called on the Handler thread.
5368 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005369 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07005370
5371 if (!mNetworkAgentInfos.contains(nai)) return;
5372
Chalard Jeand9fffc32018-05-11 20:19:20 +09005373 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09005374 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005375 }
lucaslinb25c9a62019-02-12 15:30:13 +08005376 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005377 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005378 // A network agent has disconnected.
5379 // TODO - if we move the logic to the network agent (have them disconnect
5380 // because they lost all their requests or because their score isn't good)
5381 // then they would disconnect organically, report their new state and then
5382 // disconnect the channel.
wangshengrjxtjcb9b5334d2023-05-09 09:51:06 +08005383 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005384 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
5385 null, null);
5386 }
Chalard Jean5b409c72021-02-04 13:12:59 +09005387 final boolean wasDefault = isDefaultNetwork(nai);
5388 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005389 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09005390 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005391 if (mTrackMultiNetworkActivities) {
5392 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
5393 // the network becomes no longer the default network.
5394 mNetworkActivityTracker.removeDataActivityTracking(nai);
5395 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005396 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005397 // If this was a local network forwarded to some upstream, or if some local network was
5398 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005399 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005400 // If this is a local network with an upstream selector, remove the associated network
5401 // request.
5402 if (nai.isLocalNetwork()) {
5403 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5404 if (null != selector) {
5405 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5406 }
5407 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005408 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5409 // by other networks that are already connected. Perhaps that can be done by
5410 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5411 // of rematchAllNetworksAndRequests
5412 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005413 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005414
5415 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005416 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5417 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005418 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005419 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005420 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005421 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005422 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005423 synchronized (mNetworkForNetId) {
5424 // Remove the NetworkAgent, but don't mark the netId as
5425 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005426 mNetworkForNetId.remove(nai.network.getNetId());
Tommy Webb34f81dc2023-02-20 14:10:55 -05005427 mNetIdToAllowlist.remove(nai.network.getNetId());
5428 mNetIdToDisallowedUids.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005429 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05005430 updateDisallowedUidsForNetwork(nai);
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005431 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005432 // Update allowed network lists in netd. This should be called after removing nai
5433 // from mNetworkAgentInfos.
5434 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005435 // Remove all previously satisfied requests.
5436 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005437 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005438 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005439 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005440 if (currentNetwork != null
5441 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005442 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005443 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5444 // rematch not to keep disconnected agents instead of setting it here ; this
5445 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005446 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005447 for (final NetworkOfferInfo noi : mNetworkOffers) {
5448 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005449 }
James Mattise3ef1912020-12-20 11:09:58 -08005450
Chalard Jean5b409c72021-02-04 13:12:59 +09005451 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005452 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005453 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005454 ensureNetworkTransitionWakelock(nai.toShortString());
5455 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005456 }
5457 }
junyulai2b6f0c22021-02-03 20:15:30 +08005458 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005459 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005460 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005461 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005462 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005463 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005464 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005465
Aaron Huang25ef1712021-06-08 13:11:45 +08005466 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5467 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5468 // not called by the rematch in this case. This is because the code above unset
5469 // this network from the default request's satisfier, and that is what the rematch
5470 // is using as its source data to know what the old satisfier was. So as far as the
5471 // rematch above is concerned, the old default network was null.
5472 // Therefore if there is no new default, the default network was null and is still
5473 // null, thus there was no change so makeDefault() is not called. So if the old
5474 // network had a proxy and there is no new default, the proxy tracker should be told
5475 // that there is no longer a default proxy.
5476 // Strictly speaking this is not essential because having a proxy setting when
5477 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5478 mProxyTracker.setDefaultProxy(null);
5479 }
5480
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005481 // Immediate teardown.
5482 if (nai.teardownDelayMs == 0) {
5483 destroyNetwork(nai);
5484 return;
5485 }
5486
5487 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005488 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305489 try {
5490 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5491 } catch (RemoteException e) {
5492 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5493 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005494 }
5495 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5496 }
5497
5498 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005499 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005500 // Tell netd to clean up the configuration for this network
5501 // (routing rules, DNS, etc).
5502 // This may be slow as it requires a lot of netd shelling out to ip and
5503 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005504 // after we've rematched networks with requests (which might change the default
5505 // network or service a new request from an app), so network traffic isn't interrupted
5506 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005507 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005508 }
Chalard Jean03552c42023-05-29 17:02:43 +09005509 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005510 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5511 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5512 // false if the network was never created.
5513 // TODO: delete when S is no longer supported.
5514 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005515 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005516 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005517 }
5518
Chalard Jean1e4c2182023-10-06 18:45:53 +09005519 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005520 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005521 // Step 1 : maybe this network was the upstream for one or more local networks.
5522 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5523 if (!local.isLocalNetwork()) continue;
5524 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5525 if (null == selector) continue;
5526 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5527 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5528 // called after removing all associated NRIs from mNetworkRequests.
5529 if (null == nri) continue;
5530 final NetworkAgentInfo satisfier = nri.getSatisfier();
5531 if (disconnecting != satisfier) continue;
5532 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005533 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5534 // correctly contains null as an upstream.
5535 if (sendCallbacks) {
5536 nri.setSatisfier(null, null);
5537 notifyNetworkCallbacks(local,
5538 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5539 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005540 }
5541
5542 // Step 2 : maybe this is a local network that had an upstream.
5543 if (!disconnecting.isLocalNetwork()) return;
5544 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5545 if (null == selector) return;
5546 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5547 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5548 // is called after removing all associated NRIs from mNetworkRequests.
5549 if (null == nri) return;
5550 final NetworkAgentInfo satisfier = nri.getSatisfier();
5551 if (null == satisfier) return;
5552 removeLocalNetworkUpstream(disconnecting, satisfier);
5553 }
5554
5555 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5556 @NonNull final NetworkAgentInfo upstream) {
5557 try {
5558 mRoutingCoordinatorService.removeInterfaceForward(
5559 localAgent.linkProperties.getInterfaceName(),
5560 upstream.linkProperties.getInterfaceName());
5561 } catch (RemoteException e) {
5562 loge("Couldn't remove interface forward for "
5563 + localAgent.linkProperties.getInterfaceName() + " to "
5564 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5565 }
5566 }
5567
Ken Chen6df7a902021-04-09 15:08:42 +08005568 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005569 try {
5570 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005571 final NativeNetworkConfig config;
5572 if (nai.isVPN()) {
5573 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005574 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005575 return false;
5576 }
5577 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5578 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005579 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005580 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005581 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005582 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005583 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5584 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005585 getNetworkPermission(nai.networkCapabilities),
5586 false /* secure */,
5587 VpnManager.TYPE_VPN_NONE,
5588 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005589 }
Ken Chen6df7a902021-04-09 15:08:42 +08005590 mNetd.networkCreate(config);
5591 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005592 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5593 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005594 return true;
5595 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005596 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005597 return false;
5598 }
5599 }
5600
Ken Chen6df7a902021-04-09 15:08:42 +08005601 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005602 if (mDscpPolicyTracker != null) {
5603 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5604 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005605 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005606 // the interface is going to go away. Don't send the callbacks however ; if the network
5607 // was is being disconnected the callbacks have already been sent, and if it is being
5608 // destroyed pending replacement they will be sent when it is disconnected.
5609 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005610 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005611 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005612 } catch (RemoteException | ServiceSpecificException e) {
5613 loge("Exception destroying network(networkDestroy): " + e);
5614 }
5615 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005616 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005617 } catch (RemoteException | ServiceSpecificException e) {
5618 loge("Exception destroying network: " + e);
5619 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005620 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5621 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5622 // gets created, could add data to DnsManager data structures that will never get deleted.
5623 mDnsManager.removeNetwork(nai.network);
5624
5625 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005626 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005627 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5628 }
5629
Chalard Jean254bd162022-08-25 13:04:51 +09005630 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005631 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005632 }
5633
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005634 // If this method proves to be too slow then we can maintain a separate
5635 // pendingIntent => NetworkRequestInfo map.
5636 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5637 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005638 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5639 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5640 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005641 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005642 return entry.getValue();
5643 }
5644 }
5645 return null;
5646 }
5647
Chalard Jean524f0b12021-10-25 21:11:56 +09005648 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jean03552c42023-05-29 17:02:43 +09005649 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005650 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5651 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5652 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5653 // bug is fixed.
5654 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005655 throw new IllegalStateException("This NRI is already registered. New : " + nri
5656 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005657 }
5658 }
5659 }
5660 }
5661
Chalard Jeanac9ace02022-01-26 16:54:05 +09005662 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5663 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005664 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09005665 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09005666 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005667 }
5668 return false;
5669 }
5670
James Mattisf7027322020-12-13 16:28:14 -08005671 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005672 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005673 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5674 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5675 final NetworkRequestInfo existingRequest =
5676 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005677 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005678 if (DBG) {
5679 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5680 + nri.mRequests.get(0) + " because their intents matched.");
5681 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005682 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005683 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005684 }
Erik Kline05f2b402015-04-30 12:58:40 +09005685 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005686 }
5687
James Mattisf7027322020-12-13 16:28:14 -08005688 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005689 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005690 }
5691
James Mattis3ce3d3c2021-02-09 18:18:28 -08005692 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005693 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005694 for (final NetworkRequestInfo nri : nris) {
5695 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005696 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005697 for (final NetworkRequest req : nri.mRequests) {
5698 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005699 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005700 if (req.isListen()) {
5701 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5702 if (req.networkCapabilities.hasSignalStrength()
5703 && network.satisfiesImmutableCapabilitiesOf(req)) {
5704 updateSignalStrengthThresholds(network, "REGISTER", req);
5705 }
James Mattisf7027322020-12-13 16:28:14 -08005706 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005707 }
5708 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005709
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005710 // If this NRI has a satisfier already, it is replacing an older request that
5711 // has been removed. Track it.
5712 final NetworkRequest activeRequest = nri.getActiveRequest();
5713 if (null != activeRequest) {
5714 // If there is an active request, then for sure there is a satisfier.
5715 nri.getSatisfier().addRequest(activeRequest);
5716 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005717 }
James Mattisf7027322020-12-13 16:28:14 -08005718
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005719 if (mFlags.noRematchAllRequestsOnRegister()) {
5720 rematchNetworksAndRequests(nris);
5721 } else {
5722 rematchAllNetworksAndRequests();
5723 }
James Mattis45d81842021-01-10 14:24:24 -08005724
Chalard Jean0354d8c2021-01-12 10:58:56 +09005725 // Requests that have not been matched to a network will not have been sent to the
5726 // providers, because the old satisfier and the new satisfier are the same (null in this
5727 // case). Send these requests to the providers.
5728 for (final NetworkRequestInfo nri : nris) {
5729 for (final NetworkOfferInfo noi : mNetworkOffers) {
5730 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005731 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005732 }
5733 }
5734
James Mattisf7027322020-12-13 16:28:14 -08005735 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5736 final int callingUid) {
5737 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005738 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005739 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5740 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5741 handleReleaseNetworkRequest(
5742 nri.mRequests.get(0),
5743 callingUid,
5744 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005745 }
5746 }
5747
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005748 // Determines whether the network is the best (or could become the best, if it validated), for
5749 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5750 // on the value of reason:
5751 //
5752 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5753 // then it should be torn down.
5754 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5755 // then it should be lingered.
5756 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005757 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005758
Chalard Jean254bd162022-08-25 13:04:51 +09005759 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005760 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5761 return false;
5762 }
5763
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005764 final int numRequests;
5765 switch (reason) {
5766 case TEARDOWN:
5767 numRequests = nai.numRequestNetworkRequests();
5768 break;
5769 case LINGER:
5770 numRequests = nai.numForegroundNetworkRequests();
5771 break;
5772 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005773 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005774 return true;
5775 }
5776
Chalard Jean947acd42021-03-08 22:29:27 +09005777 if (numRequests > 0) return false;
5778
Paul Jensende49eb12015-06-25 15:30:08 -04005779 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005780 if (reason == UnneededFor.LINGER
5781 && !nri.isMultilayerRequest()
5782 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005783 // Background requests don't affect lingering.
5784 continue;
5785 }
5786
James Mattis3d229892020-11-16 16:46:28 -08005787 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005788 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005789 }
5790 }
Paul Jensende49eb12015-06-25 15:30:08 -04005791 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005792 }
5793
James Mattis3d229892020-11-16 16:46:28 -08005794 private boolean isNetworkPotentialSatisfier(
5795 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005796 // While destroyed network sometimes satisfy requests (including occasionally newly
5797 // satisfying requests), *potential* satisfiers are networks that might beat a current
5798 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5799 // because it's never a good idea to keep a destroyed network in case it validates.
5800 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5801 // candidate after it's been replaced by another unvalidated network.
5802 if (candidate.isDestroyed()) return false;
5803 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005804 // request, return immediately. For multilayer requests, check to see if any of the
5805 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005806 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5807 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005808 return false;
5809 }
5810 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005811 // This multilayer listen request is satisfied therefore no further requests need to be
5812 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005813 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005814 return false;
5815 }
James Mattis3d229892020-11-16 16:46:28 -08005816 // As non-multilayer listen requests have already returned, the below would only happen
5817 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005818 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005819 continue;
5820 }
Chalard Jean80685f42023-10-30 18:31:27 +09005821 // If there is hope for this network might validate and subsequently become the best
5822 // network for that request, then it is needed. Note that this network can't already
5823 // be the best for this request, or it would be the current satisfier, and therefore
5824 // there would be no need to call this method to find out if it is a *potential*
5825 // satisfier ("unneeded", the only caller, only calls this if this network currently
5826 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005827 if (candidate.satisfies(req)) {
5828 // As soon as a network is found that satisfies a request, return. Specifically for
5829 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5830 // is important so as to not evaluate lower priority requests further in
5831 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005832 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5833 ? nri.getSatisfier() : null;
5834 // Note that this catches two important cases:
5835 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5836 // is currently satisfying the request. This is desirable when
5837 // cellular ends up validating but WiFi does not.
5838 // 2. Unvalidated WiFi will not be reaped when validated cellular
5839 // is currently satisfying the request. This is desirable when
5840 // WiFi ends up validating and out scoring cellular.
5841 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005842 }
5843 }
5844
5845 return false;
5846 }
5847
Erik Kline0c04b742016-07-07 16:50:58 +09005848 private NetworkRequestInfo getNriForAppRequest(
5849 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005850 // Looking up the app passed param request in mRequests isn't possible since it may return
5851 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5852 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005853 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5854 // to avoid potential race conditions when validating a package->uid mapping when sending
5855 // the callback on the very low-chance that an application shuts down prior to the callback
5856 // being sent.
5857 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5858 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005859
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005860 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005861 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005862 log(String.format("UID %d attempted to %s for unowned request %s",
5863 callingUid, requestedOperation, nri));
5864 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005865 }
Erik Kline0c04b742016-07-07 16:50:58 +09005866 }
5867
5868 return nri;
5869 }
5870
James Mattisf7027322020-12-13 16:28:14 -08005871 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5872 final String callingMethod) {
5873 if (nri.isMultilayerRequest()) {
5874 throw new IllegalStateException(
5875 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005876 }
5877 }
5878
James Mattisf7027322020-12-13 16:28:14 -08005879 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005880 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005881 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5882 // single NetworkRequest and thus does not apply to multilayer requests.
5883 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5884 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005885 return;
5886 }
James Mattis2516da32021-01-31 17:06:19 -08005887 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005888 return;
5889 }
James Mattisf7027322020-12-13 16:28:14 -08005890 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5891 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005892 }
5893 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005894 callCallbackForRequest(
5895 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005896 }
5897
James Mattisf7027322020-12-13 16:28:14 -08005898 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5899 final int callingUid,
5900 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005901 final NetworkRequestInfo nri =
5902 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5903 if (nri == null) {
5904 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005905 }
James Mattisf7027322020-12-13 16:28:14 -08005906 if (VDBG || (DBG && request.isRequest())) {
5907 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005908 }
5909 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005910 if (callOnUnavailable) {
5911 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5912 }
Erik Kline155a59a2015-11-25 12:49:38 +09005913 }
Erik Kline0c04b742016-07-07 16:50:58 +09005914
James Mattisa076c532020-12-02 14:12:41 -08005915 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005916 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005917 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005918 if (null == mNetworkRequests.remove(req)) {
5919 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5920 continue;
5921 }
James Mattisa076c532020-12-02 14:12:41 -08005922 if (req.isListen()) {
5923 removeListenRequestFromNetworks(req);
5924 }
5925 }
James Mattis8f036802021-06-20 16:26:01 -07005926 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005927 if (mDefaultNetworkRequests.remove(nri)) {
5928 // If this request was one of the defaults, then the UID rules need to be updated
5929 // WARNING : if the app(s) for which this network request is the default are doing
5930 // traffic, this will kill their connected sockets, even if an equivalent request
5931 // is going to be reinstated right away ; unconnected traffic will go on the default
5932 // until the new default is set, which will happen very soon.
5933 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5934 // remove ranges for those requests that won't have a replacement
5935 final NetworkAgentInfo satisfier = nri.getSatisfier();
5936 if (null != satisfier) {
5937 try {
paulhu0e79d952021-06-09 16:11:35 +08005938 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5939 satisfier.network.getNetId(),
5940 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005941 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005942 } catch (RemoteException e) {
5943 loge("Exception setting network preference default network", e);
5944 }
5945 }
5946 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005947
Junyu Lai00d92df2022-07-05 11:01:52 +08005948 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005949 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005950 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005951
5952 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005953 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005954 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005955 }
5956 }
5957
Chalard Jean0354d8c2021-01-12 10:58:56 +09005958 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5959 // needed for this offer.
5960 for (final NetworkOfferInfo noi : mNetworkOffers) {
5961 for (final NetworkRequest req : nri.mRequests) {
5962 if (req.isRequest() && noi.offer.neededFor(req)) {
5963 noi.offer.onNetworkUnneeded(req);
5964 }
5965 }
5966 }
James Mattisa076c532020-12-02 14:12:41 -08005967 }
5968
James Mattis3ce3d3c2021-02-09 18:18:28 -08005969 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5970 for (final NetworkRequestInfo nri : nris) {
5971 if (mDefaultRequest == nri) {
5972 // Make sure we never remove the default request.
5973 continue;
5974 }
5975 handleRemoveNetworkRequest(nri);
5976 }
5977 }
5978
James Mattisa076c532020-12-02 14:12:41 -08005979 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5980 // listens don't have a singular affected Network. Check all networks to see
5981 // if this listen request applies and remove it.
5982 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5983 nai.removeRequest(req.requestId);
5984 if (req.networkCapabilities.hasSignalStrength()
5985 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5986 updateSignalStrengthThresholds(nai, "RELEASE", req);
5987 }
5988 }
5989 }
5990
5991 /**
5992 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5993 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5994 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5995 */
5996 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5997 boolean wasKept = false;
5998 final NetworkAgentInfo nai = nri.getSatisfier();
5999 if (nai != null) {
6000 final int requestLegacyType = nri.getActiveRequest().legacyType;
6001 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
6002 nai.removeRequest(nri.getActiveRequest().requestId);
6003 if (VDBG || DDBG) {
6004 log(" Removing from current network " + nai.toShortString()
6005 + ", leaving " + nai.numNetworkRequests() + " requests.");
6006 }
6007 // If there are still lingered requests on this network, don't tear it down,
6008 // but resume lingering instead.
6009 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08006010 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08006011 notifyNetworkLosing(nai, now);
6012 }
6013 if (unneeded(nai, UnneededFor.TEARDOWN)) {
6014 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
6015 teardownUnneededNetwork(nai);
6016 } else {
6017 wasKept = true;
6018 }
James Mattisa076c532020-12-02 14:12:41 -08006019 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
6020 // Went from foreground to background.
6021 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09006022 }
6023
Erik Kline0c04b742016-07-07 16:50:58 +09006024 // Maintain the illusion. When this request arrived, we might have pretended
6025 // that a network connected to serve it, even though the network was already
6026 // connected. Now that this request has gone away, we might have to pretend
6027 // that the network disconnected. LegacyTypeTracker will generate that
6028 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08006029 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09006030 boolean doRemove = true;
6031 if (wasKept) {
6032 // check if any of the remaining requests for this network are for the
6033 // same legacy type - if so, don't remove the nai
6034 for (int i = 0; i < nai.numNetworkRequests(); i++) {
6035 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08006036 if (otherRequest.legacyType == requestLegacyType
6037 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09006038 if (DBG) log(" still have other legacy request - leaving");
6039 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08006040 }
6041 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07006042 }
6043
Erik Kline0c04b742016-07-07 16:50:58 +09006044 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08006045 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09006046 }
6047 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006048 }
6049 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006050
Junyu Lai00d92df2022-07-05 11:01:52 +08006051 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08006052 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09006053 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
6054 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
6055 }
6056
Lorenzo Colittid6459092016-07-04 12:55:44 +09006057 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006058 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08006059 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006060 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09006061 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006062 }
6063
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006064 @Override
lucaslin2240ef62019-03-12 13:08:03 +08006065 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
6066 enforceNetworkStackSettingsOrSetup();
6067 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
6068 encodeBool(accept), encodeBool(always), network));
6069 }
6070
6071 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006072 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08006073 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006074 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
6075 }
6076
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006077 @Override
6078 public void setTestAllowBadWifiUntil(long timeMs) {
6079 enforceSettingsPermission();
6080 if (!Build.isDebuggable()) {
6081 throw new IllegalStateException("Does not support in non-debuggable build");
6082 }
6083
6084 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
6085 throw new IllegalArgumentException("It should not exceed "
6086 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
6087 }
6088
6089 mHandler.sendMessage(
6090 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
6091 }
6092
chiachangwange0192a72023-02-06 13:25:01 +00006093 @Override
6094 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
6095 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00006096
6097 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
6098 throw new IllegalArgumentException("Argument should not exceed "
6099 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
6100 }
6101
6102 mHandler.sendMessage(
6103 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
6104 }
6105
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006106 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
6107 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
6108 " accept=" + accept + " always=" + always);
6109
6110 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6111 if (nai == null) {
6112 // Nothing to do.
6113 return;
6114 }
6115
Chalard Jean254bd162022-08-25 13:04:51 +09006116 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09006117 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006118 return;
6119 }
6120
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006121 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08006122 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006123 }
6124
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006125 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
6126 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08006127 // If network becomes partial connectivity and user already accepted to use this
6128 // network, we should respect the user's option and don't need to popup the
6129 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006130 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09006131 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09006132 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006133 }
6134
6135 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006136 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006137 }
6138
Lorenzo Colitti74baf412015-05-21 16:17:05 +09006139 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04006140 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006141 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09006142 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04006143 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09006144 }
6145
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006146 }
6147
lucaslin2240ef62019-03-12 13:08:03 +08006148 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
6149 boolean always) {
6150 if (DBG) {
6151 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
6152 + " always=" + always);
6153 }
6154
6155 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6156 if (nai == null) {
6157 // Nothing to do.
6158 return;
6159 }
6160
Chalard Jean254bd162022-08-25 13:04:51 +09006161 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08006162 // The network validated while the dialog box was up. Take no action.
6163 return;
6164 }
6165
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006166 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
6167 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08006168 }
6169
6170 // TODO: Use the current design or save the user choice into IpMemoryStore.
6171 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006172 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08006173 }
6174
6175 if (!accept) {
6176 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006177 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08006178 // Tear down the network.
6179 teardownUnneededNetwork(nai);
6180 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08006181 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
6182 // result in a partial connectivity result which will be processed by
6183 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08006184 //
6185 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
6186 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006187 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08006188 }
6189 }
6190
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006191 private void handleSetAvoidUnvalidated(Network network) {
6192 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09006193 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006194 // Nothing to do. The network either disconnected or revalidated.
6195 return;
6196 }
Chalard Jean254bd162022-08-25 13:04:51 +09006197 if (0L == nai.getAvoidUnvalidated()) {
6198 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09006199 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09006200 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006201 }
6202 }
6203
Chalard Jean5fb43c72022-09-08 19:03:14 +09006204 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09006205 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09006206 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean1f2b50f2023-05-15 17:26:13 +09006207 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006208 }
6209
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09006210 @Override
6211 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08006212 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09006213 mHandler.post(() -> {
6214 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6215 if (nai == null) return;
6216 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006217 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09006218 });
6219 }
6220
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09006221 /**
6222 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
6223 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006224 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09006225 * @param appExtras Bundle to use as intent extras for the captive portal application.
6226 * Must be treated as opaque to avoid preventing the captive portal app to
6227 * update its arguments.
6228 */
6229 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006230 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08006231 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
6232 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09006233
6234 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
6235 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006236 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
6237 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09006238 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
6239
lucaslin75ff7022020-12-17 04:14:35 +08006240 final long token = Binder.clearCallingIdentity();
6241 try {
6242 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
6243 } finally {
6244 Binder.restoreCallingIdentity(token);
6245 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09006246 }
6247
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006248 private class CaptivePortalImpl extends ICaptivePortal.Stub {
6249 private final Network mNetwork;
6250
6251 private CaptivePortalImpl(Network network) {
6252 mNetwork = network;
6253 }
6254
6255 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006256 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006257 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
6258 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00006259 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
6260 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
6261 // Since the network will be disconnected, skip notifying NetworkMonitor
6262 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006263 }
6264
Chiachang Wang938bfba2020-01-09 13:50:55 +08006265 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006266 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006267 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006268 }
6269
6270 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08006271 public void appRequest(final int request) {
6272 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
6273 if (nm == null) return;
6274
6275 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08006276 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006277 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08006278 }
6279 }
6280
6281 @Nullable
6282 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
6283 // getNetworkAgentInfoForNetwork is thread-safe
6284 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6285 if (nai == null) return null;
6286
6287 // nai.networkMonitor() is thread-safe
6288 return nai.networkMonitor();
6289 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006290 }
6291
Hugo Benichic9048bc2016-09-14 23:23:08 +00006292 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006293 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09006294 }
6295
Chalard Jean020b93a2022-09-01 13:20:14 +09006296 private boolean activelyPreferBadWifi() {
6297 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
6298 }
6299
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09006300 /**
6301 * Return whether the device should maintain continuous, working connectivity by switching away
6302 * from WiFi networks having no connectivity.
6303 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
6304 */
6305 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09006306 if (!checkNetworkStackPermission()) {
6307 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
6308 }
6309 return avoidBadWifi();
6310 }
6311
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006312 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09006313 ensureRunningOnConnectivityServiceThread();
6314 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09006315 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006316 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09006317 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09006318 if (avoidBadWifi) {
6319 // If the device is now avoiding bad wifi, remove notifications that might have
6320 // been put up when the device didn't.
6321 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
6322 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006323 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09006324 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
6325 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
6326 for (final NetworkOfferInfo noi : offersToUpdate) {
6327 updateOfferScore(noi.offer);
6328 }
Chalard Jean020b93a2022-09-01 13:20:14 +09006329 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09006330 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006331 }
6332
Erik Kline95ecfee2016-10-02 18:02:14 +09006333 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006334 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006335 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006336 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006337 if (!configRestrict) {
6338 pw.println("Bad Wi-Fi avoidance: unrestricted");
6339 return;
6340 }
6341
6342 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
6343 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09006344 pw.println("Config restrict: " + configRestrict);
6345 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006346
Chalard Jeane0fdea32022-09-14 21:44:22 +09006347 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006348 String description;
6349 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09006350 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006351 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006352 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006353 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006354 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006355 description = "avoid";
6356 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09006357 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006358 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09006359 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00006360
6361 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
6362 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09006363 if (null == configValue) {
6364 description = "unset";
6365 } else if (configValue) {
6366 description = "force true";
6367 } else {
6368 description = "force false";
6369 }
6370 pw.println("Actively prefer bad wifi conf: " + description);
6371 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006372 pw.println("Network overrides:");
6373 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09006374 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09006375 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09006376 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006377 }
6378 }
6379 pw.decreaseIndent();
6380 pw.decreaseIndent();
6381 }
6382
paulhu7746e4e2020-06-09 19:07:03 +08006383 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
6384 // unify the method.
6385 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
6386 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
6387 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
6388 return settingsComponent != null
6389 ? settingsComponent.getPackageName() : "com.android.settings";
6390 }
6391
lucaslinb1e8e382019-01-24 15:55:30 +08006392 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006393 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006394 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006395 switch (type) {
6396 case NO_INTERNET:
6397 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006398 // High priority because it is only displayed for explicitly selected networks.
6399 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006400 break;
lucasline117e2e2019-10-22 18:27:33 +08006401 case PRIVATE_DNS_BROKEN:
6402 action = Settings.ACTION_WIRELESS_SETTINGS;
6403 // High priority because we should let user know why there is no internet.
6404 highPriority = true;
6405 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006406 case LOST_INTERNET:
6407 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006408 // High priority because it could help the user avoid unexpected data usage.
6409 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006410 break;
lucaslin2240ef62019-03-12 13:08:03 +08006411 case PARTIAL_CONNECTIVITY:
6412 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006413 // Don't bother the user with a high-priority notification if the network was not
6414 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006415 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006416 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006417 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006418 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006419 return;
6420 }
6421
6422 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006423 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006424 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006425 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006426 // Some OEMs have their own Settings package. Thus, need to get the current using
6427 // Settings package name instead of just use default name "com.android.settings".
6428 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6429 intent.setClassName(settingsPkgName,
6430 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006431 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006432
paulhu2af50222020-10-11 22:52:27 +08006433 PendingIntent pendingIntent = PendingIntent.getActivity(
6434 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006435 0 /* requestCode */,
6436 intent,
paulhu2af50222020-10-11 22:52:27 +08006437 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006438
Serik Beketayevec8ad212020-12-07 22:43:07 -08006439 mNotifier.showNotification(
6440 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006441 }
6442
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006443 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6444 // Don't prompt if the network is validated, and don't prompt on captive portals
6445 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006446 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006447 return false;
6448 }
6449
6450 // If a network has partial connectivity, always prompt unless the user has already accepted
6451 // partial connectivity and selected don't ask again. This ensures that if the device
6452 // automatically connects to a network that has partial Internet access, the user will
6453 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006454 // because we have prompted them.
6455 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006456 return true;
6457 }
6458
6459 // If a network has no Internet access, only prompt if the network was explicitly selected
6460 // and if the user has not already told us to use the network regardless of whether it
6461 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006462 if (nai.networkAgentConfig.explicitlySelected
6463 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006464 return true;
6465 }
6466
6467 return false;
6468 }
6469
Chalard Jean5fb43c72022-09-08 19:03:14 +09006470 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6471 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006472
Chalard Jean5fb43c72022-09-08 19:03:14 +09006473 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6474 if (null == nai) return;
6475
6476 if (nai.setEvaluated()) {
6477 // If setEvaluated() returned true, the network never had any form of connectivity.
6478 // This may have an impact on request matching if bad WiFi avoidance is off and the
6479 // network was found not to have Internet access.
6480 nai.updateScoreForNetworkAgentUpdate();
6481 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006482
6483 // Also, if this is WiFi and it should be preferred actively, now is the time to
6484 // prompt the user that they walked past and connected to a bad WiFi.
6485 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6486 && !avoidBadWifi()
6487 && activelyPreferBadWifi()) {
6488 // The notification will be removed if the network validates or disconnects.
6489 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6490 return;
6491 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006492 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006493
Chalard Jean5fb43c72022-09-08 19:03:14 +09006494 if (!shouldPromptUnvalidated(nai)) return;
6495
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006496 // Stop automatically reconnecting to this network in the future. Automatically connecting
6497 // to a network that provides no or limited connectivity is not useful, because the user
6498 // cannot use that network except through the notification shown by this method, and the
6499 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006500 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006501
Chalard Jean254bd162022-08-25 13:04:51 +09006502 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006503 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006504 } else {
6505 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6506 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006507 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006508
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006509 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6510 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006511 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006512
lucaslin2240ef62019-03-12 13:08:03 +08006513 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6514 return;
6515 }
6516
6517 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006518 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006519 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006520 }
6521
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006522 @Override
6523 public int getMultipathPreference(Network network) {
6524 enforceAccessPermission();
6525
6526 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006527 if (nai != null && nai.networkCapabilities
6528 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006529 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6530 }
6531
Aaron Huang9a57acf2020-12-08 10:03:29 +08006532 final NetworkPolicyManager netPolicyManager =
6533 mContext.getSystemService(NetworkPolicyManager.class);
6534
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006535 final long token = Binder.clearCallingIdentity();
6536 final int networkPreference;
6537 try {
6538 networkPreference = netPolicyManager.getMultipathPreference(network);
6539 } finally {
6540 Binder.restoreCallingIdentity(token);
6541 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006542 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006543 return networkPreference;
6544 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006545 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6546 }
6547
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006548 @Override
6549 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006550 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006551 }
6552
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006553 private class InternalHandler extends Handler {
6554 public InternalHandler(Looper looper) {
6555 super(looper);
6556 }
6557
6558 @Override
6559 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006560 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006561 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006562 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006563 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006564 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006565 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006566 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006567 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006568 break;
6569 }
Aaron Huang25ef1712021-06-08 13:11:45 +08006570 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006571 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang25ef1712021-06-08 13:11:45 +08006572 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006573 break;
6574 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006575 case EVENT_REGISTER_NETWORK_PROVIDER: {
6576 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006577 break;
6578 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006579 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6580 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006581 break;
6582 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006583 case EVENT_REGISTER_NETWORK_OFFER: {
6584 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6585 break;
6586 }
6587 case EVENT_UNREGISTER_NETWORK_OFFER: {
6588 final NetworkOfferInfo offer =
6589 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6590 if (null != offer) {
6591 handleUnregisterNetworkOffer(offer);
6592 }
6593 break;
6594 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006595 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006596 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6597 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6598 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006599 break;
6600 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006601 case EVENT_REGISTER_NETWORK_REQUEST:
6602 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006603 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006604 break;
6605 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006606 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6607 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006608 handleRegisterNetworkRequestWithIntent(msg);
6609 break;
6610 }
Erik Kline155a59a2015-11-25 12:49:38 +09006611 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6612 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6613 handleTimedOutNetworkRequest(nri);
6614 break;
6615 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006616 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6617 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6618 break;
6619 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006620 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006621 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6622 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006623 break;
6624 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006625 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006626 Network network = (Network) msg.obj;
6627 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006628 break;
6629 }
lucaslin2240ef62019-03-12 13:08:03 +08006630 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6631 Network network = (Network) msg.obj;
6632 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6633 toBool(msg.arg2));
6634 break;
6635 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006636 case EVENT_SET_AVOID_UNVALIDATED: {
6637 handleSetAvoidUnvalidated((Network) msg.obj);
6638 break;
6639 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006640 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6641 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006642 break;
6643 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006644 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6645 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006646 break;
6647 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006648 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6649 // handler thread.
6650 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006651 mKeepaliveTracker.handleStartKeepalive(msg);
6652 break;
6653 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006654 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006655 final AutomaticOnOffKeepalive ki =
6656 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6657 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006658
chiachangwang676c84e2023-02-14 09:22:05 +00006659 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006660 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006661 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006662 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006663 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6664 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006665 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6666 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006667 }
6668 }
6669
6670 // If the network no longer exists, then the keepalive should have been
6671 // cleaned up already. There is no point trying to resume keepalives.
6672 if (!networkFound) return;
6673
chiachangwang676c84e2023-02-14 09:22:05 +00006674 if (underpinnedNetworkFound) {
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006675 final NetworkCapabilities underpinnedNc =
6676 getNetworkCapabilitiesInternal(underpinnedNetwork);
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006677 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006678 underpinnedNetwork.netId, underpinnedNc.getUids());
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006679 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006680 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006681 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006682 }
6683 break;
6684 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006685 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006686 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006687 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6688 (IBinder) msg.obj);
6689 if (ki == null) {
6690 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006691 return;
6692 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006693 final int reason = msg.arg2;
6694 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006695 break;
6696 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006697 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6698 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6699 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006700 break;
6701 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006702 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6703 handlePrivateDnsSettingsChanged();
6704 break;
dalyk1720e542018-03-05 12:42:22 -05006705 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6706 handlePrivateDnsValidationUpdate(
6707 (PrivateDnsValidationUpdate) msg.obj);
6708 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006709 case EVENT_UID_BLOCKED_REASON_CHANGED:
6710 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006711 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006712 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6713 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6714 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006715 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006716 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6717 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006718 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006719 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006720 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006721 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006722 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6723 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006724 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006725 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006726 }
lucaslin1193a5d2021-01-21 02:04:15 +08006727 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006728 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006729 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006730 break;
paulhu51f77dc2021-06-07 02:34:20 +00006731 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6732 handleMobileDataPreferredUidsChanged();
6733 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006734 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6735 final long timeMs = ((Long) msg.obj).longValue();
6736 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6737 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006738 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6739 handleIngressRateLimitChanged();
6740 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006741 case EVENT_USER_DOES_NOT_WANT:
6742 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6743 if (nai == null) break;
6744 nai.onPreventAutomaticReconnect();
Jean Chalard01a7d322023-06-27 08:54:23 +00006745 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006746 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006747 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6748 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6749 break;
chiachangwange0192a72023-02-06 13:25:01 +00006750 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6751 final long time = ((Long) msg.obj).longValue();
6752 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6753 break;
6754 }
Mark Fasheh7501e762023-05-04 20:23:11 +00006755 case EVENT_UID_FROZEN_STATE_CHANGED:
6756 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6757 handleFrozenUids(args.mUids, args.mFrozenStates);
6758 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006759 }
6760 }
6761 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006762
Lorenzo Colittid6459092016-07-04 12:55:44 +09006763 @Override
markchien5776f962019-12-16 20:15:20 +08006764 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006765 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006766 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006767 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6768 Context.TETHERING_SERVICE);
6769 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006770 }
6771
Lorenzo Colittid6459092016-07-04 12:55:44 +09006772 @Override
markchien5776f962019-12-16 20:15:20 +08006773 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006774 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006775 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006776 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6777 Context.TETHERING_SERVICE);
6778 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006779 }
6780
Lorenzo Colittid6459092016-07-04 12:55:44 +09006781 @Override
markchien5776f962019-12-16 20:15:20 +08006782 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006783 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006784 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006785 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6786 Context.TETHERING_SERVICE);
6787 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006788 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006789
markchien5776f962019-12-16 20:15:20 +08006790
Lorenzo Colittid6459092016-07-04 12:55:44 +09006791 @Override
markchien5776f962019-12-16 20:15:20 +08006792 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006793 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006794 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006795 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6796 Context.TETHERING_SERVICE);
6797
6798 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006799 }
6800
Lorenzo Colittid6459092016-07-04 12:55:44 +09006801 @Override
markchien5776f962019-12-16 20:15:20 +08006802 @Deprecated
6803 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006804 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006805 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6806 Context.TETHERING_SERVICE);
6807
6808 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006809 }
6810
Udam Saini8f7d6a72017-06-07 12:06:28 -07006811 @Override
markchien5776f962019-12-16 20:15:20 +08006812 @Deprecated
6813 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006814 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006815 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6816 Context.TETHERING_SERVICE);
6817 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006818 }
6819
Robert Greenwalte0b00512014-07-02 09:59:16 -07006820 // Called when we lose the default network and have no replacement yet.
6821 // This will automatically be cleared after X seconds or a new default network
6822 // becomes CONNECTED, whichever happens first. The timer is started by the
6823 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006824 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006825 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006826 if (mNetTransitionWakeLock.isHeld()) {
6827 return;
6828 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006829 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006830 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6831 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006832 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006833 mWakelockLogs.log("ACQUIRE for " + forWhom);
6834 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006835 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006836 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006837 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006838 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006839
Hugo Benichi471b62a2017-03-30 23:18:10 +09006840 // Called when we gain a new default network to release the network transition wakelock in a
6841 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6842 // message is cancelled.
6843 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006844 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006845 if (!mNetTransitionWakeLock.isHeld()) {
6846 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006847 }
6848 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006849 // Cancel self timeout on wakelock hold.
6850 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6851 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6852 mHandler.sendMessageDelayed(msg, 1000);
6853 }
6854
6855 // Called when either message of ensureNetworkTransitionWakelock or
6856 // scheduleReleaseNetworkTransitionWakelock is processed.
6857 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6858 String event = eventName(eventId);
6859 synchronized (this) {
6860 if (!mNetTransitionWakeLock.isHeld()) {
6861 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006862 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006863 return;
6864 }
6865 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006866 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6867 mTotalWakelockDurationMs += lockDuration;
6868 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6869 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006870 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006871 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006872 }
6873
Robert Greenwalt986c7412010-09-08 15:24:47 -07006874 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006875 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006876 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006877 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006878 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006879 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006880 }
6881
Lorenzo Colittid6459092016-07-04 12:55:44 +09006882 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006883 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006884 enforceAccessPermission();
6885 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006886 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006887 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006888
6889 final NetworkAgentInfo nai;
6890 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006891 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006892 } else {
6893 nai = getNetworkAgentInfoForNetwork(network);
6894 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006895
6896 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006897 mHandler.obtainMessage(
6898 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006899 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006900
Hugo Benichid6b510a2017-04-06 17:22:18 +09006901 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006902 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006903 if (nai == null
6904 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006905 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006906 return;
6907 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006908 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006909 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006910 mConnectivityDiagnosticsHandler.sendMessage(
6911 mConnectivityDiagnosticsHandler.obtainMessage(
6912 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6913 new ReportedNetworkConnectivityInfo(
6914 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006915 return;
6916 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006917 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006918 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006919 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006920 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006921 // Validating a network that has not yet connected could result in a call to
6922 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006923 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006924 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006925 }
paulhu7aeba372020-12-30 00:42:19 +08006926 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6927 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006928 return;
6929 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006930
6931 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6932 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6933 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6934 // completed.
6935 mConnectivityDiagnosticsHandler.sendMessage(
6936 mConnectivityDiagnosticsHandler.obtainMessage(
6937 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6938 new ReportedNetworkConnectivityInfo(
6939 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006940 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006941 }
6942
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006943 // TODO: call into netd.
6944 private boolean queryUserAccess(int uid, Network network) {
6945 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6946 if (nai == null) return false;
6947
6948 // Any UID can use its default network.
6949 if (nai == getDefaultNetworkForUid(uid)) return true;
6950
6951 // Privileged apps can use any network.
6952 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6953 return true;
6954 }
6955
6956 // An unprivileged UID can use a VPN iff the VPN applies to it.
6957 if (nai.isVPN()) {
6958 return nai.networkCapabilities.appliesToUid(uid);
6959 }
6960
6961 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6962 // sockets, i.e., if it is the owner.
6963 final NetworkAgentInfo vpn = getVpnForUid(uid);
6964 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6965 && uid != vpn.networkCapabilities.getOwnerUid()) {
6966 return false;
6967 }
6968
6969 // The UID's permission must be at least sufficient for the network. Since the restricted
6970 // permission was already checked above, that just leaves background networks.
6971 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6972 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6973 }
6974
6975 // Unrestricted network. Anyone gets to use it.
6976 return true;
6977 }
6978
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006979 /**
6980 * Returns information about the proxy a certain network is using. If given a null network, it
6981 * it will return the proxy for the bound network for the caller app or the default proxy if
6982 * none.
6983 *
6984 * @param network the network we want to get the proxy information for.
6985 * @return Proxy information if a network has a proxy configured, or otherwise null.
6986 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006987 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006988 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006989 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006990 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006991 if (network == null) {
6992 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006993 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006994 true);
6995 if (activeNetwork == null) {
6996 return null;
6997 }
6998 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006999 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00007000 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
7001 // caller may not have.
7002 return getLinkPropertiesProxyInfo(network);
7003 }
7004 // No proxy info available if the calling UID does not have network access.
7005 return null;
7006 }
7007
Irina Dumitrescude132bb2018-12-05 16:19:47 +00007008
7009 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04007010 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
7011 if (nai == null) return null;
7012 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00007013 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
7014 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04007015 }
7016 }
7017
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09007018 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09007019 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08007020 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09007021 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007022 }
7023
Chalard Jean777e2e52018-06-07 18:02:37 +09007024 @Override
7025 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04007026 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09007027 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007028 }
7029
Aaron Huang25ef1712021-06-08 13:11:45 +08007030 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09007031 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang25ef1712021-06-08 13:11:45 +08007032 final NetworkAgentInfo nai = getDefaultNetwork();
7033 // TODO : this method should check that net == nai.network, unfortunately at this point
7034 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
7035 // is only ever installed on the default network so in practice this is okay.
7036 if (null == nai) return;
7037 // PAC proxies only work on the default network. Therefore, only the default network
7038 // should have its link properties fixed up for PAC proxies.
7039 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
7040 if (nai.everConnected()) {
7041 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
7042 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007043 }
7044
Irina Dumitrescude132bb2018-12-05 16:19:47 +00007045 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
7046 // when any network changes proxy.
7047 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
7048 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08007049 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
7050 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05007051 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
7052
Chalard Jean7d97afc2018-06-07 17:41:29 +09007053 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09007054 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05007055 }
7056 }
7057
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007058 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09007059 final private HashMap<Uri, Integer> mUriEventMap;
7060 final private Context mContext;
7061 final private Handler mHandler;
7062
7063 SettingsObserver(Context context, Handler handler) {
7064 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007065 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09007066 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007067 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007068 }
7069
Erik Kline05f2b402015-04-30 12:58:40 +09007070 void observe(Uri uri, int what) {
7071 mUriEventMap.put(uri, what);
7072 final ContentResolver resolver = mContext.getContentResolver();
7073 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007074 }
7075
7076 @Override
7077 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08007078 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09007079 }
7080
7081 @Override
7082 public void onChange(boolean selfChange, Uri uri) {
7083 final Integer what = mUriEventMap.get(uri);
7084 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007085 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09007086 } else {
7087 loge("No matching event to send for URI=" + uri);
7088 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07007089 }
7090 }
Wink Savillee70c6f52010-12-03 12:01:38 -08007091
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07007092 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08007093 Log.d(TAG, s);
7094 }
7095
7096 private static void logw(String s) {
7097 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08007098 }
7099
Daniel Brightf9e945b2020-06-15 16:10:01 -07007100 private static void logwtf(String s) {
7101 Log.wtf(TAG, s);
7102 }
7103
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09007104 private static void logwtf(String s, Throwable t) {
7105 Log.wtf(TAG, s, t);
7106 }
7107
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07007108 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08007109 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08007110 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07007111
Hugo Benichi39621362017-02-11 17:04:43 +09007112 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08007113 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09007114 }
7115
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07007116 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08007117 * Return the information of all ongoing VPNs.
7118 *
7119 * <p>This method is used to update NetworkStatsService.
7120 *
7121 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08007122 */
junyulai2050bed2021-01-23 09:46:34 +08007123 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08007124 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09007125 if (mLockdownEnabled) {
7126 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08007127 }
junyulai2050bed2021-01-23 09:46:34 +08007128 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09007129 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08007130 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09007131 if (info != null) {
7132 infoList.add(info);
7133 }
7134 }
junyulai2050bed2021-01-23 09:46:34 +08007135 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08007136 }
7137
7138 /**
7139 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00007140 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08007141 */
junyulai2050bed2021-01-23 09:46:34 +08007142 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007143 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08007144 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
7145 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09007146 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
7147 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
7148 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08007149 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
7150 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00007151 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00007152 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08007153 }
7154 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007155
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007156 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007157
7158 List<String> interfaces = new ArrayList<>();
7159 for (Network network : underlyingNetworks) {
7160 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
7161 if (underlyingNai == null) continue;
7162 LinkProperties lp = underlyingNai.linkProperties;
7163 for (String iface : lp.getAllInterfaceNames()) {
7164 if (!TextUtils.isEmpty(iface)) {
7165 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00007166 }
7167 }
Benedict Wong34857f82019-06-12 17:46:15 +00007168 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007169
7170 if (interfaces.isEmpty()) return null;
7171
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007172 // Must be non-null or NetworkStatsService will crash.
7173 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
7174 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08007175 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08007176 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09007177
junyulai2050bed2021-01-23 09:46:34 +08007178 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
7179 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08007180 }
7181
James Mattisd31bdfa2020-12-23 16:37:26 -08007182 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08007183 private Network[] underlyingNetworksOrDefault(final int ownerUid,
7184 Network[] underlyingNetworks) {
7185 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007186 if (underlyingNetworks == null && defaultNetwork != null) {
7187 // null underlying networks means to track the default.
7188 underlyingNetworks = new Network[] { defaultNetwork };
7189 }
7190 return underlyingNetworks;
7191 }
7192
7193 // Returns true iff |network| is an underlying network of |nai|.
7194 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
7195 // TODO: support more than one level of underlying networks, either via a fixed-depth search
7196 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09007197 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08007198 final Network[] underlying = underlyingNetworksOrDefault(
7199 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007200 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007201 }
7202
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007203 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007204 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007205 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007206 * When underlying networks change, such networks may have to update capabilities to reflect
7207 * things like the metered bit, their transports, and so on. The capabilities are calculated
7208 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007209 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007210 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007211 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007212 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007213 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007214 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007215 }
7216 }
7217 }
7218
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007219 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
7220 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
7221 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
7222 // a VPN is not up.
7223 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
7224 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
7225 for (UidRange range : blockedUidRanges) {
7226 if (range.contains(uid)) return true;
7227 }
7228 return false;
7229 }
7230
7231 @Override
7232 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08007233 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007234 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
7235 encodeBool(requireVpn), 0 /* arg2 */, ranges));
7236 }
7237
7238 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
7239 if (DBG) {
7240 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
7241 + Arrays.toString(ranges));
7242 }
7243 // Cannot use a Set since the list of UID ranges might contain duplicates.
7244 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
7245 for (int i = 0; i < ranges.length; i++) {
7246 if (requireVpn) {
7247 newVpnBlockedUidRanges.add(ranges[i]);
7248 } else {
7249 newVpnBlockedUidRanges.remove(ranges[i]);
7250 }
7251 }
7252
7253 try {
7254 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
7255 } catch (RemoteException | ServiceSpecificException e) {
7256 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
7257 + Arrays.toString(ranges) + "): netd command failed: " + e);
7258 }
7259
Chalard Jean03552c42023-05-29 17:02:43 +09007260 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00007261 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
7262 }
7263
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007264 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
7265 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00007266 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
7267 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Oliver Scottb825c6f2022-10-27 23:52:45 +00007268
7269 if (nai.isVPN()) {
7270 updateVpnFiltering(nai.linkProperties, nai.linkProperties, nai, true /* force */);
7271 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007272 }
7273
7274 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
7275 }
7276
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07007277 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007278 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08007279 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007280 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01007281 }
7282
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007283 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
7284 return mLockdownEnabled
7285 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
7286 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00007287 }
7288
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007289 private NetworkAgentInfo getLegacyLockdownNai() {
7290 if (!mLockdownEnabled) {
7291 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00007292 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007293 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007294 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
7295 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00007296
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007297 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007298 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
7299 // a local variable. There is no need to make a copy because its contents cannot change.
7300 final Network[] underlying = nai.declaredUnderlyingNetworks;
7301 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007302 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007303 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007304
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007305 // The legacy lockdown VPN always uses the default network.
7306 // If the VPN's underlying network is no longer the current default network, it means that
7307 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007308 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
7309 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007310 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007311 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007312 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007313 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007314
7315 return nai;
7316 };
7317
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007318 // TODO: move all callers to filterForLegacyLockdown and delete this method.
7319 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
7320 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007321 private DetailedState getLegacyLockdownState(DetailedState origState) {
7322 if (origState != DetailedState.CONNECTED) {
7323 return origState;
7324 }
7325 return (mLockdownEnabled && getLegacyLockdownNai() == null)
7326 ? DetailedState.CONNECTING
7327 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007328 }
7329
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007330 private void filterForLegacyLockdown(NetworkInfo ni) {
7331 if (!mLockdownEnabled || !ni.isConnected()) return;
7332 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
7333 // state of its VPN. This is to ensure that when an underlying network connects, apps will
7334 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
7335 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
7336 // network, this time with a state of CONNECTED.
7337 //
7338 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
7339 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
7340 // is not too far off the truth, since an always-on VPN, when not connected, is always
7341 // trying to reconnect.
7342 if (getLegacyLockdownNai() == null) {
7343 ni.setDetailedState(DetailedState.CONNECTING, "", null);
7344 }
7345 }
7346
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007347 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07007348 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04007349 String action) {
paulhu8e96a752019-08-12 16:25:11 +08007350 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09007351 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
7352 return;
7353 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04007354 final long ident = Binder.clearCallingIdentity();
7355 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09007356 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007357 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09007358 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04007359 } finally {
7360 Binder.restoreCallingIdentity(ident);
7361 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07007362 }
Wink Savillecb117d32013-08-29 14:57:08 -07007363
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007364 @Override
7365 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01007366 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007367 final long ident = Binder.clearCallingIdentity();
7368 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007369 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09007370 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007371 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
7372 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08007373 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007374 } finally {
7375 Binder.restoreCallingIdentity(ident);
7376 }
7377 }
7378
James Mattis02220e22021-03-13 19:27:21 -08007379 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08007380 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7381 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7382 }
Chalard Jeane0abd522023-01-23 16:47:43 +09007383 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007384 }
7385
James Mattis02220e22021-03-13 19:27:21 -08007386 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09007387 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007388 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08007389 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
7390 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09007391 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08007392 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7393 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7394 }
junyulaid91e7052020-08-28 13:44:33 +08007395 }
7396
James Mattis02220e22021-03-13 19:27:21 -08007397 private void onPackageChanged(@NonNull final String packageName) {
7398 // This is necessary in case a package is added or removed, but also when it's replaced to
7399 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
7400 // as one in the preferences, then it should follow the same routing as that other package,
7401 // which means updating the rules is never to be needed in this case (whether it joins or
7402 // leaves a UID with a preference).
7403 if (isMappedInOemNetworkPreference(packageName)) {
7404 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7405 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007406
7407 // Invalidates cache entry when the package is updated.
7408 synchronized (mSelfCertifiedCapabilityCache) {
7409 mSelfCertifiedCapabilityCache.remove(packageName);
7410 }
James Mattis02220e22021-03-13 19:27:21 -08007411 }
7412
7413 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007414 @Override
7415 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007416 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007417 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007418 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007419
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007420 // User should be filled for below intents, check the existence.
7421 if (user == null) {
7422 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7423 return;
7424 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007425
Lorenzo Colitticd675292021-02-04 17:32:07 +09007426 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007427 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007428 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007429 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007430 } else {
junyulaid91e7052020-08-28 13:44:33 +08007431 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007432 }
7433 }
7434 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007435
James Mattis02220e22021-03-13 19:27:21 -08007436 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7437 @Override
7438 public void onReceive(Context context, Intent intent) {
7439 ensureRunningOnConnectivityServiceThread();
7440 switch (intent.getAction()) {
7441 case Intent.ACTION_PACKAGE_ADDED:
7442 case Intent.ACTION_PACKAGE_REMOVED:
7443 case Intent.ACTION_PACKAGE_REPLACED:
7444 onPackageChanged(intent.getData().getSchemeSpecificPart());
7445 break;
7446 default:
7447 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7448 }
7449 }
7450 };
7451
Junyu Lai38c75032023-12-04 07:52:19 +00007452 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
7453 private final BroadcastReceiver mDataSaverReceiver = new BroadcastReceiver() {
7454 @Override
7455 public void onReceive(Context context, Intent intent) {
7456 if (mDeps.isAtLeastV()) {
7457 throw new IllegalStateException(
7458 "data saver status should be updated from platform");
7459 }
7460 ensureRunningOnConnectivityServiceThread();
7461 switch (intent.getAction()) {
7462 case ACTION_RESTRICT_BACKGROUND_CHANGED:
7463 // If the uid is present in the deny list, the API will consistently
7464 // return ENABLED. To retrieve the global switch status, the system
7465 // uid is chosen because it will never be included in the deny list.
7466 final int dataSaverForSystemUid =
7467 mPolicyManager.getRestrictBackgroundStatus(Process.SYSTEM_UID);
7468 final boolean isDataSaverEnabled = (dataSaverForSystemUid
7469 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
7470 mBpfNetMaps.setDataSaverEnabled(isDataSaverEnabled);
7471 break;
7472 default:
7473 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7474 }
7475 }
7476 };
7477
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007478 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007479 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007480
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007481 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007482 public final String name;
7483 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007484 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007485 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007486
lifraf3a3492021-03-10 13:58:14 +08007487 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7488 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007489 this.name = name;
7490 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007491 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007492 mDeathRecipient = deathRecipient;
7493
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007494 if (mDeathRecipient == null) {
7495 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007496 }
7497 }
7498
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007499 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007500 try {
7501 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7502 } catch (RemoteException e) {
7503 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007504 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007505 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007506 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007507
James Mattis4fce5d12020-11-12 15:53:42 -08007508 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7509 for (int i = 0; i < requests.size(); i++) {
7510 ensureNetworkRequestHasType(requests.get(i));
7511 }
7512 }
7513
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007514 private void ensureNetworkRequestHasType(NetworkRequest request) {
7515 if (request.type == NetworkRequest.Type.NONE) {
7516 throw new IllegalArgumentException(
7517 "All NetworkRequests in ConnectivityService must have a type");
7518 }
7519 }
7520
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007521 /**
7522 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007523 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007524 */
James Mattis258ea3c2020-11-15 15:04:40 -08007525 @VisibleForTesting
7526 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007527 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7528 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007529 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007530
James Mattisa076c532020-12-02 14:12:41 -08007531 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7532 void setSatisfier(
7533 @Nullable final NetworkAgentInfo satisfier,
7534 @Nullable final NetworkRequest activeRequest) {
7535 mSatisfier = satisfier;
7536 mActiveRequest = activeRequest;
7537 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007538
James Mattisd31bdfa2020-12-23 16:37:26 -08007539 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007540 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007541 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007542 private NetworkAgentInfo mSatisfier;
7543 NetworkAgentInfo getSatisfier() {
7544 return mSatisfier;
7545 }
7546
7547 // The request in mRequests assigned to a network agent. This is null if none of the
7548 // requests in mRequests can be satisfied. This member has the constraint of only being
7549 // accessible on the handler thread.
7550 @Nullable
7551 private NetworkRequest mActiveRequest;
7552 NetworkRequest getActiveRequest() {
7553 return mActiveRequest;
7554 }
7555
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007556 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007557 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007558 @Nullable
7559 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007560
7561 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007562 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007563 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007564 final int mPid;
7565 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007566 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007567 @Nullable
7568 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007569
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007570 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007571 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007572
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007573 // Effective UID of this request. This is different from mUid when a privileged process
7574 // files a request on behalf of another UID. This UID is used to determine blocked status,
7575 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7576 // maximum limit of registered callbacks per UID.
7577 final int mAsUid;
7578
paulhu48291862021-07-14 14:53:57 +08007579 // Preference order of this request.
7580 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007581
James Mattis3ce3d3c2021-02-09 18:18:28 -08007582 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7583 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7584 // maintained for keying off of. This is only a concern when the original nri
7585 // mNetworkRequests changes which happens currently for apps that register callbacks to
7586 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7587 // that match the per-app default nri that currently tracks the calling app's uid so that
7588 // callbacks are fired at the appropriate time. When the callbacks fire,
7589 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7590 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7591 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7592 @NonNull
7593 private final NetworkRequest mNetworkRequestForCallback;
7594 NetworkRequest getNetworkRequestForCallback() {
7595 return mNetworkRequestForCallback;
7596 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007597
James Mattisd31bdfa2020-12-23 16:37:26 -08007598 /**
7599 * Get the list of UIDs this nri applies to.
7600 */
7601 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007602 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007603 // networkCapabilities.getUids() returns a defensive copy.
7604 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007605 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7606 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007607 }
7608
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007609 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7610 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007611 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007612 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007613 }
7614
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007615 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007616 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007617 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007618 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007619 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007620 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007621 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007622 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007623 mBinder = null;
7624 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007625 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007626 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007627 mPerUidCounter = getRequestCounter(this);
7628 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007629 /**
7630 * Location sensitive data not included in pending intent. Only included in
7631 * {@link NetworkCallback}.
7632 */
7633 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007634 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007635 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007636 }
7637
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007638 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007639 @Nullable final IBinder binder,
7640 @NetworkCallback.Flag int callbackFlags,
7641 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007642 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7643 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007644 }
7645
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007646 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007647 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007648 @Nullable final IBinder binder,
7649 @NetworkCallback.Flag int callbackFlags,
7650 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007651 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007652 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007653 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007654 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007655 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007656 mBinder = binder;
7657 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007658 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007659 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007660 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007661 mPerUidCounter = getRequestCounter(this);
7662 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007663 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007664 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007665 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007666 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007667 }
7668
James Mattis3ce3d3c2021-02-09 18:18:28 -08007669 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7670 @NonNull final List<NetworkRequest> r) {
7671 super();
7672 ensureAllNetworkRequestsHaveType(r);
7673 mRequests = initializeRequests(r);
7674 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007675 final NetworkAgentInfo satisfier = nri.getSatisfier();
7676 if (null != satisfier) {
7677 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7678 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007679 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007680 // As this code creates a new NRI with a new set of requests, figure out which of
7681 // the list of requests should be the active request. It is always the first
7682 // request of the list that can be satisfied by the satisfier since the order of
7683 // requests is a priority order.
7684 // Note even in the presence of a satisfier there may not be an active request,
7685 // when the satisfier is the no-service network.
7686 NetworkRequest activeRequest = null;
7687 for (final NetworkRequest candidate : r) {
7688 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7689 activeRequest = candidate;
7690 break;
7691 }
7692 }
7693 setSatisfier(satisfier, activeRequest);
7694 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007695 mMessenger = nri.mMessenger;
7696 mBinder = nri.mBinder;
7697 mPid = nri.mPid;
7698 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007699 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007700 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007701 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007702 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007703 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007704 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007705 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007706 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007707 }
7708
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007709 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007710 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007711 }
7712
paulhue9913722021-05-26 15:19:20 +08007713 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007714 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007715 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007716 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007717 }
7718
James Mattis2516da32021-01-31 17:06:19 -08007719 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7720 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7721 // false.
7722 boolean isBeingSatisfied() {
7723 return (null != mSatisfier && null != mActiveRequest);
7724 }
7725
James Mattis3d229892020-11-16 16:46:28 -08007726 boolean isMultilayerRequest() {
7727 return mRequests.size() > 1;
7728 }
7729
James Mattis45d81842021-01-10 14:24:24 -08007730 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7731 // Creating a defensive copy to prevent the sender from modifying the list being
7732 // reflected in the return value of this method.
7733 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007734 return Collections.unmodifiableList(tempRequests);
7735 }
7736
James Mattisb1392002021-03-31 13:57:52 -07007737 void linkDeathRecipient() {
7738 if (null != mBinder) {
7739 try {
7740 mBinder.linkToDeath(this, 0);
7741 } catch (RemoteException e) {
7742 binderDied();
7743 }
7744 }
7745 }
7746
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007747 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007748 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007749 try {
7750 mBinder.unlinkToDeath(this, 0);
7751 } catch (NoSuchElementException e) {
7752 // Temporary workaround for b/194394697 pending analysis of additional logs
7753 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7754 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007755 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007756 }
7757
paulhu48291862021-07-14 14:53:57 +08007758 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7759 // Compare two preference orders.
7760 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007761 }
7762
paulhu48291862021-07-14 14:53:57 +08007763 int getPreferenceOrderForNetd() {
7764 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7765 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7766 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007767 }
paulhu48291862021-07-14 14:53:57 +08007768 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007769 }
7770
James Mattis4fce5d12020-11-12 15:53:42 -08007771 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007772 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007773 // As an immutable collection, mRequests cannot change by the time the
7774 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7775 // is acceptable. Use handleReleaseNetworkRequest and not directly
7776 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7777 // the app already unregistered the request.
7778 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7779 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007780 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007781
James Mattis4fce5d12020-11-12 15:53:42 -08007782 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007783 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007784 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7785 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007786 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007787 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007788 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007789 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007790 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007791 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007792 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007793 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007794 }
7795
Junyu Lai00d92df2022-07-05 11:01:52 +08007796 // Keep backward compatibility since the ServiceSpecificException is used by
7797 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7798 public static class RequestInfoPerUidCounter extends PerUidCounter {
7799 RequestInfoPerUidCounter(int maxCountPerUid) {
7800 super(maxCountPerUid);
7801 }
7802
7803 @Override
7804 public synchronized void incrementCountOrThrow(int uid) {
7805 try {
7806 super.incrementCountOrThrow(uid);
7807 } catch (IllegalStateException e) {
7808 throw new ServiceSpecificException(
7809 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7810 "Uid " + uid + " exceeded its allotted requests limit");
7811 }
7812 }
7813
7814 @Override
7815 public synchronized void decrementCountOrThrow(int uid) {
7816 throw new UnsupportedOperationException("Use decrementCount instead.");
7817 }
7818
7819 public synchronized void decrementCount(int uid) {
7820 try {
7821 super.decrementCountOrThrow(uid);
7822 } catch (IllegalStateException e) {
7823 logwtf("Exception when decrement per uid request count: ", e);
7824 }
7825 }
7826 }
7827
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007828 // This checks that the passed capabilities either do not request a
7829 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007830 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007831 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007832 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007833 throw new SecurityException("Insufficient permissions to request a specific SSID");
7834 }
paulhu1a407652019-03-22 16:35:06 +08007835
7836 if (nc.hasSignalStrength()
7837 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7838 throw new SecurityException(
7839 "Insufficient permissions to request a specific signal strength");
7840 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007841 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007842
junyulai2217bec2021-04-14 23:33:31 +08007843 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007844 enforceNetworkFactoryPermission();
7845 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007846 }
7847
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007848 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007849 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007850 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007851 // mNetworkRequests may contain the same value multiple times in case of
7852 // multilayer requests. It won't matter in this case because the thresholds
7853 // will then be the same and be deduplicated as they enter the `thresholds` set.
7854 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007855 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7856 for (final NetworkRequest req : nri.mRequests) {
7857 if (req.networkCapabilities.hasSignalStrength()
7858 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7859 thresholds.add(req.networkCapabilities.getSignalStrength());
7860 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007861 }
7862 }
7863 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007864 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007865 }
7866
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007867 private void updateSignalStrengthThresholds(
7868 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007869 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007870
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007871 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007872 String detail;
7873 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7874 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7875 } else {
7876 detail = reason;
7877 }
7878 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007879 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007880 }
7881
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007882 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007883 }
7884
Chalard Jeandd421992021-12-16 23:16:02 +09007885 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007886 if (nc == null) {
7887 return;
7888 }
7889 NetworkSpecifier ns = nc.getNetworkSpecifier();
7890 if (ns == null) {
7891 return;
7892 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007893 if (ns instanceof MatchAllNetworkSpecifier) {
7894 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7895 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007896 }
7897
Chalard Jeandd421992021-12-16 23:16:02 +09007898 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007899 ensureValidNetworkSpecifier(nc);
7900 if (nc.isPrivateDnsBroken()) {
7901 throw new IllegalArgumentException("Can't request broken private DNS");
7902 }
Chalard Jeande665262022-02-25 16:12:12 +09007903 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007904 throw new IllegalArgumentException("Can't request access UIDs");
7905 }
lucasline117e2e2019-10-22 18:27:33 +08007906 }
7907
Chalard Jeandd421992021-12-16 23:16:02 +09007908 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7909 ensureListenableCapabilities(nc);
7910 final String badCapability = nc.describeFirstNonRequestableCapability();
7911 if (badCapability != null) {
7912 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7913 }
7914 }
7915
Chiachang Wang3bc52762021-11-25 14:17:57 +08007916 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7917 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007918 private boolean isTargetSdkAtleast(int version, int callingUid,
7919 @NonNull String callingPackageName) {
7920 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007921 final PackageManager pm =
7922 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007923 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007924 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007925 if (callingVersion < version) return false;
7926 } catch (PackageManager.NameNotFoundException e) { }
7927 return true;
7928 }
7929
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007930 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007931 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007932 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007933 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007934 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007935 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007936 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7937 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007938 throw new SecurityException("Insufficient permissions to specify legacy type");
7939 }
markchienfac84a22020-03-18 21:16:15 +08007940 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007941 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007942 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007943 // Privileged callers can track the default network of another UID by passing in a UID.
7944 if (asUid != Process.INVALID_UID) {
7945 enforceSettingsPermission();
7946 } else {
7947 asUid = callingUid;
7948 }
junyulaiad010792021-01-11 16:53:38 +08007949 final NetworkRequest.Type reqType;
7950 try {
7951 reqType = NetworkRequest.Type.values()[reqTypeInt];
7952 } catch (ArrayIndexOutOfBoundsException e) {
7953 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7954 }
7955 switch (reqType) {
7956 case TRACK_DEFAULT:
7957 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007958 // is unused and will be replaced by ones appropriate for the UID (usually, the
7959 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007960 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007961 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007962 enforceAccessPermission();
7963 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007964 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007965 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007966 networkCapabilities = new NetworkCapabilities(defaultNc);
7967 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007968 case BACKGROUND_REQUEST:
7969 enforceNetworkStackOrSettingsPermission();
7970 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007971 case REQUEST:
7972 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7973 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007974 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007975 // TODO: this is incorrect. We mark the request as metered or not depending on
7976 // the state of the app when the request is filed, but we never change the
7977 // request if the app changes network state. http://b/29964605
7978 enforceMeteredApnPolicy(networkCapabilities);
7979 break;
junyulai1b1c8742021-03-12 20:05:08 +08007980 case LISTEN_FOR_BEST:
7981 enforceAccessPermission();
7982 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7983 break;
junyulaiad010792021-01-11 16:53:38 +08007984 default:
7985 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007986 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007987 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007988 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007989 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007990
junyulai1b1c8742021-03-12 20:05:08 +08007991 // Enforce FOREGROUND if the caller does not have permission to use background network.
7992 if (reqType == LISTEN_FOR_BEST) {
7993 restrictBackgroundRequestForCaller(networkCapabilities);
7994 }
7995
7996 // Set the UID range for this request to the single UID of the requester, unless the
7997 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007998 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7999 // are no visible methods to set the UIDs, an app could use reflection to try and get
8000 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08008001 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08008002 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
8003 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07008004
Etan Cohen85000162017-02-05 10:42:27 -08008005 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008006 throw new IllegalArgumentException("Bad timeout specified");
8007 }
Etan Cohen9786d922015-11-18 10:56:15 -08008008
James Mattis3ce3d3c2021-02-09 18:18:28 -08008009 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08008010 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008011 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09008012 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008013 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09008014 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008015
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09008016 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
8017 // copied from the default request above. (This is necessary to ensure, for example, that
8018 // the callback does not leak sensitive information to unprivileged apps.) Check that the
8019 // changes don't alter request matching.
8020 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
8021 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09008022 throw new IllegalStateException(
8023 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09008024 + networkCapabilities + " vs. " + defaultNc);
8025 }
8026
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008027 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07008028 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008029 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07008030 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008031 }
8032 return networkRequest;
8033 }
8034
James Mattis3ce3d3c2021-02-09 18:18:28 -08008035 /**
8036 * Return the nri to be used when registering a network request. Specifically, this is used with
8037 * requests registered to track the default request. If there is currently a per-app default
8038 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
8039 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008040 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8041 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008042 * @param nr the network request for the nri.
8043 * @param msgr the messenger for the nri.
8044 * @param binder the binder for the nri.
8045 * @param callingAttributionTag the calling attribution tag for the nri.
8046 * @return the nri to register.
8047 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008048 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08008049 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08008050 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08008051 @Nullable String callingAttributionTag) {
8052 final List<NetworkRequest> requests;
8053 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
8054 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008055 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08008056 } else {
8057 requests = Collections.singletonList(nr);
8058 }
Roshan Pius951c0032020-12-22 15:10:42 -08008059 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008060 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008061 }
8062
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09008063 private boolean shouldCheckCapabilitiesDeclaration(
8064 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
8065 @NonNull final String callingPackageName) {
8066 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
8067 // Only run the check if the change is enabled.
8068 if (!mDeps.isChangeEnabled(
8069 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
8070 callingPackageName, user)) {
8071 return false;
8072 }
8073
8074 return networkCapabilities.hasCapability(
8075 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
8076 || networkCapabilities.hasCapability(
8077 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
8078 }
8079
8080 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09008081 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09008082 // This check is added to fix the linter error for "current min is 30", which is not going
8083 // to happen because Connectivity service always run in S+.
Chalard Jean03552c42023-05-29 17:02:43 +09008084 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09008085 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
8086 return;
8087 }
8088 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09008089 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09008090 try {
8091 synchronized (mSelfCertifiedCapabilityCache) {
8092 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
8093 callerPackageName);
8094 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09008095 final PackageManager packageManager =
8096 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
8097 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09008098 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
8099 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
8100 callerPackageName
8101 );
8102 final XmlResourceParser parser = packageManager
8103 .getResourcesForApplication(callerPackageName)
8104 .getXml(networkSliceProperty.getResourceId());
8105 applicationNetworkCapabilities =
8106 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
8107 mSelfCertifiedCapabilityCache.put(callerPackageName,
8108 applicationNetworkCapabilities);
8109 }
8110
8111 }
8112 } catch (PackageManager.NameNotFoundException ne) {
8113 throw new SecurityException(
8114 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
8115 + " property");
8116 } catch (XmlPullParserException | IOException | InvalidTagException e) {
8117 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09008118 } finally {
8119 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09008120 }
8121
8122 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
8123 networkCapabilities);
8124 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07008125 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08008126 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09008127 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
8128 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09008129 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
8130 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09008131 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09008132 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08008133 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
8134 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
8135 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
8136 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08008137 }
junyulai96bd9fe2022-03-08 17:36:42 +08008138 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008139 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07008140 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008141 }
8142 }
8143
fenglu3f357402015-03-20 11:29:56 -07008144 @Override
fenglub00f4882015-04-21 17:12:05 -07008145 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07008146 enforceAccessPermission();
8147 NetworkAgentInfo nai = null;
8148 if (network == null) {
8149 return false;
8150 }
8151 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008152 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07008153 }
8154 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008155 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07008156 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008157 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07008158 Integer uidReqs = mBandwidthRequests.get(uid);
8159 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008160 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07008161 }
8162 mBandwidthRequests.put(uid, ++uidReqs);
8163 }
fenglu3f357402015-03-20 11:29:56 -07008164 return true;
8165 }
8166 return false;
8167 }
8168
Felipe Leme0a5ae422016-06-20 16:36:29 -07008169 private boolean isSystem(int uid) {
8170 return uid < Process.FIRST_APPLICATION_UID;
8171 }
fenglu3f357402015-03-20 11:29:56 -07008172
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008173 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008174 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07008175 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09008176 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07008177 return;
8178 }
Hugo Benichi39621362017-02-11 17:04:43 +09008179 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
8180 // Policy already enforced.
8181 return;
8182 }
paulhuaf50d7d2020-12-24 19:47:34 +08008183 final long ident = Binder.clearCallingIdentity();
8184 try {
8185 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
8186 // If UID is restricted, don't allow them to bring up metered APNs.
8187 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
8188 }
8189 } finally {
8190 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008191 }
8192 }
8193
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008194 @Override
8195 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07008196 PendingIntent operation, @NonNull String callingPackageName,
8197 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00008198 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008199 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008200 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07008201 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08008202 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008203 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09008204 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008205 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08008206 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08008207 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
8208 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09008209
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008210 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09008211 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008212 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
8213 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09008214 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008215 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
8216 nri));
8217 return networkRequest;
8218 }
8219
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008220 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
8221 mHandler.sendMessageDelayed(
8222 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09008223 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008224 }
8225
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008226 @Override
8227 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00008228 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008229 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09008230 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008231 }
8232
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09008233 // In order to implement the compatibility measure for pre-M apps that call
8234 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
8235 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
8236 // This ensures it has permission to do so.
8237 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
8238 if (nc == null) {
8239 return false;
8240 }
8241 int[] transportTypes = nc.getTransportTypes();
8242 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
8243 return false;
8244 }
8245 try {
8246 mContext.enforceCallingOrSelfPermission(
8247 android.Manifest.permission.ACCESS_WIFI_STATE,
8248 "ConnectivityService");
8249 } catch (SecurityException e) {
8250 return false;
8251 }
8252 return true;
8253 }
8254
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008255 @Override
8256 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08008257 Messenger messenger, IBinder binder,
8258 @NetworkCallback.Flag int callbackFlags,
8259 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008260 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09008261 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
8262 enforceAccessPermission();
8263 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008264
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008265 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008266 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08008267 Binder.getCallingPid(), callingUid, callingPackageName);
8268 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09008269 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
8270 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
8271 // onLost and onAvailable callbacks when networks move in and out of the background.
8272 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
8273 // can't request networks.
8274 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09008275 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07008276
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008277 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09008278 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08008279 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008280 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08008281 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09008282 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008283
8284 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
8285 return networkRequest;
8286 }
8287
8288 @Override
8289 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08008290 PendingIntent operation, @NonNull String callingPackageName,
8291 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00008292 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008293 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04008294 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
8295 enforceAccessPermission();
8296 }
Chalard Jeandd421992021-12-16 23:16:02 +09008297 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008298 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08008299 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09008300 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08008301 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09008302
8303 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09008304 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008305 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
8306 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09008307 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04008308
WeiZhang1cc3f172021-06-03 19:02:04 -05008309 mHandler.sendMessage(mHandler.obtainMessage(
8310 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008311 }
8312
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008313 /** Returns the next Network provider ID. */
8314 public final int nextNetworkProviderId() {
8315 return mNextNetworkProviderId.getAndIncrement();
8316 }
8317
Erik Kline0c04b742016-07-07 16:50:58 +09008318 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008319 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09008320 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09008321 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09008322 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008323 }
8324
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008325 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
8326 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008327 // Avoid creating duplicates. even if an app makes a direct AIDL call.
8328 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
8329 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08008330 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008331 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008332 return;
8333 }
8334
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008335 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
8336 mNetworkProviderInfos.put(npi.messenger, npi);
8337 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008338 }
8339
8340 @Override
8341 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008342 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08008343 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008344 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08008345 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008346 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
8347 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008348 }
8349
8350 @Override
8351 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008352 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008353 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008354 }
8355
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008356 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09008357 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008358 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
8359 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09008360 Objects.requireNonNull(score);
8361 Objects.requireNonNull(caps);
8362 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008363 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008364 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09008365 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
8366 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008367 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
8368 }
8369
Chalard Jeanbb902a52021-08-18 01:35:19 +09008370 private void updateOfferScore(final NetworkOffer offer) {
8371 final boolean yieldToBadWiFi =
8372 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
8373 final NetworkOffer newOffer = new NetworkOffer(
8374 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
8375 offer.caps, offer.callback, offer.providerId);
8376 if (offer.equals(newOffer)) return;
8377 handleRegisterNetworkOffer(newOffer);
8378 }
8379
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008380 @Override
8381 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08008382 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008383 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
8384 }
8385
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008386 private void handleUnregisterNetworkProvider(Messenger messenger) {
8387 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
8388 if (npi == null) {
8389 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008390 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008391 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008392 // Unregister all the offers from this provider
8393 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
8394 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09008395 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008396 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
8397 toRemove.add(noi);
8398 }
8399 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09008400 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008401 handleUnregisterNetworkOffer(noi);
8402 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008403 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07008404 }
8405
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008406 @Override
James Mattisf7027322020-12-13 16:28:14 -08008407 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008408 if (request.hasTransport(TRANSPORT_TEST)) {
8409 enforceNetworkFactoryOrTestNetworksPermission();
8410 } else {
8411 enforceNetworkFactoryPermission();
8412 }
James Mattisf7027322020-12-13 16:28:14 -08008413 final NetworkRequestInfo nri = mNetworkRequests.get(request);
8414 if (nri != null) {
8415 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
8416 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
8417 mHandler.post(() -> handleReleaseNetworkRequest(
8418 nri.mRequests.get(0), mDeps.getCallingUid(), true));
8419 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008420 }
8421
Paul Jensen1f567382015-02-13 14:18:39 -05008422 // NOTE: Accessed on multiple threads, must be synchronized on itself.
8423 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008424 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05008425 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008426 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05008427 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008428 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008429
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008430 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05008431 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008432 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008433
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008434 // UID ranges for users that are currently blocked by VPNs.
8435 // This array is accessed and iterated on multiple threads without holding locks, so its
8436 // contents must never be mutated. When the ranges change, the array is replaced with a new one
8437 // (on the handler thread).
8438 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
8439
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008440 // Must only be accessed on the handler thread
8441 @NonNull
8442 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8443
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008444 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008445 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008446
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008447 // Current OEM network preferences. This object must only be written to on the handler thread.
8448 // Since it is immutable and always non-null, other threads may read it if they only care
8449 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008450 @NonNull
8451 private OemNetworkPreferences mOemNetworkPreferences =
8452 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008453 // Current per-profile network preferences. This object follows the same threading rules as
8454 // the OEM network preferences above.
8455 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008456 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8457 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008458
lucaslin3ba7cc22022-12-19 02:35:33 +00008459 // Current VPN network preferences. This object follows the same threading rules as the OEM
8460 // network preferences above.
8461 @NonNull
8462 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8463 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8464
paulhu51f77dc2021-06-07 02:34:20 +00008465 // A set of UIDs that should use mobile data preferentially if available. This object follows
8466 // the same threading rules as the OEM network preferences above.
8467 @NonNull
8468 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8469
James Mattiscb1e0362021-04-06 17:07:42 -07008470 // OemNetworkPreferences activity String log entries.
8471 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8472 @NonNull
8473 private final LocalLog mOemNetworkPreferencesLogs =
8474 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8475
James Mattis02220e22021-03-13 19:27:21 -08008476 /**
8477 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8478 * @param packageName the package name to check existence of a mapping for.
8479 * @return true if a mapping exists, false otherwise
8480 */
8481 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8482 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8483 }
8484
James Mattise3ef1912020-12-20 11:09:58 -08008485 // The always-on request for an Internet-capable network that apps without a specific default
8486 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008487 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008488 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008489 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008490 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008491 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008492 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008493 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008494
James Mattisd31bdfa2020-12-23 16:37:26 -08008495 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8496 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8497 }
8498
8499 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008500 * Return the default network request currently tracking the given uid.
8501 * @param uid the uid to check.
8502 * @return the NetworkRequestInfo tracking the given uid.
8503 */
8504 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008505 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008506 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008507 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008508 // Checking the first request is sufficient as only multilayer requests will have more
8509 // than one request and for multilayer, all requests will track the same uids.
8510 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008511 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008512 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008513 highestPriorityNri = nri;
8514 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008515 }
8516 }
paulhuaa0743d2021-05-26 21:56:03 +08008517 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008518 }
8519
8520 /**
8521 * Get a copy of the network requests of the default request that is currently tracking the
8522 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008523 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8524 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008525 * @param requestorUid the uid to check the default for.
8526 * @param requestorPackageName the requestor's package name.
8527 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8528 */
8529 @NonNull
8530 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008531 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008532 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008533 getDefaultRequestTrackingUid(asUid).mRequests,
8534 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008535 }
8536
8537 /**
8538 * Copy the given nri's NetworkRequest collection.
8539 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008540 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8541 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008542 * @param requestorUid the uid to set on the copied collection.
8543 * @param requestorPackageName the package name to set on the copied collection.
8544 * @return the copied NetworkRequest collection.
8545 */
8546 @NonNull
8547 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008548 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8549 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008550 final List<NetworkRequest> requests = new ArrayList<>();
8551 for (final NetworkRequest nr : requestsToCopy) {
8552 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008553 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008554 nr.legacyType, nextNetworkRequestId(), nr.type));
8555 }
8556 return requests;
8557 }
8558
8559 @NonNull
8560 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008561 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8562 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008563 // These capabilities are for a TRACK_DEFAULT callback, so:
8564 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8565 // mDefaultRequest and a per-UID default request.
8566 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008567 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008568 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008569 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8570 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008571 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008572 restrictRequestUidsForCallerAndSetRequestorInfo(
8573 netCap, requestorUid, requestorPackageName);
8574 return netCap;
8575 }
8576
8577 /**
8578 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8579 * @param nr the network request to check for equality against.
8580 * @return the nri if one exists, null otherwise.
8581 */
8582 @Nullable
8583 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8584 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8585 if (nri.getNetworkRequestForCallback().equals(nr)) {
8586 return nri;
8587 }
8588 }
8589 return null;
8590 }
8591
8592 /**
8593 * Check if an nri is currently being managed by per-app default networking.
8594 * @param nri the nri to check.
8595 * @return true if this nri is currently being managed by per-app default networking.
8596 */
8597 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8598 // nri.mRequests.get(0) is only different from the original request filed in
8599 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8600 // functionality therefore if these two don't match, it means this particular nri is
8601 // currently being managed by a per-app default.
8602 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8603 }
8604
8605 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008606 * Determine if an nri is a managed default request that disallows default networking.
8607 * @param nri the request to evaluate
8608 * @return true if device-default networking is disallowed
8609 */
8610 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8611 // Check if this nri is a managed default that supports the default network at its
8612 // lowest priority request.
8613 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8614 final NetworkCapabilities lowestPriorityNetCap =
8615 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8616 return isPerAppDefaultRequest(nri)
8617 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8618 lowestPriorityNetCap));
8619 }
8620
Erik Kline05f2b402015-04-30 12:58:40 +09008621 // Request used to optionally keep mobile data active even when higher
8622 // priority networks like Wi-Fi are active.
8623 private final NetworkRequest mDefaultMobileDataRequest;
8624
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008625 // Request used to optionally keep wifi data active even when higher
8626 // priority networks like ethernet are active.
8627 private final NetworkRequest mDefaultWifiRequest;
8628
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008629 // Request used to optionally keep vehicle internal network always active
8630 private final NetworkRequest mDefaultVehicleRequest;
8631
James Mattisd31bdfa2020-12-23 16:37:26 -08008632 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8633 // network with no service. This NAI should never be matched against, nor should any public API
8634 // ever return the associated network. For this reason, this NAI is not in the list of available
8635 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8636 // default requests that don't support using the device default network which will ultimately
8637 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8638 @VisibleForTesting
8639 final NetworkAgentInfo mNoServiceNetwork;
8640
Chalard Jean5b409c72021-02-04 13:12:59 +09008641 // The NetworkAgentInfo currently satisfying the default request, if any.
8642 private NetworkAgentInfo getDefaultNetwork() {
8643 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008644 }
8645
James Mattis2516da32021-01-31 17:06:19 -08008646 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008647 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008648 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8649 // Currently, all network requests will have the same uids therefore checking the first
8650 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008651 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008652 if (null == uids) {
8653 continue;
8654 }
8655 for (final UidRange range : uids) {
8656 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008657 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008658 highestPriorityNri = nri;
8659 }
James Mattis2516da32021-01-31 17:06:19 -08008660 }
8661 }
8662 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008663 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008664 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008665 }
8666
Varun Ananddf569952019-02-06 10:13:38 -08008667 @Nullable
8668 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8669 return nai != null ? nai.network : null;
8670 }
8671
8672 private void ensureRunningOnConnectivityServiceThread() {
8673 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8674 throw new IllegalStateException(
8675 "Not running on ConnectivityService thread: "
8676 + Thread.currentThread().getName());
8677 }
8678 }
8679
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008680 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008681 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8682 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008683 }
8684
Chalard Jean29d06db2018-05-02 21:14:54 +09008685 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008686 * Returns whether local agents are supported on this device.
8687 *
8688 * Local agents are supported from U on TVs, and from V on all devices.
8689 */
8690 @VisibleForTesting
8691 public boolean areLocalAgentsSupported() {
8692 final PackageManager pm = mContext.getPackageManager();
8693 // Local agents are supported starting on U on TVs and on V on everything else.
8694 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8695 }
8696
8697 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008698 * Register a new agent with ConnectivityService to handle a network.
8699 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008700 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008701 * @param networkInfo the initial info associated with this network. It can be updated later :
8702 * see {@link #updateNetworkInfo}.
8703 * @param linkProperties the initial link properties of this network. They can be updated
8704 * later : see {@link #updateLinkProperties}.
8705 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008706 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008707 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008708 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008709 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008710 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008711 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008712 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008713 public Network registerNetworkAgent(INetworkAgent na,
8714 NetworkInfo networkInfo,
8715 LinkProperties linkProperties,
8716 NetworkCapabilities networkCapabilities,
8717 @NonNull NetworkScore initialScore,
8718 @Nullable LocalNetworkConfig localNetworkConfig,
8719 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008720 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008721 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8722 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8723 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008724 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008725 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008726 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008727 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008728 } else {
8729 enforceNetworkFactoryPermission();
8730 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008731 final boolean hasLocalCap =
8732 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8733 if (hasLocalCap && !areLocalAgentsSupported()) {
8734 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8735 throw new IllegalArgumentException("Local agents are not supported in this version");
8736 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008737 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8738 if (hasLocalCap != hasLocalNetworkConfig) {
8739 throw new IllegalArgumentException(null != localNetworkConfig
8740 ? "Only local network agents can have a LocalNetworkConfig"
8741 : "Local network agents must have a LocalNetworkConfig"
8742 );
8743 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008744
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008745 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008746 final long token = Binder.clearCallingIdentity();
8747 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008748 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008749 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8750 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008751 } finally {
8752 Binder.restoreCallingIdentity(token);
8753 }
8754 }
8755
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008756 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008757 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008758 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8759 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008760 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008761
Chalard Jeandbc46952022-02-02 00:14:18 +09008762 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8763 // and mutate them at any time.
8764 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8765 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8766 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008767 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008768
Chalard Jean366c5252022-01-25 18:27:53 +09008769 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008770 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008771 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8772 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008773 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008774 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008775 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8776 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8777 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008778
Chalard Jeandbc46952022-02-02 00:14:18 +09008779 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008780 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008781 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008782 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008783 mDeps.getNetworkStack().makeNetworkMonitor(
8784 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008785 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8786 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008787 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008788 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008789 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008790 }
8791
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008792 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008793 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008794 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008795 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008796 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008797 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8798 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8799 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008800
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008801 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008802
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008803 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008804 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008805 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008806 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008807
8808 try {
8809 networkMonitor.start();
8810 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008811 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008812 }
Chalard Jean366c5252022-01-25 18:27:53 +09008813
Chalard Jean1e4c2182023-10-06 18:45:53 +09008814 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008815 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008816 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008817 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008818 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008819 updateNetworkInfo(nai, networkInfo);
Tommy Webb34f81dc2023-02-20 14:10:55 -05008820 updateDisallowedUidsForNetwork(nai);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008821 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008822 }
8823
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008824 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8825 @NonNull public final NetworkOffer offer;
8826
8827 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8828 this.offer = offer;
8829 }
8830
8831 @Override
8832 public void binderDied() {
8833 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8834 }
8835 }
8836
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008837 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8838 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8839 if (npi.providerId == providerId) return true;
8840 }
8841 return false;
8842 }
8843
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008844 /**
8845 * Register or update a network offer.
8846 * @param newOffer The new offer. If the callback member is the same as an existing
8847 * offer, it is an update of that offer.
8848 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008849 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008850 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8851 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008852 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008853 // This may actually happen if a provider updates its score or registers and then
8854 // immediately unregisters. The offer would still be in the handler queue, but the
8855 // provider would have been removed.
8856 if (DBG) log("Received offer from an unregistered provider");
8857 return;
8858 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008859 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8860 if (null != existingOffer) {
8861 handleUnregisterNetworkOffer(existingOffer);
8862 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008863 if (DBG) {
8864 // handleUnregisterNetworkOffer has already logged the old offer
8865 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8866 }
8867 } else {
8868 if (DBG) {
8869 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8870 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008871 }
8872 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8873 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008874 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008875 } catch (RemoteException e) {
8876 noi.binderDied();
8877 return;
8878 }
8879 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008880 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008881 }
8882
8883 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8884 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008885 if (DBG) {
8886 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8887 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008888
8889 // If the provider removes the offer and dies immediately afterwards this
8890 // function may be called twice in a row, but the array will no longer contain
8891 // the offer.
8892 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008893 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008894 }
8895
8896 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8897 @NonNull final INetworkOfferCallback callback) {
8898 ensureRunningOnConnectivityServiceThread();
8899 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008900 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008901 }
8902 return null;
8903 }
8904
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008905 /**
8906 * Called when receiving LinkProperties directly from a NetworkAgent.
8907 * Stores into |nai| any data coming from the agent that might also be written to the network's
8908 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8909 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008910 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008911 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008912 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8913 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008914 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008915 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008916 }
8917
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008918 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008919 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008920 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008921
Lorenzo Colittid523d142020-04-01 20:16:30 +09008922 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8923 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8924 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008925 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008926
Oliver Scottb825c6f2022-10-27 23:52:45 +00008927 final boolean anyIfaceChanges =
8928 updateInterfaces(newLp, oldLp, netId, networkAgent);
8929
8930 // If any interface names changed, ensure VPN filtering is updated so that ingress filtering
8931 // uses the most up-to-date allowed interface.
8932 final boolean shouldForceUpdateVpnFiltering = networkAgent.isVPN() && anyIfaceChanges;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008933
8934 // update filtering rules, need to happen after the interface update so netd knows about the
8935 // new interface (the interface name -> index map becomes initialized)
Oliver Scottb825c6f2022-10-27 23:52:45 +00008936 updateVpnFiltering(newLp, oldLp, networkAgent, shouldForceUpdateVpnFiltering);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008937
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008938 updateMtu(newLp, oldLp);
8939 // TODO - figure out what to do for clat
8940// for (LinkProperties lp : newLp.getStackedLinks()) {
8941// updateMtu(lp, null);
8942// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008943 if (isDefaultNetwork(networkAgent)) {
Aaron Huang25ef1712021-06-08 13:11:45 +08008944 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008945 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8946 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008947
Erik Klineb9888902016-04-05 13:30:49 +09008948 updateRoutes(newLp, oldLp, netId);
8949 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008950 // Make sure LinkProperties represents the latest private DNS status.
8951 // This does not need to be done before updateDnses because the
8952 // LinkProperties are not the source of the private DNS configuration.
8953 // updateDnses will fetch the private DNS configuration from DnsManager.
8954 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008955
Chalard Jean5b409c72021-02-04 13:12:59 +09008956 if (isDefaultNetwork(networkAgent)) {
Aaron Huang25ef1712021-06-08 13:11:45 +08008957 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09008958 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008959 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008960 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008961
8962 updateWakeOnLan(newLp);
8963
Hai Shalome58bdc62021-01-11 18:45:34 -08008964 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8965 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8966 // does, it needs to be merged here.
8967 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8968 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008969
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008970 // TODO - move this check to cover the whole function
8971 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008972 synchronized (networkAgent) {
8973 networkAgent.linkProperties = newLp;
8974 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008975 // Start or stop DNS64 detection and 464xlat according to network state.
8976 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008977 // Notify NSS when relevant events happened. Currently, NSS only cares about
8978 // interface changed to update clat interfaces accounting.
8979 final boolean interfacesChanged = oldLp == null
8980 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8981 if (interfacesChanged) {
8982 notifyIfacesChangedForNetworkStats();
8983 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008984 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8985 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008986 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008987 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008988
8989 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008990 }
8991
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09008992 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8993 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8994 }
8995
Hai Shalome58bdc62021-01-11 18:45:34 -08008996 /**
8997 * @param naData captive portal data from NetworkAgent
8998 * @param apiData captive portal data from capport API
8999 */
9000 @Nullable
9001 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
9002 CaptivePortalData apiData) {
9003 if (naData == null || apiData == null) {
9004 return naData == null ? apiData : naData;
9005 }
9006 final CaptivePortalData.Builder captivePortalBuilder =
9007 new CaptivePortalData.Builder(naData);
9008
9009 if (apiData.isCaptive()) {
9010 captivePortalBuilder.setCaptive(true);
9011 }
9012 if (apiData.isSessionExtendable()) {
9013 captivePortalBuilder.setSessionExtendable(true);
9014 }
9015 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
9016 // Expiry time, bytes remaining, refresh time all need to come from the same source,
9017 // otherwise data would be inconsistent. Prefer the capport API info if present,
9018 // as it can generally be refreshed more often.
9019 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
9020 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
9021 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
9022 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
9023 // No source has time / bytes remaining information: surface the newest refresh time
9024 // for other fields
9025 captivePortalBuilder.setRefreshTime(
9026 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
9027 }
9028
Hai Shalom7c6ab402021-02-04 19:34:06 -08009029 // Prioritize the user portal URL from the network agent if the source is authenticated.
9030 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
9031 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
9032 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
9033 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08009034 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08009035 // Prioritize the venue information URL from the network agent if the source is
9036 // authenticated.
9037 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
9038 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
9039 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
9040 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08009041 }
9042 return captivePortalBuilder.build();
9043 }
9044
Suprabh Shukla619549f2023-04-26 18:47:36 -07009045 @VisibleForTesting
9046 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08009047 // This needs to be kept in sync and backwards compatible with the decoding logic in
9048 // NetdEventListenerService, which is non-mainline code.
9049 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
9050 }
9051
Suprabh Shukla63e59342023-04-25 23:15:43 -07009052 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
9053 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
9054 return true;
9055 }
9056 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
9057 return true;
9058 }
9059 return false;
9060 }
9061
Suprabh Shukla1e312032023-01-24 03:36:37 -08009062 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09009063 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09009064 // marks on unsupported interfaces is harmless.
Suprabh Shukla63e59342023-04-25 23:15:43 -07009065 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09009066 return;
9067 }
Joel Scherpelza235a812017-05-22 13:47:41 +09009068
Joel Scherpelz946a3c92017-06-08 15:35:21 +09009069 // Mask/mark of zero will not detect anything interesting.
9070 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00009071 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09009072 return;
9073 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09009074
Suprabh Shukla1e312032023-01-24 03:36:37 -08009075 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09009076 try {
9077 if (add) {
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00009078 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09009079 } else {
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00009080 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09009081 }
9082 } catch (Exception e) {
9083 loge("Exception modifying wakeup packet monitoring: " + e);
9084 }
Joel Scherpelza235a812017-05-22 13:47:41 +09009085 }
9086
Oliver Scottb825c6f2022-10-27 23:52:45 +00009087 /** Return whether there were any added or removed interface names. */
9088 private boolean updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09009089 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08009090 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09009091 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08009092 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09009093 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09009094 for (final String iface : interfaceDiff.added) {
9095 try {
9096 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09009097 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08009098 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08009099 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08009100 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09009101 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08009102 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09009103 }
Paul Jensenbff73492014-04-28 10:33:11 -04009104 }
9105 }
Chalard Jean9589e722019-11-19 19:03:53 +09009106 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04009107 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009108 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08009109 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09009110 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04009111 } catch (Exception e) {
9112 loge("Exception removing interface: " + e);
9113 }
9114 }
Oliver Scottb825c6f2022-10-27 23:52:45 +00009115 return !(interfaceDiff.added.isEmpty() && interfaceDiff.removed.isEmpty());
Paul Jensenbff73492014-04-28 10:33:11 -04009116 }
9117
Paul Jensene0fd4a82014-08-06 15:51:33 -04009118 /**
9119 * Have netd update routes from oldLp to newLp.
9120 * @return true if routes changed between oldLp and newLp
9121 */
Junyu Lai970963e2022-10-25 15:46:47 +08009122 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
9123 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08009124 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08009125 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
9126 new CompareOrUpdateResult<>(
9127 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08009128 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08009129 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009130
9131 // add routes before removing old in case it helps with continuous connectivity
9132
Chalard Jean9dd11612018-06-04 16:52:49 +09009133 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009134 for (RouteInfo route : routeDiff.added) {
9135 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009136 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009137 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09009138 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009139 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009140 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09009141 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009142 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009143 }
9144 }
9145 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009146 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009147 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009148 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09009149 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009150 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009151 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09009152 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009153 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009154 }
9155 }
9156
9157 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009158 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009159 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09009160 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009161 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09009162 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009163 }
9164 }
Tyler Weare4314862019-12-05 14:55:30 -08009165
9166 for (RouteInfo route : routeDiff.updated) {
9167 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
9168 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09009169 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08009170 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09009171 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08009172 }
9173 }
9174 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
9175 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009176 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09009177
Junyu Lai970963e2022-10-25 15:46:47 +08009178 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
9179 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09009180 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
9181 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009182 }
Erik Klineb9888902016-04-05 13:30:49 +09009183
Erik Kline31b4a9e2018-01-11 21:07:29 +09009184 if (DBG) {
9185 final Collection<InetAddress> dnses = newLp.getDnsServers();
9186 log("Setting DNS servers for network " + netId + " to " + dnses);
9187 }
Erik Klineb9888902016-04-05 13:30:49 +09009188 try {
chenbruce7b2f8982020-02-20 14:28:31 +08009189 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08009190 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09009191 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09009192 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09009193 }
Erik Kline54e35c02017-04-07 15:29:29 +09009194 }
9195
Junyu Lai970963e2022-10-25 15:46:47 +08009196 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
Oliver Scottb825c6f2022-10-27 23:52:45 +00009197 @NonNull NetworkAgentInfo nai, boolean force) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009198 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
9199 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009200 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
9201 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009202
9203 if (!wasFiltering && !needsFiltering) {
9204 // Nothing to do.
9205 return;
9206 }
9207
Oliver Scottb825c6f2022-10-27 23:52:45 +00009208 if (!force && Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009209 // Nothing changed.
9210 return;
9211 }
9212
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009213 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00009214 if (ranges == null || ranges.isEmpty()) {
9215 return;
9216 }
9217
Qingxi Libb8da982020-01-17 17:54:27 -08009218 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009219 // TODO: this create a window of opportunity for apps to receive traffic between the time
9220 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06009221 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009222 // old rules are being removed.
9223 if (wasFiltering) {
9224 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
Oliver Scottb825c6f2022-10-27 23:52:45 +00009225 mPermissionMonitor.updateVpnLockdownUidInterfaceRules(oldLp.getInterfaceName(), ranges,
9226 vpnAppUid, false /* add */);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009227 }
9228 if (needsFiltering) {
9229 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
Oliver Scottb825c6f2022-10-27 23:52:45 +00009230 mPermissionMonitor.updateVpnLockdownUidInterfaceRules(newLp.getInterfaceName(), ranges,
9231 vpnAppUid, true /* add */);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009232 }
9233 }
9234
Valentin Iftime9fa35092019-09-24 13:32:13 +02009235 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009236 if (mWolSupportedInterfaces == null) {
9237 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009238 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009239 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02009240 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
9241 }
9242
Luke Huangb913c812018-08-24 20:33:16 +08009243 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09009244 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08009245 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09009246 }
9247 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08009248 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09009249 }
Luke Huangb913c812018-08-24 20:33:16 +08009250 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09009251 }
9252
Chalard Jean62edfd82019-12-02 18:39:29 +09009253 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
9254 @NonNull final NetworkCapabilities newNc) {
9255 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
9256 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09009257 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09009258 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08009259 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08009260 } catch (RemoteException | ServiceSpecificException e) {
9261 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09009262 }
9263 }
9264 }
9265
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009266 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009267 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09009268 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009269 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08009270 underlyingNetworks = underlyingNetworksOrDefault(
9271 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09009272 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009273 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
9274 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009275 // metered if any underlying is metered, or originally declared metered by the agent.
9276 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009277 boolean roaming = false; // roaming if any underlying is roaming
9278 boolean congested = false; // congested if any underlying is congested
9279 boolean suspended = true; // suspended if all underlying are suspended
9280
9281 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08009282 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009283 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08009284 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009285 for (Network underlyingNetwork : underlyingNetworks) {
9286 final NetworkAgentInfo underlying =
9287 getNetworkAgentInfoForNetwork(underlyingNetwork);
9288 if (underlying == null) continue;
9289
9290 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
9291 hadUnderlyingNetworks = true;
9292 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09009293 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009294 }
9295
9296 // Merge capabilities of this underlying network. For bandwidth, assume the
9297 // worst case.
9298 downKbps = NetworkCapabilities.minBandwidth(downKbps,
9299 underlyingCaps.getLinkDownstreamBandwidthKbps());
9300 upKbps = NetworkCapabilities.minBandwidth(upKbps,
9301 underlyingCaps.getLinkUpstreamBandwidthKbps());
9302 // If this underlying network is metered, the VPN is metered (it may cost money
9303 // to send packets on this network).
9304 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
9305 // If this underlying network is roaming, the VPN is roaming (the billing structure
9306 // is different than the usual, local one).
9307 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9308 // If this underlying network is congested, the VPN is congested (the current
9309 // condition of the network affects the performance of this network).
9310 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
9311 // If this network is not suspended, the VPN is not suspended (the VPN
9312 // is able to transfer some data).
9313 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08009314 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009315 }
9316 }
9317 if (!hadUnderlyingNetworks) {
9318 // No idea what the underlying networks are; assume reasonable defaults
9319 metered = true;
9320 roaming = false;
9321 congested = false;
9322 suspended = false;
9323 }
9324
Chalard Jean1d420b32022-10-12 16:39:37 +09009325 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009326 newNc.setLinkDownstreamBandwidthKbps(downKbps);
9327 newNc.setLinkUpstreamBandwidthKbps(upKbps);
9328 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
9329 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
9330 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
9331 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08009332 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009333 }
9334
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009335 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009336 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
9337 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
9338 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04009339 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09009340 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009341 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09009342 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09009343 // Don't complain for VPNs since they're not driven by requests and there is no risk of
9344 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009345 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09009346 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09009347 if (nai.everConnected()
9348 && !nai.isVPN()
9349 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009350 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09009351 // does not cause any request (that is not a listen) currently matching that agent to
9352 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009353 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09009354 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009355 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09009356 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009357 }
9358
Paul Jensen53f08952015-06-16 14:27:36 -04009359 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009360 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09009361 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009362 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04009363 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009364 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04009365 }
Chalard Jean254bd162022-08-25 13:04:51 +09009366 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009367 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04009368 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009369 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04009370 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009371 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009372 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009373 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009374 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009375 }
Chalard Jean254bd162022-08-25 13:04:51 +09009376 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08009377 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9378 } else {
9379 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9380 }
lucasline117e2e2019-10-22 18:27:33 +08009381 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009382
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009383 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09009384 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
9385 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009386 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09009387 }
9388
Lorenzo Colittibd079452021-07-02 11:47:57 +09009389 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09009390 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09009391 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009392 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009393 }
9394
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009395 return newNc;
9396 }
9397
Lorenzo Colitti44840702021-01-11 22:27:57 +09009398 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
9399 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
9400 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9401 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9402 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9403 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9404 if (prevSuspended != suspended) {
9405 // TODO (b/73132094) : remove this call once the few users of onSuspended and
9406 // onResumed have been removed.
9407 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
9408 : ConnectivityManager.CALLBACK_RESUMED);
9409 }
9410 if (prevSuspended != suspended || prevRoaming != roaming) {
9411 // updateNetworkInfo will mix in the suspended info from the capabilities and
9412 // take appropriate action for the network having possibly changed state.
9413 updateNetworkInfo(nai, nai.networkInfo);
9414 }
9415 }
9416
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009417 /**
9418 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
9419 *
9420 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
9421 * capabilities we manage and store in {@code nai}, such as validated status and captive
9422 * portal status)
9423 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
9424 * potentially triggers rematches.
9425 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
9426 * change.)
9427 *
9428 * @param oldScore score of the network before any of the changes that prompted us
9429 * to call this function.
9430 * @param nai the network having its capabilities updated.
9431 * @param nc the new network capabilities.
9432 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009433 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09009434 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009435 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009436 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09009437 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
9438 if (null != differences) {
9439 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
9440 }
Chalard Jean62edfd82019-12-02 18:39:29 +09009441 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09009442 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009443
Tommy Webb34f81dc2023-02-20 14:10:55 -05009444 if (prevNc != null && (!prevNc.equalsUids(newNc) || !prevNc.equalsTransportTypes(newNc))) {
9445 updateDisallowedUidsForNetwork(nai);
9446 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009447 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09009448 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09009449 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009450
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009451 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009452 // If the requestable capabilities haven't changed, and the score hasn't changed, then
9453 // the change we're processing can't affect any requests, it can only affect the listens
9454 // on this network. We might have been called by rematchNetworkAndRequests when a
9455 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09009456 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009457 } else {
9458 // If the requestable capabilities have changed or the score changed, we can't have been
9459 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009460 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009461 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009462 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009463 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009464
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009465 final boolean oldMetered = prevNc.isMetered();
9466 final boolean newMetered = newNc.isMetered();
9467 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009468
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009469 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009470 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9471 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009472 }
junyulaif2c67e42018-08-07 19:50:45 +08009473
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009474 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9475 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009476
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009477 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009478 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009479 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009480 }
9481
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009482 // This network might have been underlying another network. Propagate its capabilities.
9483 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009484
Ken Chen5a35cf92023-10-07 07:54:22 +08009485 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009486 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009487 }
lucaslin53e8a262021-06-08 01:43:59 +08009488
9489 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009490 }
9491
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009492 /** Convenience method to update the capabilities for a given network. */
9493 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009494 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009495 }
9496
Chalard Jean1e4c2182023-10-06 18:45:53 +09009497 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009498 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009499 @Nullable final LocalNetworkConfig oldConfig,
9500 @NonNull final LocalNetworkConfig newConfig) {
9501 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009502 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9503 return;
9504 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009505
Chalard Jean4fe23392023-10-17 23:02:27 +09009506 if (VDBG) {
9507 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9508 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009509 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
9510 // TODO : apply the diff for multicast routing.
9511 configBuilder.setUpstreamMulticastRoutingConfig(
9512 newConfig.getUpstreamMulticastRoutingConfig());
9513 configBuilder.setDownstreamMulticastRoutingConfig(
9514 newConfig.getDownstreamMulticastRoutingConfig());
9515
9516 final NetworkRequest oldRequest =
9517 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9518 final NetworkCapabilities oldCaps =
9519 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9520 final NetworkRequestInfo oldNri =
9521 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9522 final NetworkAgentInfo oldSatisfier =
9523 null == oldNri ? null : oldNri.getSatisfier();
9524 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9525 final NetworkCapabilities newCaps =
9526 (null == newRequest) ? null : newRequest.networkCapabilities;
9527 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9528 if (null != oldRequest && requestUpdated) {
9529 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9530 if (null == newRequest && null != oldSatisfier) {
9531 // If there is an old satisfier, but no new request, then remove the old upstream.
9532 removeLocalNetworkUpstream(nai, oldSatisfier);
9533 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009534 // When there is a new request, the rematch sees the new request and sends the
9535 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9536 // But here there is no new request, so the rematch won't see anything. Send
9537 // callbacks to apps now to tell them about the loss of upstream.
9538 notifyNetworkCallbacks(nai,
9539 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009540 return;
9541 }
9542 }
9543 if (null != newRequest && requestUpdated) {
9544 // File the new request if :
9545 // - it has changed (requestUpdated), or
9546 // - it's the first time this local info (null == oldConfig)
9547 // is updated and the request has not been filed yet.
9548 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9549 // upstream (the best) but never request it to be brought up.
9550 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9551 nextNetworkRequestId(), LISTEN_FOR_BEST);
9552 configBuilder.setUpstreamSelector(nr);
9553 final NetworkRequestInfo nri = new NetworkRequestInfo(
9554 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9555 0 /* callbackFlags */, null /* attributionTag */);
9556 if (null != oldSatisfier) {
9557 // Set the old satisfier in the new NRI so that the rematch will see any changes
9558 nri.setSatisfier(oldSatisfier, nr);
9559 }
9560 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009561 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9562 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9563 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009564 handleRegisterNetworkRequest(nri);
9565 } else {
9566 configBuilder.setUpstreamSelector(oldRequest);
9567 nai.localNetworkConfig = configBuilder.build();
9568 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009569 }
9570
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009571 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009572 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009573 *
9574 * Ingress interface filtering enforces that all apps under the given network can only receive
9575 * packets from the network's interface (and loopback). This is important for VPNs because
9576 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9577 * non-VPN interfaces.
9578 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009579 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009580 * 1. the network is an app VPN (not legacy VPN)
9581 * 2. the VPN does not allow bypass
9582 * 3. the VPN is fully-routed
9583 * 4. the VPN interface is non-null
9584 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009585 * @see INetd#firewallAddUidInterfaceRules
9586 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009587 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009588 @Nullable
9589 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009590 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009591 if (nc == null || lp == null) return null;
9592 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009593 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009594 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009595 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009596 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009597 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009598 && !lp.hasExcludeRoute()) {
9599 return lp.getInterfaceName();
9600 }
9601 return null;
9602 }
9603
9604 /**
9605 * Returns whether we need to set interface filtering rule or not
9606 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009607 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009608 String isolationIface) {
9609 // Allow rules are always needed if VPN isolation is enabled.
9610 if (isolationIface != null) return true;
9611
9612 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9613 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9614 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jean03552c42023-05-29 17:02:43 +09009615 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009616 }
9617
Chiachang Wang28afaff2020-12-10 22:24:47 +08009618 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9619 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9620 int index = 0;
9621 for (UidRange range : ranges) {
9622 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9623 index++;
9624 }
9625 return stableRanges;
9626 }
9627
Chalard Jeane6c95272022-01-25 21:04:21 +09009628 private static UidRangeParcel[] intsToUidRangeStableParcels(
9629 final @NonNull ArraySet<Integer> uids) {
9630 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9631 int index = 0;
9632 for (int uid : uids) {
9633 stableRanges[index] = new UidRangeParcel(uid, uid);
9634 index++;
9635 }
9636 return stableRanges;
9637 }
9638
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009639 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9640 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9641 for (int i = 0; i < ranges.length; i++) {
9642 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9643 }
9644 return stableRanges;
9645 }
9646
Motomu Utsumia20f7602023-03-16 17:04:21 +09009647 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi5d718002023-06-04 21:32:08 +09009648 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009649 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9650 try {
Motomu Utsumi5d718002023-06-04 21:32:08 +09009651 if (mDeps.isAtLeastU()) {
9652 final Set<Integer> exemptUidSet = new ArraySet<>();
9653 for (final int uid: exemptUids) {
9654 exemptUidSet.add(uid);
9655 }
9656 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9657 } else {
9658 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9659 }
Ken Chen5e65a852020-12-24 12:59:10 +08009660 } catch (Exception e) {
9661 loge("Exception in socket destroy: ", e);
9662 }
9663 }
9664 }
9665
paulhuaa0743d2021-05-26 21:56:03 +08009666 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi5d718002023-06-04 21:32:08 +09009667 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009668 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9669 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9670 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi5d718002023-06-04 21:32:08 +09009671 exemptUids[0] = VPN_UID;
9672 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009673 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9674
Motomu Utsumi6345e462023-03-13 13:24:50 +09009675 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi5d718002023-06-04 21:32:08 +09009676 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009677 try {
9678 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009679 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009680 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009681 } else {
paulhu0e79d952021-06-09 16:11:35 +08009682 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009683 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009684 }
9685 } catch (Exception e) {
9686 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9687 " on netId " + nai.network.netId + ". " + e);
9688 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009689 // Close sockets that established connection while requesting netd.
Motomu Utsumi5d718002023-06-04 21:32:08 +09009690 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009691 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009692
lucaslin53e8a262021-06-08 01:43:59 +08009693 private boolean isProxySetOnAnyDefaultNetwork() {
9694 ensureRunningOnConnectivityServiceThread();
9695 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9696 final NetworkAgentInfo nai = nri.getSatisfier();
9697 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9698 return true;
9699 }
9700 }
9701 return false;
9702 }
9703
9704 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9705 NetworkCapabilities newNc) {
9706 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9707 // the proxy might be changed since the default network satisfied by the apps might also
9708 // changed.
9709 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9710 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009711 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9712 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009713 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009714 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9715 mProxyTracker.sendProxyBroadcast();
9716 }
9717 }
9718
Chalard Jeane6c95272022-01-25 21:04:21 +09009719 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9720 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009721 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9722 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009723 if (null == prevRanges) prevRanges = new ArraySet<>();
9724 if (null == newRanges) newRanges = new ArraySet<>();
9725 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9726
9727 prevRanges.removeAll(newRanges);
9728 newRanges.removeAll(prevRangesCopy);
9729
9730 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009731 // When updating the VPN uid routing rules, add the new range first then remove the old
9732 // range. If old range were removed first, there would be a window between the old
9733 // range being removed and the new range being added, during which UIDs contained
9734 // in both ranges are not subject to any VPN routing rules. Adding new range before
9735 // removing old range works because, unlike the filtering rules below, it's possible to
9736 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009737 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9738 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9739 // [1-5] & [1-2],[4-5] == [3]
9740 // Then we can do:
9741 // maybeCloseSockets([3])
9742 // mNetd.networkAddUidRanges([1-2],[4-5])
9743 // mNetd.networkRemoveUidRanges([1-5])
9744 // maybeCloseSockets([3])
9745 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9746 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009747 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009748 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009749 }
9750 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009751 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009752 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009753 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9754 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009755 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9756 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009757 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009758 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009759 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9760 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9761 // were added first and then newRanges got removed later, there would be only one uid
9762 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9763 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9764 // Note that this is in contrast with the (more robust) update of VPN routing rules
9765 // above, where the addition of new ranges happens before the removal of old ranges.
9766 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9767 // to be removed will never overlap with the new range to be added.
9768 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009769 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9770 prevNc.getOwnerUid());
Oliver Scottb825c6f2022-10-27 23:52:45 +00009771 mPermissionMonitor.updateVpnLockdownUidInterfaceRules(
9772 nai.linkProperties.getInterfaceName(), prevRanges, prevNc.getOwnerUid(),
9773 false /* add */);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009774 }
9775 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009776 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Oliver Scottb825c6f2022-10-27 23:52:45 +00009777 mPermissionMonitor.updateVpnLockdownUidInterfaceRules(
9778 nai.linkProperties.getInterfaceName(), newRanges, newNc.getOwnerUid(),
9779 true /* add */);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009780 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009781 } catch (Exception e) {
9782 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009783 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009784 }
9785 }
9786
Chalard Jeande665262022-02-25 16:12:12 +09009787 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009788 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
Tommy Webb34f81dc2023-02-20 14:10:55 -05009789 if (!nai.isVPN()) {
9790 updateAllowedUidsForNetwork(nai);
9791 }
Chalard Jeane6c95272022-01-25 21:04:21 +09009792 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009793 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9794 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009795 if (prevEmpty && newEmpty) return;
9796
9797 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009798 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009799 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009800 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009801
9802 if (prevUids.equals(newUids)) return;
9803
9804 // This implementation is very simple and vastly faster for sets of Integers than
9805 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9806 // a key computed from the value and has storage for that.
9807 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9808 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9809 toRemove.removeAll(newUids);
9810 toAdd.removeAll(prevUids);
9811
9812 try {
9813 if (!toAdd.isEmpty()) {
9814 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9815 nai.network.netId,
9816 intsToUidRangeStableParcels(toAdd),
9817 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9818 }
9819 if (!toRemove.isEmpty()) {
9820 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9821 nai.network.netId,
9822 intsToUidRangeStableParcels(toRemove),
9823 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9824 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009825 } catch (ServiceSpecificException e) {
9826 // Has the interface disappeared since the network was built ?
9827 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009828 } catch (RemoteException e) {
9829 // Netd died. This usually causes a runtime restart anyway.
9830 }
9831 }
9832
Junyu Lai2ed7d412022-10-07 16:52:21 +08009833 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9834 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009835 ensureRunningOnConnectivityServiceThread();
9836
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009837 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009838 // Ignore updates for disconnected networks
9839 return;
9840 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009841 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009842 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009843 + "; created=" + nai.getCreatedTime()
9844 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009845 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009846 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9847 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009848 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009849 }
9850
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009851 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9852 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009853 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009854 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009855 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009856 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9857 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9858 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009859 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9860 // need to be sent as a separate extra.
9861 final NetworkRequest req = nri.isMultilayerRequest()
9862 ? nri.getActiveRequest()
9863 // Non-multilayer listen requests do not have an active request
9864 : nri.mRequests.get(0);
9865 if (req == null) {
9866 Log.wtf(TAG, "No request in NRI " + nri);
9867 }
9868 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009869 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009870 sendIntent(nri.mPendingIntent, intent);
9871 }
9872 // else not handled
9873 }
9874
Michael Groover73f69482023-01-27 11:01:25 -06009875 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9876 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009877 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9878 mPendingIntentWakeLock.acquire();
9879 try {
9880 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009881 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jean03552c42023-05-29 17:02:43 +09009882 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009883 // Explicitly disallow the receiver from starting activities, to prevent apps from
9884 // utilizing the PendingIntent as a backdoor to do this.
9885 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9886 }
9887 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9888 null /* requiredPermission */,
Chalard Jean03552c42023-05-29 17:02:43 +09009889 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009890 } catch (PendingIntent.CanceledException e) {
9891 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9892 mPendingIntentWakeLock.release();
9893 releasePendingNetworkRequest(pendingIntent);
9894 }
9895 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9896 }
9897
9898 @Override
9899 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9900 String resultData, Bundle resultExtras) {
9901 if (DBG) log("Finished sending " + pendingIntent);
9902 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009903 // Release with a delay so the receiving client has an opportunity to put in its
9904 // own request.
9905 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009906 }
9907
Chalard Jean22350c92023-10-07 19:21:45 +09009908 @Nullable
9909 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9910 if (!nai.isLocalNetwork()) return null;
9911 final Network upstream;
9912 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9913 if (null == selector) {
9914 upstream = null;
9915 } else {
9916 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9917 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9918 upstream = (null == satisfier) ? null : satisfier.network;
9919 }
9920 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9921 }
9922
Chalard Jean46bfbf02022-02-02 00:56:25 +09009923 // networkAgent is only allowed to be null if notificationType is
9924 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9925 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009926 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009927 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009928 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009929 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009930 // Default request has no msgr. Also prevents callbacks from being invoked for
9931 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9932 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9933 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009934 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009935 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009936 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009937 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009938 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009939 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009940 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009941 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9942 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009943 }
Roshan Pius951c0032020-12-22 15:10:42 -08009944 final boolean includeLocationSensitiveInfo =
9945 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009946 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009947 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009948 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009949 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009950 networkCapabilitiesRestrictedForCallerPermissions(
9951 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9952 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009953 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009954 nri.mCallingAttributionTag);
9955 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009956 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9957 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009958 // The local network info is often null, so can't use the static putParcelable
9959 // method here.
9960 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9961 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009962 // For this notification, arg1 contains the blocked status.
9963 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009964 break;
9965 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009966 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009967 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009968 break;
9969 }
9970 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009971 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009972 final NetworkCapabilities netCap =
9973 networkCapabilitiesRestrictedForCallerPermissions(
9974 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9975 putParcelable(
9976 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009977 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009978 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009979 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009980 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009981 break;
9982 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009983 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009984 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9985 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009986 break;
9987 }
junyulaif2c67e42018-08-07 19:50:45 +08009988 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009989 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009990 msg.arg1 = arg1;
9991 break;
9992 }
Chalard Jean22350c92023-10-07 19:21:45 +09009993 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9994 if (!networkAgent.isLocalNetwork()) {
9995 Log.wtf(TAG, "Callback for local info for a non-local network");
9996 return;
9997 }
9998 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9999 break;
10000 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010001 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010002 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -070010003 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010004 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -070010005 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010006 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -080010007 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -070010008 }
James Mattis45d81842021-01-10 14:24:24 -080010009 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010010 } catch (RemoteException e) {
10011 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -080010012 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010013 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010014 }
10015
Hugo Benichif8a0f9f2017-03-23 22:40:44 +090010016 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
10017 bundle.putParcelable(t.getClass().getSimpleName(), t);
10018 }
10019
Chalard Jean0702f982021-09-16 21:50:07 +090010020 /**
10021 * Returns whether reassigning a request from an NAI to another can be done gracefully.
10022 *
10023 * When a request should be assigned to a new network, it is normally lingered to give
10024 * time for apps to gracefully migrate their connections. When both networks are on the same
10025 * radio, but that radio can't do time-sharing efficiently, this may end up being
10026 * counter-productive because any traffic on the old network may drastically reduce the
10027 * performance of the new network.
10028 * The stack supports a configuration to let modem vendors state that their radio can't
10029 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
10030 * from one cell network to another can't be done gracefully.
10031 *
10032 * @param oldNai the old network serving the request
10033 * @param newNai the new network serving the request
10034 * @return whether the switch can be graceful
10035 */
10036 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
10037 @NonNull final NetworkAgentInfo newSatisfier) {
10038 if (mCellularRadioTimesharingCapable) return true;
10039 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
10040 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
10041 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
10042 }
10043
Paul Jensenaf94b982014-09-30 15:37:41 -040010044 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010045 if (nai.numRequestNetworkRequests() != 0) {
10046 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10047 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +090010048 // Ignore listening and track default requests.
10049 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010050 loge("Dead network still had at least " + nr);
10051 break;
10052 }
Paul Jensenaf94b982014-09-30 15:37:41 -040010053 }
Jean Chalard01a7d322023-06-27 08:54:23 +000010054 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -040010055 }
10056
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010057 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
10058 if (oldNetwork == null) {
10059 loge("Unknown NetworkAgentInfo in handleLingerComplete");
10060 return;
10061 }
Chalard Jean49707572019-12-10 21:07:02 +090010062 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010063
10064 // If we get here it means that the last linger timeout for this network expired. So there
10065 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +080010066 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010067
Lorenzo Colitti2666be82016-09-09 18:48:56 +090010068 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010069 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010070 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010071 } else {
junyulai0ac374f2020-12-14 18:41:52 +080010072 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +090010073 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010074 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010075 }
10076
James Mattise3ef1912020-12-20 11:09:58 -080010077 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
10078 boolean isDefaultChanged = false;
10079 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
10080 final NetworkReassignment.RequestReassignment reassignment =
10081 changes.getReassignment(defaultRequestInfo);
10082 if (null == reassignment) {
10083 continue;
10084 }
10085 // reassignment only contains those instances where the satisfying network changed.
10086 isDefaultChanged = true;
10087 // Notify system services of the new default.
10088 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
10089 }
Chiachang Wang087fd272018-09-28 22:42:48 +080010090
James Mattise3ef1912020-12-20 11:09:58 -080010091 if (isDefaultChanged) {
10092 // Hold a wakelock for a short time to help apps in migrating to a new default.
10093 scheduleReleaseNetworkTransitionWakelock();
10094 }
10095 }
10096
Aaron Huang25ef1712021-06-08 13:11:45 +080010097 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
10098 if (null == oldDefaultNetwork) return;
10099 // The network stopped being the default. If it was using a PAC proxy, then the
10100 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
10101 // to the local proxy server, which would forward them over the newly default network.
10102 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
10103 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
10104 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
10105 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
10106 }
10107
James Mattise3ef1912020-12-20 11:09:58 -080010108 private void makeDefault(@NonNull final NetworkRequestInfo nri,
10109 @Nullable final NetworkAgentInfo oldDefaultNetwork,
10110 @Nullable final NetworkAgentInfo newDefaultNetwork) {
10111 if (DBG) {
10112 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
10113 }
Chalard Jean8e382112019-12-03 20:45:30 +090010114
James Mattisd31bdfa2020-12-23 16:37:26 -080010115 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
10116 if (newDefaultNetwork != null) {
10117 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -040010118 }
Lorenzo Colitti24861882018-01-19 00:50:48 +090010119
James Mattisd31bdfa2020-12-23 16:37:26 -080010120 // Set an app level managed default and return since further processing only applies to the
10121 // default network.
10122 if (mDefaultRequest != nri) {
10123 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
10124 return;
10125 }
10126
10127 makeDefaultNetwork(newDefaultNetwork);
10128
James Mattise3ef1912020-12-20 11:09:58 -080010129 if (oldDefaultNetwork != null) {
10130 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
10131 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010132 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +090010133 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang25ef1712021-06-08 13:11:45 +080010134 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -080010135 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang25ef1712021-06-08 13:11:45 +080010136 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -080010137 updateTcpBufferSizes(null != newDefaultNetwork
10138 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +090010139 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -040010140 }
10141
James Mattisd31bdfa2020-12-23 16:37:26 -080010142 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
10143 @Nullable final NetworkAgentInfo oldDefaultNetwork,
10144 @Nullable final NetworkAgentInfo newDefaultNetwork) {
10145 try {
10146 if (VDBG) {
10147 log("Setting default network for " + nri
10148 + " using UIDs " + nri.getUids()
10149 + " with old network " + (oldDefaultNetwork != null
10150 ? oldDefaultNetwork.network().getNetId() : "null")
10151 + " and new network " + (newDefaultNetwork != null
10152 ? newDefaultNetwork.network().getNetId() : "null"));
10153 }
10154 if (nri.getUids().isEmpty()) {
10155 throw new IllegalStateException("makeDefaultForApps called without specifying"
10156 + " any applications to set as the default." + nri);
10157 }
10158 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +080010159 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -080010160 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +080010161 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +080010162 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -080010163 }
10164 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +080010165 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -080010166 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +080010167 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +080010168 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -080010169 }
10170 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +090010171 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -080010172 }
Tommy Webb34f81dc2023-02-20 14:10:55 -050010173 updateUidDefaultNetworkRules(newDefaultNetwork);
James Mattisd31bdfa2020-12-23 16:37:26 -080010174 }
10175
Junyu Lai35665cc2022-12-19 17:37:48 +080010176 /**
10177 * Collect restricted uid ranges for the given network and UserHandle, these uids
10178 * are not restricted for matched enterprise networks but being restricted for non-matched
10179 * enterprise networks and non-enterprise networks.
10180 */
10181 @NonNull
10182 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
10183 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
10184 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
10185 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
10186 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
10187
10188 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
10189 // The NC is built from a `ProfileNetworkPreference` which has only one
10190 // enterprise ID, so it's guaranteed to have exactly one.
10191 final int prefId = pref.capabilities.getEnterpriseIds()[0];
10192 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
10193 continue;
10194 }
10195 }
10196
10197 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
10198 pref.capabilities.getUidRanges())) {
10199 throw new IllegalArgumentException(
10200 "Overlapping uid range in preference: " + pref);
10201 }
10202 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
10203 }
10204 return restrictedUidRanges;
10205 }
10206
10207 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +080010208 // Netd command is not implemented before U.
Chalard Jean03552c42023-05-29 17:02:43 +090010209 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +080010210
Junyu Lai35665cc2022-12-19 17:37:48 +080010211 ensureRunningOnConnectivityServiceThread();
10212 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
10213 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
10214 .getUserHandles(true /* excludeDying */);
10215 if (users.isEmpty()) {
10216 throw new IllegalStateException("No user is available");
10217 }
10218
10219 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10220 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
10221 for (final UserHandle user : users) {
10222 final ArraySet<UidRange> restrictedUidRanges =
10223 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
10224 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
10225 UidRange.createForUser(user), restrictedUidRanges));
10226 }
10227
10228 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
10229 configs.add(new NativeUidRangeConfig(
10230 nai.network.netId, rangesParcel, 0 /* subPriority */));
10231 }
10232
10233 // The netd API replaces the previous configs with the current configs.
10234 // Thus, for network disconnection or preference removal, no need to
10235 // unset previous config. Instead, collecting all currently needed
10236 // configs and issue to netd.
10237 try {
10238 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
10239 } catch (ServiceSpecificException e) {
10240 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +080010241 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +080010242 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +080010243 // Netd died. This will cause a runtime restart anyway.
10244 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +080010245 }
10246 }
10247
James Mattisd31bdfa2020-12-23 16:37:26 -080010248 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
10249 try {
10250 if (null != newDefaultNetwork) {
10251 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
10252 } else {
10253 mNetd.networkClearDefault();
10254 }
10255 } catch (RemoteException | ServiceSpecificException e) {
10256 loge("Exception setting default network :" + e);
10257 }
Tommy Webb34f81dc2023-02-20 14:10:55 -050010258 updateUidDefaultNetworkRules(newDefaultNetwork);
James Mattisd31bdfa2020-12-23 16:37:26 -080010259 }
10260
Chalard Jean05cbe972019-12-09 11:50:38 +090010261 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010262 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +090010263 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +090010264 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +090010265 processNewlySatisfiedListenRequests(nai);
10266 }
10267
10268 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -080010269 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10270 if (nri.isMultilayerRequest()) {
10271 continue;
10272 }
10273 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010274 if (!nr.isListen()) continue;
10275 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -080010276 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010277 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
10278 }
10279 }
Chalard Jeancd397a22019-11-22 22:33:33 +090010280 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010281
Chalard Jeancd397a22019-11-22 22:33:33 +090010282 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -080010283 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10284 if (nri.isMultilayerRequest()) {
10285 continue;
10286 }
10287 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010288 if (!nr.isListen()) continue;
10289 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
10290 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +090010291 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010292 }
10293 }
10294 }
10295
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010296 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010297 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010298 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -080010299 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +090010300 @Nullable public final NetworkRequest mOldNetworkRequest;
10301 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010302 @Nullable public final NetworkAgentInfo mOldNetwork;
10303 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -080010304 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +090010305 @Nullable final NetworkRequest oldNetworkRequest,
10306 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010307 @Nullable final NetworkAgentInfo oldNetwork,
10308 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010309 mNetworkRequestInfo = networkRequestInfo;
10310 mOldNetworkRequest = oldNetworkRequest;
10311 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010312 mOldNetwork = oldNetwork;
10313 mNewNetwork = newNetwork;
10314 }
Chalard Jean49707572019-12-10 21:07:02 +090010315
10316 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +090010317 final NetworkRequest requestToShow = null != mNewNetworkRequest
10318 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
10319 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -080010320 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
10321 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +090010322 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010323 }
10324
Chalard Jean46a62372019-12-10 21:25:24 +090010325 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010326
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010327 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +090010328 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010329 }
10330
10331 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +090010332 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +090010333 // The code is never supposed to add two reassignments of the same request. Make
10334 // sure this stays true, but without imposing this expensive check on all
10335 // reassignments on all user devices.
10336 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -080010337 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +090010338 throw new IllegalStateException("Trying to reassign ["
10339 + reassignment + "] but already have ["
10340 + existing + "]");
10341 }
10342 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +090010343 }
Chalard Jean46a62372019-12-10 21:25:24 +090010344 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010345 }
10346
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010347 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +090010348 // the passed request.
10349 @Nullable
10350 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010351 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010352 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010353 }
10354 return null;
10355 }
Chalard Jean49707572019-12-10 21:07:02 +090010356
10357 public String toString() {
10358 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
10359 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +090010360 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010361 for (final RequestReassignment rr : getRequestReassignments()) {
10362 sj.add(rr.toString());
10363 }
10364 return sj.toString();
10365 }
10366
10367 public String debugString() {
10368 final StringBuilder sb = new StringBuilder();
10369 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +090010370 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010371 for (final RequestReassignment rr : getRequestReassignments()) {
10372 sb.append("\n ").append(rr);
10373 }
10374 return sb.append("\n").toString();
10375 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010376 }
10377
Chalard Jean24344d72019-12-04 13:32:31 +090010378 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +090010379 @Nullable final NetworkRequest previousRequest,
10380 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +090010381 @Nullable final NetworkAgentInfo previousSatisfier,
10382 @Nullable final NetworkAgentInfo newSatisfier,
10383 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -080010384 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +090010385 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +090010386 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010387 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010388 log(" accepting network in place of " + previousSatisfier.toShortString()
10389 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010390 }
James Mattisa076c532020-12-02 14:12:41 -080010391 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010392 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +090010393 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +090010394 // If this network switch can't be supported gracefully, the request is not
10395 // lingered. This allows letting go of the network sooner to reclaim some
10396 // performance on the new network, since the radio can't do both at the same
10397 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010398 //
10399 // Also don't linger the request if the old network has been destroyed.
10400 // A destroyed network does not provide actual network connectivity, so
10401 // lingering it is not useful. In particular this ensures that a destroyed
10402 // network is outscored by its replacement,
10403 // then it is torn down immediately instead of being lingered, and any apps that
10404 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +090010405 previousSatisfier.lingerRequest(previousRequest.requestId, now);
10406 }
Chalard Jean24344d72019-12-04 13:32:31 +090010407 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010408 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010409 }
junyulai0ac374f2020-12-14 18:41:52 +080010410
10411 // To prevent constantly CPU wake up for nascent timer, if a network comes up
10412 // and immediately satisfies a request then remove the timer. This will happen for
10413 // all networks except in the case of an underlying network for a VCN.
10414 if (newSatisfier.isNascent()) {
10415 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +080010416 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010417 }
10418
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010419 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -080010420 newSatisfier.unlingerRequest(newRequest.requestId);
10421 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +080010422 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -080010423 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010424 }
Chalard Jeana8ac2302021-03-01 22:16:08 +090010425 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010426 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010427 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -080010428 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010429 }
James Mattisa076c532020-12-02 14:12:41 -080010430 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010431 }
James Mattisa076c532020-12-02 14:12:41 -080010432 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010433 }
10434
James Mattisa076c532020-12-02 14:12:41 -080010435 /**
10436 * This function is triggered when something can affect what network should satisfy what
10437 * request, and it computes the network reassignment from the passed collection of requests to
10438 * network match to the one that the system should now have. That data is encoded in an
10439 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
10440 * satisfier.
10441 *
10442 * After the reassignment is computed, it is applied to the state objects.
10443 *
10444 * @param networkRequests the nri objects to evaluate for possible network reassignment
10445 * @return NetworkReassignment listing of proposed network assignment changes
10446 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010447 @NonNull
James Mattisa076c532020-12-02 14:12:41 -080010448 private NetworkReassignment computeNetworkReassignment(
10449 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090010450 final NetworkReassignment changes = new NetworkReassignment();
10451
Chalard Jeanc81d4c32021-04-07 17:06:19 +090010452 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090010453 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010454 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +090010455 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +090010456 }
Chalard Jean857a1712019-12-10 21:08:07 +090010457
James Mattisa076c532020-12-02 14:12:41 -080010458 for (final NetworkRequestInfo nri : networkRequests) {
10459 // Non-multilayer listen requests can be ignored.
10460 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
10461 continue;
10462 }
10463 NetworkAgentInfo bestNetwork = null;
10464 NetworkRequest bestRequest = null;
10465 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090010466 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080010467 // Stop evaluating as the highest possible priority request is satisfied.
10468 if (null != bestNetwork) {
10469 bestRequest = req;
10470 break;
10471 }
10472 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010473 if (null == bestNetwork && isDefaultBlocked(nri)) {
10474 // Remove default networking if disallowed for managed default requests.
10475 bestNetwork = mNoServiceNetwork;
10476 }
10477 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010478 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010479 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010480 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010481 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010482 }
10483 return changes;
10484 }
10485
James Mattisa076c532020-12-02 14:12:41 -080010486 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10487 return new HashSet<>(mNetworkRequests.values());
10488 }
10489
Paul Jensenc88b39b2015-06-16 14:27:36 -040010490 /**
James Mattisa076c532020-12-02 14:12:41 -080010491 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010492 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010493 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010494 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010495 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10496 }
10497
10498 /**
10499 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10500 * being disconnected.
10501 */
10502 private void rematchNetworksAndRequests(
10503 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10504 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010505 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010506 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010507 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010508 final long computed = SystemClock.elapsedRealtime();
10509 applyNetworkReassignment(changes, start);
10510 final long applied = SystemClock.elapsedRealtime();
10511 issueNetworkNeeds();
10512 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010513 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010514 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10515 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010516 log(changes.debugString());
10517 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010518 // Shorter form, only one line of log
10519 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10520 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010521 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010522 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010523
Chalard Jean1e4c2182023-10-06 18:45:53 +090010524 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10525 @Nullable final NetworkAgentInfo nai2) {
10526 if (null == nai1) return null == nai2;
10527 if (null == nai2) return false;
10528 return nai1.linkProperties.getInterfaceName()
10529 .equals(nai2.linkProperties.getInterfaceName());
10530 }
10531
Chalard Jeand7f762d2019-12-10 19:01:29 +090010532 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010533 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010534 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010535
10536 // Since most of the time there are only 0 or 1 background networks, it would probably
10537 // be more efficient to just use an ArrayList here. TODO : measure performance
10538 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10539 for (final NetworkAgentInfo nai : nais) {
10540 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10541 }
10542
Chalard Jeand7f762d2019-12-10 19:01:29 +090010543 // First, update the lists of satisfied requests in the network agents. This is necessary
10544 // because some code later depends on this state to be correct, most prominently computing
10545 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010546 for (final NetworkReassignment.RequestReassignment event :
10547 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010548 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10549 event.mOldNetworkRequest, event.mNewNetworkRequest,
10550 event.mOldNetwork, event.mNewNetwork,
10551 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010552 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010553
James Mattise3ef1912020-12-20 11:09:58 -080010554 // Process default network changes if applicable.
10555 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010556
Chalard Jean68eab722023-11-16 17:00:04 +090010557 // Update forwarding rules for the upstreams of local networks. Do this before sending
10558 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10559 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10560 // onAvailable so clients know what network the change is about. Store such changes in
10561 // an array that's only allocated if necessary (because it's almost never necessary).
10562 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10563 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10564 if (!nai.isLocalNetwork()) continue;
10565 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10566 if (null == nr) continue; // No upstream for this local network
10567 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10568 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10569 if (null == change) continue; // No change in upstreams for this network
10570 final String fromIface = nai.linkProperties.getInterfaceName();
10571 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10572 || change.mOldNetwork.isDestroyed()) {
10573 // There can be a change with the same interface name if the new network is the
10574 // replacement for the old network that was unregisteredAfterReplacement.
10575 try {
10576 if (null != change.mOldNetwork) {
10577 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10578 change.mOldNetwork.linkProperties.getInterfaceName());
10579 }
10580 // If the new upstream is already destroyed, there is no point in setting up
10581 // a forward (in fact, it might forward to the interface for some new network !)
10582 // Later when the upstream disconnects CS will try to remove the forward, which
10583 // is ignored with a benign log by RoutingCoordinatorService.
10584 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10585 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10586 change.mNewNetwork.linkProperties.getInterfaceName());
10587 }
10588 } catch (final RemoteException e) {
10589 loge("Can't update forwarding rules", e);
10590 }
10591 }
10592 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10593 localInfoChangedAgents.add(nai);
10594 }
10595
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010596 // Notify requested networks are available after the default net is switched, but
10597 // before LegacyTypeTracker sends legacy broadcasts
10598 for (final NetworkReassignment.RequestReassignment event :
10599 changes.getRequestReassignments()) {
10600 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010601 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010602 } else {
James Mattisa076c532020-12-02 14:12:41 -080010603 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010604 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010605 }
10606 }
10607
junyulai0ac374f2020-12-14 18:41:52 +080010608 // Update the inactivity state before processing listen callbacks, because the background
10609 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010610 // just yet though, because they have to be sent after the listens are processed to keep
10611 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010612 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010613 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010614 // Rematching may have altered the inactivity state of some networks, so update all
10615 // inactivity timers. updateInactivityState reads the state from the network agent
10616 // and does nothing if the state has not changed : the source of truth is controlled
10617 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10618 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010619 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010620 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010621 }
10622 }
10623
Chalard Jeanb10ab412019-12-11 14:12:30 +090010624 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010625 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010626 // Process listen requests and update capabilities if the background state has
10627 // changed for this network. For consistency with previous behavior, send onLost
10628 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010629 processNewlyLostListenRequests(nai);
10630 if (oldBackground != nai.isBackgroundNetwork()) {
10631 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010632 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010633 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010634 }
10635
junyulai0ac374f2020-12-14 18:41:52 +080010636 for (final NetworkAgentInfo nai : inactiveNetworks) {
10637 // For nascent networks, if connecting with no foreground request, skip broadcasting
10638 // LOSING for backward compatibility. This is typical when mobile data connected while
10639 // wifi connected with mobile data always-on enabled.
10640 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010641 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010642 }
10643
Chalard Jean68eab722023-11-16 17:00:04 +090010644 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10645 if (null != localInfoChangedAgents) {
10646 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10647 notifyNetworkCallbacks(nai,
10648 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010649 }
10650 }
10651
James Mattise3ef1912020-12-20 11:09:58 -080010652 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010653
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010654 // Tear down all unneeded networks.
Jean Chalard01a7d322023-06-27 08:54:23 +000010655 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010656 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010657 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010658 // This network has active linger timers and no requests, but is not
10659 // lingering. Linger it.
10660 //
10661 // One way (the only way?) this can happen if this network is unvalidated
10662 // and became unneeded due to another network improving its score to the
10663 // point where this network will no longer be able to satisfy any requests
10664 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010665 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010666 notifyNetworkLosing(nai, now);
10667 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010668 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010669 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010670 teardownUnneededNetwork(nai);
10671 }
10672 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010673 }
10674 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010675
Chalard Jean62edfd82019-12-02 18:39:29 +090010676 /**
10677 * Apply a change in background state resulting from rematching networks with requests.
10678 *
10679 * During rematch, a network may change background states by starting to satisfy or stopping
10680 * to satisfy a foreground request. Listens don't count for this. When a network changes
10681 * background states, its capabilities need to be updated and callbacks fired for the
10682 * capability change.
10683 *
10684 * @param nai The network that changed background states
10685 */
10686 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10687 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10688 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10689 updateNetworkPermissions(nai, newNc);
10690 nai.getAndSetNetworkCapabilities(newNc);
10691 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10692 }
10693
Chalard Jeanf0344532019-11-19 19:23:38 +090010694 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010695 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010696 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010697 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10698 changes.getReassignment(mDefaultRequest);
10699 final NetworkAgentInfo oldDefaultNetwork =
10700 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10701 final NetworkAgentInfo newDefaultNetwork =
10702 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010703
Chalard Jean5b409c72021-02-04 13:12:59 +090010704 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010705 // Maintain the illusion : since the legacy API only understands one network at a time,
10706 // if the default network changed, apps should see a disconnected broadcast for the
10707 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010708 if (oldDefaultNetwork != null) {
10709 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10710 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010711 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010712 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010713 // The new default network can be newly null if and only if the old default
10714 // network doesn't satisfy the default request any more because it lost a
10715 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010716 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010717 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010718 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010719 }
10720 }
10721
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010722 // Now that all the callbacks have been sent, send the legacy network broadcasts
10723 // as needed. This is necessary so that legacy requests correctly bind dns
10724 // requests to this network. The legacy users are listening for this broadcast
10725 // and will generally do a dns request so they can ensureRouteToHost and if
10726 // they do that before the callbacks happen they'll use the default network.
10727 //
10728 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10729 // callbacks, but if apps can receive the broadcast before the callback, they still might
10730 // have an inconsistent view of networking.
10731 //
10732 // This *does* introduce a race where if the user uses the new api
10733 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10734 // they may get old info. Reverse this after the old startUsing api is removed.
10735 // This is on top of the multiple intent sequencing referenced in the todo above.
10736 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010737 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010738 addNetworkToLegacyTypeTracker(nai);
10739 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010740 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010741 }
10742
Chalard Jean0354d8c2021-01-12 10:58:56 +090010743 private void issueNetworkNeeds() {
10744 ensureRunningOnConnectivityServiceThread();
10745 for (final NetworkOfferInfo noi : mNetworkOffers) {
10746 issueNetworkNeeds(noi);
10747 }
10748 }
10749
10750 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10751 ensureRunningOnConnectivityServiceThread();
10752 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10753 informOffer(nri, noi.offer, mNetworkRanker);
10754 }
10755 }
10756
10757 /**
10758 * Inform a NetworkOffer about any new situation of a request.
10759 *
10760 * This function handles updates to offers. A number of events may happen that require
10761 * updating the registrant for this offer about the situation :
10762 * • The offer itself was updated. This may lead the offer to no longer being able
10763 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10764 * or conversely being strengthened enough to beat the satisfier (and therefore
10765 * start being needed)
10766 * • The network satisfying a request changed (including cases where the request
10767 * starts or stops being satisfied). The new network may be a stronger or weaker
10768 * match than the old one, possibly affecting whether the offer is needed.
10769 * • The network satisfying a request updated their score. This may lead the offer
10770 * to no longer be able to beat it if the current satisfier got better, or
10771 * conversely start being a good choice if the current satisfier got weaker.
10772 *
10773 * @param nri The request
10774 * @param offer The offer. This may be an updated offer.
10775 */
10776 private static void informOffer(@NonNull NetworkRequestInfo nri,
10777 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10778 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10779 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010780
10781 // Multi-layer requests have a currently active request, the one being satisfied.
10782 // Since the system will try to bring up a better network than is currently satisfying
10783 // the request, NetworkProviders need to be told the offers matching the requests *above*
10784 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10785 // not needed, and the offer is needed for the active request iff the offer can beat
10786 // the satisfier.
10787 // For non-multilayer requests, the logic above gracefully degenerates to only the
10788 // last case.
10789 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10790 // providers that the offer is needed for this request, until the active request is found.
10791 // In a second phase, deal with the currently active request. In a third phase, inform
10792 // the providers that offer is unneeded for the remaining requests.
10793
10794 // First phase : inform providers of all requests above the active request.
10795 int i;
10796 for (i = 0; nri.mRequests.size() > i; ++i) {
10797 final NetworkRequest request = nri.mRequests.get(i);
10798 if (activeRequest == request) break; // Found the active request : go to phase 2
10799 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10800 // Since this request is higher-priority than the one currently satisfied, if the
10801 // offer can satisfy it, the provider should try and bring up the network for sure ;
10802 // no need to even ask the ranker – an offer that can satisfy is always better than
10803 // no network. Hence tell the provider so unless it already knew.
10804 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10805 offer.onNetworkNeeded(request);
10806 }
10807 }
10808
10809 // Second phase : deal with the active request (if any)
10810 if (null != activeRequest && activeRequest.isRequest()) {
10811 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010812 // If an offer can satisfy the request, it is considered needed if it is currently
10813 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010814 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010815 && satisfier.factorySerialNumber == offer.providerId
10816 && activeRequest.canBeSatisfiedBy(offer.caps);
10817 final boolean newNeeded = currentlyServing
10818 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010819 if (newNeeded != oldNeeded) {
10820 if (newNeeded) {
10821 offer.onNetworkNeeded(activeRequest);
10822 } else {
10823 // The offer used to be able to beat the satisfier. Now it can't.
10824 offer.onNetworkUnneeded(activeRequest);
10825 }
10826 }
10827 }
10828
10829 // Third phase : inform the providers that the offer isn't needed for any request
10830 // below the active one.
10831 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10832 final NetworkRequest request = nri.mRequests.get(i);
10833 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10834 // Since this request is lower-priority than the one currently satisfied, if the
10835 // offer can satisfy it, the provider should not try and bring up the network.
10836 // Hence tell the provider so unless it already knew.
10837 if (offer.neededFor(request)) {
10838 offer.onNetworkUnneeded(request);
10839 }
10840 }
10841 }
10842
Chalard Jean61c79252019-11-07 23:07:32 +090010843 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10844 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10845 NetworkRequest nr = nai.requestAt(i);
10846 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10847 // legacy type tracker filters out repeat adds
10848 mLegacyTypeTracker.add(nr.legacyType, nai);
10849 }
10850 }
10851
10852 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010853 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010854 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10855 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10856 if (nai.isVPN()) {
10857 mLegacyTypeTracker.add(TYPE_VPN, nai);
10858 }
10859 }
10860
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010861 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010862 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010863 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010864 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010865 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010866 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010867
Chalard Jean254bd162022-08-25 13:04:51 +090010868 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010869 // Don't repeat publish.
10870 if (newInetCondition == mDefaultInetConditionPublished) return;
10871
10872 mDefaultInetConditionPublished = newInetCondition;
10873 sendInetConditionBroadcast(nai.networkInfo);
10874 }
10875
Chalard Jeand61375d2020-01-14 22:46:36 +090010876 @NonNull
10877 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10878 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010879 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010880 final boolean suspended =
10881 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10882 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10883 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10884 // state. This is because the network could have been suspended before connecting,
10885 // or it could be disconnecting while being suspended, and in both these cases
10886 // the state should not be overridden. Note that the only detailed state that
10887 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10888 // worry about multiple different substates of CONNECTED.
10889 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10890 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010891 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10892 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10893 // network agent is created, then goes to suspended, then goes out of suspended without
10894 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010895 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010896 ? NetworkInfo.DetailedState.CONNECTED
10897 : NetworkInfo.DetailedState.CONNECTING,
10898 info.getReason(),
10899 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010900 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010901 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010902 return newInfo;
10903 }
10904
10905 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10906 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10907
Erik Kline99f301b2017-02-15 19:59:17 +090010908 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010909 NetworkInfo oldInfo = null;
10910 synchronized (networkAgent) {
10911 oldInfo = networkAgent.networkInfo;
10912 networkAgent.networkInfo = newInfo;
10913 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010914
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010915 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010916 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10917 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010918 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010919
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +090010920 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010921 // A network that has just connected has zero requests and is thus a foreground network.
10922 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10923
Luke Huangfdd11f82019-04-09 18:41:49 +080010924 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +090010925
10926 networkAgent.setCreated();
10927
10928 // If the network is created immediately on register, then apply the LinkProperties now.
10929 // Otherwise, this is done further down when the network goes into connected state.
10930 // Applying the LinkProperties means that the network is ready to carry traffic -
10931 // interfaces and routing rules have been added, DNS servers programmed, etc.
10932 // For VPNs, this must be done before the capabilities are updated, because as soon as
10933 // that happens, UIDs are routed to the network.
10934 if (shouldCreateNetworksImmediately()) {
10935 applyInitialLinkProperties(networkAgent);
10936 }
10937
10938 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10939 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010940 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010941 // Initialize the network's capabilities to their starting values according to the
10942 // underlying networks. This ensures that the capabilities are correct before
10943 // anything happens to the network.
10944 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010945 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010946 networkAgent.onNetworkCreated();
Tommy Webb34f81dc2023-02-20 14:10:55 -050010947 updateDisallowedUidsForNetwork(networkAgent);
Chalard Jeande665262022-02-25 16:12:12 +090010948 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010949 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010950 }
10951
Chalard Jean254bd162022-08-25 13:04:51 +090010952 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10953 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010954
lucaslin45e639b2019-04-03 17:09:28 +080010955 // NetworkCapabilities need to be set before sending the private DNS config to
10956 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010957 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10958
Erik Kline9a62f012018-03-21 07:18:33 -070010959 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +090010960 if (!shouldCreateNetworksImmediately()) {
10961 applyInitialLinkProperties(networkAgent);
10962 } else {
10963 // The network was created when the agent registered, and the LinkProperties are
10964 // already up-to-date. However, updateLinkProperties also makes some changes only
10965 // when the network connects. Apply those changes here. On T and below these are
10966 // handled by the applyInitialLinkProperties call just above.
10967 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10968 // If something depends on both LinkProperties and connected state, it should be in
10969 // this method as well.
10970 networkAgent.clatd.update();
10971 updateProxy(networkAgent.linkProperties, null);
10972 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010973
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010974 // If a rate limit has been configured and is applicable to this network (network
10975 // provides internet connectivity), apply it. The tc police filter cannot be attached
10976 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010977 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010978 // Note: in case of a system server crash, the NetworkController constructor in netd
10979 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10980 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10981 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10982 mIngressRateLimit);
10983 }
10984
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010985 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10986 // command must be sent after updating LinkProperties to maximize chances of
10987 // NetworkMonitor seeing the correct LinkProperties when starting.
10988 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010989 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010990 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010991 }
Chalard Jeand4900722022-02-06 12:25:38 +090010992 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10993 params.networkAgentConfig = networkAgent.networkAgentConfig;
10994 params.networkCapabilities = networkAgent.networkCapabilities;
10995 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10996 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010997 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10998 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10999 // call that would cause a Log.wtf to be emitted from the system_server process, and
11000 // in the absence of a satisfactory, scalable solution which follows an easy/standard
11001 // process to check the interface version, just use an SDK check. NetworkStack will
11002 // always be new enough when running on T+.
Chalard Jean03552c42023-05-29 17:02:43 +090011003 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090011004 networkAgent.networkMonitor().notifyNetworkConnected(params);
11005 } else {
11006 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
11007 params.networkCapabilities);
11008 }
Chalard Jean3f0ff5b2023-06-05 19:26:17 +090011009 final long evaluationDelay;
11010 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
11011 // If the network is anything other than pure wifi, use the default timeout.
11012 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
11013 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
11014 // If the network is explicitly selected, use the default timeout because it's
11015 // shorter and the user is likely staring at the screen expecting it to validate
11016 // right away.
11017 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
11018 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
11019 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
11020 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
11021 } else {
11022 // It's wifi, automatically connected, and bad wifi is preferred : use the
11023 // longer timeout to avoid the device switching to captive portals with bad
11024 // signal or very slow response.
11025 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
11026 }
11027 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090011028
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090011029 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
11030 // be communicated to a particular NetworkAgent depends only on the network's immutable,
11031 // capabilities, so it only needs to be done once on initial connect, not every time the
11032 // network's capabilities change. Note that we do this before rematching the network,
11033 // so we could decide to tear it down immediately afterwards. That's fine though - on
11034 // disconnection NetworkAgents should stop any signal strength monitoring they have been
11035 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090011036 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090011037
junyulai0ac374f2020-12-14 18:41:52 +080011038 // Before first rematching networks, put an inactivity timer without any request, this
11039 // allows {@code updateInactivityState} to update the state accordingly and prevent
11040 // tearing down for any {@code unneeded} evaluation in this period.
11041 // Note that the timer will not be rescheduled since the expiry time is
11042 // fixed after connection regardless of the network satisfying other requests or not.
11043 // But it will be removed as soon as the network satisfies a request for the first time.
11044 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
11045 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080011046 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080011047
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090011048 if (mTrackMultiNetworkActivities) {
11049 // Start tracking activity of this network.
11050 // This must be called before rematchAllNetworksAndRequests since the network
11051 // should be tracked when the network becomes the default network.
11052 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
11053 // can be triggered later if this network becomes the default network.
11054 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
11055 }
11056
Paul Jensen05e85ee2014-09-11 11:00:39 -040011057 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090011058 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090011059
11060 // This has to happen after matching the requests, because callbacks are just requests.
11061 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070011062 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard01a7d322023-06-27 08:54:23 +000011063 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040011064 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000011065 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040011066 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090011067 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000011068 if (networkAgent.isVPN()) {
11069 // As the active or bound network changes for apps, broadcast the default proxy, as
11070 // apps may need to update their proxy data. This is called after disconnecting from
11071 // VPN to make sure we do not broadcast the old proxy data.
11072 // TODO(b/122649188): send the broadcast only to VPN users.
11073 mProxyTracker.sendProxyBroadcast();
11074 }
Chalard Jean254bd162022-08-25 13:04:51 +090011075 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
11076 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070011077 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011078 }
11079 }
11080
Chalard Jean28018572020-12-21 18:36:52 +090011081 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090011082 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
11083 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090011084 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070011085 }
11086
Erik Kline99f301b2017-02-15 19:59:17 +090011087 // Notify only this one new request of the current state. Transfer all the
11088 // current state by calling NetworkCapabilities and LinkProperties callbacks
11089 // so that callers can be guaranteed to have as close to atomicity in state
11090 // transfer as can be supported by this current API.
11091 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070011092 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090011093 if (nri.mPendingIntent != null) {
11094 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
11095 // Attempt no subsequent state pushes where intents are involved.
11096 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011097 }
Erik Kline99f301b2017-02-15 19:59:17 +090011098
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011099 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080011100 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011101 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
11102 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
11103 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080011104 }
11105
Chalard Jean8fd82ae2019-12-04 18:49:18 +090011106 // Notify the requests on this NAI that the network is now lingered.
11107 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080011108 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090011109 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
11110 }
11111
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011112 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
11113 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
11114 return vpnBlocked
11115 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
11116 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
11117 }
11118
11119 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
11120 if (blockedReasons == BLOCKED_REASON_NONE) {
11121 mUidBlockedReasons.delete(uid);
11122 } else {
11123 mUidBlockedReasons.put(uid, blockedReasons);
11124 }
11125 }
11126
junyulaif2c67e42018-08-07 19:50:45 +080011127 /**
11128 * Notify of the blocked state apps with a registered callback matching a given NAI.
11129 *
11130 * Unlike other callbacks, blocked status is different between each individual uid. So for
11131 * any given nai, all requests need to be considered according to the uid who filed it.
11132 *
11133 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011134 * @param oldMetered True if the previous network capabilities were metered.
11135 * @param newMetered True if the current network capabilities are metered.
11136 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
11137 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080011138 */
11139 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000011140 boolean newMetered, List<UidRange> oldBlockedUidRanges,
11141 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080011142
11143 for (int i = 0; i < nai.numNetworkRequests(); i++) {
11144 NetworkRequest nr = nai.requestAt(i);
11145 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090011146
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011147 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
11148 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
11149 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011150 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090011151 : oldVpnBlocked;
11152
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011153 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
11154 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
11155 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080011156 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011157 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080011158 }
11159 }
11160 }
11161
11162 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000011163 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080011164 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000011165 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080011166 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011167 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090011168 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080011169 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090011170 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000011171
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011172 final int oldBlockedState = getBlockedState(
11173 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
11174 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
11175 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080011176 continue;
junyulaif2c67e42018-08-07 19:50:45 +080011177 }
junyulaif2c67e42018-08-07 19:50:45 +080011178 for (int i = 0; i < nai.numNetworkRequests(); i++) {
11179 NetworkRequest nr = nai.requestAt(i);
11180 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011181 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011182 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
11183 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080011184 }
11185 }
11186 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011187 }
11188
Chalard Jean3a3f5f22019-04-10 23:07:55 +090011189 @VisibleForTesting
11190 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090011191 // The NetworkInfo we actually send out has no bearing on the real
11192 // state of affairs. For example, if the default connection is mobile,
11193 // and a request for HIPRI has just gone away, we need to pretend that
11194 // HIPRI has just disconnected. So we need to set the type to HIPRI and
11195 // the state to DISCONNECTED, even though the network is of type MOBILE
11196 // and is still connected.
11197 NetworkInfo info = new NetworkInfo(nai.networkInfo);
11198 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090011199 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070011200 if (state != DetailedState.DISCONNECTED) {
11201 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090011202 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011203 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070011204 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070011205 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
11206 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
11207 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
11208 if (info.isFailover()) {
11209 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
11210 nai.networkInfo.setFailover(false);
11211 }
11212 if (info.getReason() != null) {
11213 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
11214 }
11215 if (info.getExtraInfo() != null) {
11216 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
11217 }
11218 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090011219 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080011220 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070011221 if (newDefaultAgent != null) {
11222 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
11223 newDefaultAgent.networkInfo);
11224 } else {
11225 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
11226 }
11227 }
11228 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
11229 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090011230 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011231 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090011232 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011233 }
11234 }
11235 }
11236
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011237 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090011238 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090011239 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090011240 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090011241 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090011242 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
11243 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011244 NetworkRequestInfo nri = mNetworkRequests.get(nr);
11245 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011246 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011247 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011248 } else {
11249 sendPendingIntentForRequest(nri, networkAgent, notifyType);
11250 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011251 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011252 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070011253
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011254 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
11255 notifyNetworkCallbacks(networkAgent, notifyType, 0);
11256 }
11257
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011258 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090011259 * Returns the list of all interfaces that could be used by network traffic that does not
11260 * explicitly specify a network. This includes the default network, but also all VPNs that are
11261 * currently connected.
11262 *
11263 * Must be called on the handler thread.
11264 */
junyulaie7c7d2a2021-01-26 15:29:15 +080011265 @NonNull
11266 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080011267 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080011268 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080011269 final Set<Integer> activeNetIds = new ArraySet<>();
11270 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
11271 if (nri.isBeingSatisfied()) {
11272 activeNetIds.add(nri.getSatisfier().network().netId);
11273 }
11274 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090011275 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090011276 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090011277 defaultNetworks.add(nai.network);
11278 }
11279 }
junyulaie7c7d2a2021-01-26 15:29:15 +080011280 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090011281 }
11282
11283 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090011284 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
11285 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011286 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080011287 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080011288 ensureRunningOnConnectivityServiceThread();
11289 String activeIface = null;
11290 LinkProperties activeLinkProperties = getActiveLinkProperties();
11291 if (activeLinkProperties != null) {
11292 activeIface = activeLinkProperties.getInterfaceName();
11293 }
Benedict Wong9308cd32019-06-12 17:46:31 +000011294
junyulai2050bed2021-01-23 09:46:34 +080011295 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011296 try {
junyulaide41fc22021-01-22 22:46:01 +080011297 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090011298 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080011299 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
11300 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011301 } catch (Exception ignored) {
11302 }
11303 }
11304
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070011305 @Override
Udam Sainicd645462016-01-04 12:16:14 -080011306 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080011307 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090011308 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090011309 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010011310
11311 if (!TextUtils.isEmpty(settingUrl)) {
11312 return settingUrl;
11313 }
11314
11315 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011316 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010011317 if (!TextUtils.isEmpty(settingUrl)) {
11318 return settingUrl;
11319 }
11320
11321 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080011322 }
11323
11324 @Override
junyulai070f9ff2019-01-16 20:23:34 +080011325 public void startNattKeepalive(Network network, int intervalSeconds,
11326 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011327 enforceKeepalivePermission();
11328 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080011329 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000011330 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
11331 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000011332 // false and set the underpinned network to null because there is no way and no
11333 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
11334 // deprecated method.
11335 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011336 }
11337
11338 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011339 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080011340 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000011341 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070011342 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080011343 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011344 mKeepaliveTracker.startNattKeepalive(
11345 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000011346 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
11347 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070011348 } finally {
11349 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11350 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011351 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11352 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011353 }
11354 }
junyulaid05a1922019-01-15 11:32:44 +080011355 }
11356
11357 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011358 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080011359 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070011360 try {
11361 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080011362 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011363 mKeepaliveTracker.startTcpKeepalive(
11364 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
11365 } finally {
11366 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11367 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011368 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11369 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011370 }
11371 }
junyulai0835a1e2019-01-08 20:04:33 +080011372 }
11373
11374 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011375 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011376 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011377 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
11378 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011379 }
11380
11381 @Override
Remi NGUYEN VAN6ca02962023-02-20 20:10:09 +090011382 public int[] getSupportedKeepalives() {
11383 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
11384 // Backwards compatibility with CTS 13
11385 android.Manifest.permission.QUERY_ALL_PACKAGES);
11386
11387 return BinderUtils.withCleanCallingIdentity(() ->
11388 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
11389 }
11390
11391 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070011392 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080011393 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070011394
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011395 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080011396 final long token = Binder.clearCallingIdentity();
11397 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011398 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
11399 UserHandle.getUserHandleForUid(uid))) {
11400 return;
11401 }
11402
Heemin Seogdb8489d2019-06-12 09:21:44 -070011403 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
11404 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011405
11406 // Turn airplane mode off
11407 setAirplaneMode(false);
11408
11409 // restore private DNS settings to default mode (opportunistic)
11410 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
11411 UserHandle.getUserHandleForUid(uid))) {
11412 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
11413 PRIVATE_DNS_MODE_OPPORTUNISTIC);
11414 }
11415
11416 Settings.Global.putString(mContext.getContentResolver(),
11417 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080011418 } finally {
11419 Binder.restoreCallingIdentity(token);
11420 }
Stuart Scottd5463642015-04-02 18:00:02 -070011421 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040011422
Ricky Wai7097cc92018-01-23 04:09:45 +000011423 @Override
11424 public byte[] getNetworkWatchlistConfigHash() {
11425 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
11426 if (nwm == null) {
11427 loge("Unable to get NetworkWatchlistManager");
11428 return null;
11429 }
11430 // Redirect it to network watchlist service to access watchlist file and calculate hash.
11431 return nwm.getWatchlistConfigHash();
11432 }
11433
Hugo Benichibe0c7652016-05-31 16:28:06 +090011434 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090011435 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080011436 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090011437 }
Hugo Benichif4210292017-04-21 15:07:12 +090011438
11439 private static boolean toBool(int encodedBoolean) {
11440 return encodedBoolean != 0; // Only 0 means false.
11441 }
11442
11443 private static int encodeBool(boolean b) {
11444 return b ? 1 : 0;
11445 }
mswest4632928412018-03-12 10:34:34 -070011446
11447 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011448 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
11449 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
11450 @NonNull String[] args) {
11451 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
11452 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070011453 }
11454
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011455 private Boolean parseBooleanArgument(final String arg) {
11456 if ("true".equals(arg)) {
11457 return true;
11458 } else if ("false".equals(arg)) {
11459 return false;
11460 } else {
11461 return null;
11462 }
11463 }
11464
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011465 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070011466 @Override
11467 public int onCommand(String cmd) {
11468 if (cmd == null) {
11469 return handleDefaultCommands(cmd);
11470 }
11471 final PrintWriter pw = getOutPrintWriter();
11472 try {
11473 switch (cmd) {
11474 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011475 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11476 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011477 final String action = getNextArg();
11478 if ("enable".equals(action)) {
11479 setAirplaneMode(true);
11480 return 0;
11481 } else if ("disable".equals(action)) {
11482 setAirplaneMode(false);
11483 return 0;
11484 } else if (action == null) {
11485 final ContentResolver cr = mContext.getContentResolver();
11486 final int enabled = Settings.Global.getInt(cr,
11487 Settings.Global.AIRPLANE_MODE_ON);
11488 pw.println(enabled == 0 ? "disabled" : "enabled");
11489 return 0;
11490 } else {
11491 onHelp();
11492 return -1;
11493 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011494 case "set-chain3-enabled": {
11495 final Boolean enabled = parseBooleanArgument(getNextArg());
11496 if (null == enabled) {
11497 onHelp();
11498 return -1;
11499 }
11500 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11501 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11502 enabled);
11503 return 0;
11504 }
11505 case "get-chain3-enabled": {
11506 final boolean chainEnabled = getFirewallChainEnabled(
11507 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11508 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11509 return 0;
11510 }
11511 case "set-package-networking-enabled": {
11512 final Boolean enabled = parseBooleanArgument(getNextArg());
11513 final String packageName = getNextArg();
11514 if (null == enabled || null == packageName) {
11515 onHelp();
11516 return -1;
11517 }
11518 // Throws NameNotFound if the package doesn't exist.
11519 final int appId = setPackageFirewallRule(
11520 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11521 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11522 final String msg = (enabled ? "Enabled" : "Disabled")
11523 + " networking for " + packageName + ", appId " + appId;
11524 Log.i(TAG, msg);
11525 pw.println(msg);
11526 return 0;
11527 }
11528 case "get-package-networking-enabled": {
11529 final String packageName = getNextArg();
11530 final int rule = getPackageFirewallRule(
11531 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11532 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11533 pw.println(packageName + ":" + "allow");
11534 } else if (FIREWALL_RULE_DENY == rule) {
11535 pw.println(packageName + ":" + "deny");
11536 } else {
11537 throw new IllegalStateException("Unknown rule " + rule + " for package "
11538 + packageName);
11539 }
11540 return 0;
11541 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011542 case "reevaluate":
11543 // Usage : adb shell cmd connectivity reevaluate <netId>
11544 // If netId is omitted, then reevaluate the default network
11545 final String netId = getNextArg();
11546 final NetworkAgentInfo nai;
11547 if (null == netId) {
11548 // Note that the command is running on the wrong thread to call this,
11549 // so this could in principle return stale data. But it can't crash.
11550 nai = getDefaultNetwork();
11551 } else {
11552 // If netId can't be parsed, this throws NumberFormatException, which
11553 // is passed back to adb who prints it.
11554 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11555 }
11556 if (null == nai) {
11557 pw.println("Unknown network (net ID not found or no default network)");
11558 return 0;
11559 }
11560 Log.d(TAG, "Reevaluating network " + nai.network);
11561 reportNetworkConnectivity(nai.network, !nai.isValidated());
11562 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011563 case "bpf-get-cgroup-program-id": {
11564 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11565 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11566 // for more detail.
11567 // If type can't be parsed, this throws NumberFormatException, which
11568 // is passed back to adb who prints it.
11569 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011570 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011571 pw.println(ret);
11572 return 0;
11573 }
mswest4632928412018-03-12 10:34:34 -070011574 default:
11575 return handleDefaultCommands(cmd);
11576 }
11577 } catch (Exception e) {
11578 pw.println(e);
11579 }
11580 return -1;
11581 }
11582
11583 @Override
11584 public void onHelp() {
11585 PrintWriter pw = getOutPrintWriter();
11586 pw.println("Connectivity service commands:");
11587 pw.println(" help");
11588 pw.println(" Print this help text.");
11589 pw.println(" airplane-mode [enable|disable]");
11590 pw.println(" Turn airplane mode on or off.");
11591 pw.println(" airplane-mode");
11592 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011593 pw.println(" set-chain3-enabled [true|false]");
11594 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11595 pw.println(" get-chain3-enabled");
11596 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11597 pw.println(" set-package-networking-enabled [true|false] [package name]");
11598 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11599 + " no effect if the chain is disabled.");
11600 pw.println(" get-package-networking-enabled [package name]");
11601 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011602 }
11603 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011604
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011605 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011606 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11607 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11608 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011609 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011610 }
11611
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011612 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11613 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011614 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11615 final TransportInfo newInfo = nc.getTransportInfo();
11616 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11617 return;
11618 }
11619 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011620 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011621 }
11622 }
11623
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011624 /**
11625 * @param connectionInfo the connection to resolve.
11626 * @return {@code uid} if the connection is found and the app has permission to observe it
11627 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11628 * connection is not found.
11629 */
11630 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011631 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11632 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11633 }
11634
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011635 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011636 connectionInfo.local, connectionInfo.remote);
11637
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011638 if (uid == INVALID_UID) return uid; // Not found.
11639
11640 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11641 // VPN, if any, that applies to the UID that owns the connection.
11642 if (checkNetworkStackPermission()) return uid;
11643
11644 final NetworkAgentInfo vpn = getVpnForUid(uid);
11645 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011646 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011647 return INVALID_UID;
11648 }
11649
11650 return uid;
11651 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011652
Benedict Wong493e04b2018-11-09 14:45:34 -080011653 /**
11654 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11655 *
11656 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11657 */
11658 @Override
11659 public IBinder startOrGetTestNetworkService() {
11660 synchronized (mTNSLock) {
11661 TestNetworkService.enforceTestNetworkPermissions(mContext);
11662
11663 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011664 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011665 }
11666
11667 return mTNS;
11668 }
11669 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011670
Cody Kesting73708bf2019-12-18 10:57:50 -080011671 /**
11672 * Handler used for managing all Connectivity Diagnostics related functions.
11673 *
11674 * @see android.net.ConnectivityDiagnosticsManager
11675 *
11676 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11677 */
11678 @VisibleForTesting
11679 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011680 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11681
Cody Kesting73708bf2019-12-18 10:57:50 -080011682 /**
11683 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11684 * android.net.ConnectivityDiagnosticsManager}.
11685 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11686 * NetworkRequestInfo to be registered
11687 */
11688 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11689
11690 /**
11691 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11692 * android.net.ConnectivityDiagnosticsManager}.
11693 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11694 * arg1 = the uid of the caller
11695 */
11696 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11697
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011698 /**
11699 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011700 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011701 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11702 * NetworkMonitor.
11703 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011704 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011705 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011706
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011707 /**
11708 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11709 * been detected on the network.
11710 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11711 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11712 * arg2 = NetID.
11713 * data = PersistableBundle of extras passed from NetworkMonitor.
11714 */
11715 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11716
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011717 /**
11718 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11719 * the platform. This event will invoke {@link
11720 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11721 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011722 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011723 */
11724 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11725
Cody Kesting73708bf2019-12-18 10:57:50 -080011726 private ConnectivityDiagnosticsHandler(Looper looper) {
11727 super(looper);
11728 }
11729
11730 @Override
11731 public void handleMessage(Message msg) {
11732 switch (msg.what) {
11733 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11734 handleRegisterConnectivityDiagnosticsCallback(
11735 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11736 break;
11737 }
11738 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11739 handleUnregisterConnectivityDiagnosticsCallback(
11740 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11741 break;
11742 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011743 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011744 final ConnectivityReportEvent reportEvent =
11745 (ConnectivityReportEvent) msg.obj;
11746
Aaron Huang959d3642021-01-21 15:47:41 +080011747 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011748 break;
11749 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011750 case EVENT_DATA_STALL_SUSPECTED: {
11751 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011752 final Pair<Long, PersistableBundle> arg =
11753 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011754 if (nai == null) break;
11755
Aaron Huang959d3642021-01-21 15:47:41 +080011756 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011757 break;
11758 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011759 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011760 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011761 break;
11762 }
11763 default: {
11764 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11765 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011766 }
11767 }
11768 }
11769
11770 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11771 @VisibleForTesting
11772 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11773 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11774 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011775 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011776
11777 @VisibleForTesting
11778 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011779 @NonNull IConnectivityDiagnosticsCallback cb,
11780 @NonNull NetworkRequestInfo nri,
11781 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011782 mCb = cb;
11783 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011784 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011785 }
11786
11787 @Override
11788 public void binderDied() {
11789 log("ConnectivityDiagnosticsCallback IBinder died.");
11790 unregisterConnectivityDiagnosticsCallback(mCb);
11791 }
11792 }
11793
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011794 /**
11795 * Class used for sending information from {@link
11796 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11797 */
11798 private static class NetworkTestedResults {
11799 private final int mNetId;
11800 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011801 @Nullable private final String mRedirectUrl;
11802
11803 private NetworkTestedResults(
11804 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11805 mNetId = netId;
11806 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011807 mRedirectUrl = redirectUrl;
11808 }
11809 }
11810
11811 /**
11812 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11813 * ConnectivityDiagnosticsHandler}.
11814 */
11815 private static class ConnectivityReportEvent {
11816 private final long mTimestampMillis;
11817 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011818 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011819
Aaron Huang959d3642021-01-21 15:47:41 +080011820 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11821 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011822 mTimestampMillis = timestampMillis;
11823 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011824 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011825 }
11826 }
11827
Cody Kestingf1120be2020-08-03 18:01:40 -070011828 /**
11829 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11830 * ConnectivityDiagnosticsHandler}.
11831 */
11832 private static class ReportedNetworkConnectivityInfo {
11833 public final boolean hasConnectivity;
11834 public final boolean isNetworkRevalidating;
11835 public final int reporterUid;
11836 @NonNull public final NetworkAgentInfo nai;
11837
11838 private ReportedNetworkConnectivityInfo(
11839 boolean hasConnectivity,
11840 boolean isNetworkRevalidating,
11841 int reporterUid,
11842 @NonNull NetworkAgentInfo nai) {
11843 this.hasConnectivity = hasConnectivity;
11844 this.isNetworkRevalidating = isNetworkRevalidating;
11845 this.reporterUid = reporterUid;
11846 this.nai = nai;
11847 }
11848 }
11849
Cody Kesting73708bf2019-12-18 10:57:50 -080011850 private void handleRegisterConnectivityDiagnosticsCallback(
11851 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11852 ensureRunningOnConnectivityServiceThread();
11853
11854 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011855 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011856 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11857
James Mattis64b8b0f2020-11-24 17:40:49 -080011858 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11859 // confusing for these networks to change when an NRI is satisfied in another layer.
11860 if (nri.isMultilayerRequest()) {
11861 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11862 + "network requests.");
11863 }
11864
Cody Kesting73708bf2019-12-18 10:57:50 -080011865 // This means that the client registered the same callback multiple times. Do
11866 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011867 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011868 if (VDBG) log("Diagnostics callback is already registered");
11869
11870 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11871 // incremented when the NetworkRequestInfo is created as part of
11872 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011873 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011874 return;
11875 }
11876
Cody Kesting31f1ff62020-03-05 10:46:02 -080011877 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011878
11879 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011880 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011881 } catch (RemoteException e) {
11882 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011883 return;
11884 }
11885
11886 // Once registered, provide ConnectivityReports for matching Networks
11887 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11888 synchronized (mNetworkForNetId) {
11889 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11890 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011891 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11892 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011893 matchingNetworks.add(nai);
11894 }
11895 }
11896 }
11897 for (final NetworkAgentInfo nai : matchingNetworks) {
11898 final ConnectivityReport report = nai.getConnectivityReport();
11899 if (report == null) {
11900 continue;
11901 }
11902 if (!checkConnectivityDiagnosticsPermissions(
11903 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11904 continue;
11905 }
11906
11907 try {
11908 cb.onConnectivityReportAvailable(report);
11909 } catch (RemoteException e) {
11910 // Exception while sending the ConnectivityReport. Move on to the next network.
11911 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011912 }
11913 }
11914
11915 private void handleUnregisterConnectivityDiagnosticsCallback(
11916 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11917 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011918 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011919
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011920 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11921 mConnectivityDiagnosticsCallbacks.remove(iCb);
11922 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011923 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11924 return;
11925 }
11926
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011927 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011928
Cody Kesting70fa2b22020-12-02 12:16:56 -080011929 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11930 // (if the Binder died)
11931 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11932 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011933 return;
11934 }
11935
Cody Kesting46cb1672020-03-04 13:35:20 -080011936 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11937 // incremented when the NetworkRequestInfo is created as part of
11938 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011939 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011940
Cody Kesting31f1ff62020-03-05 10:46:02 -080011941 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011942 }
11943
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011944 private void handleNetworkTestedWithExtras(
11945 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11946 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011947 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011948 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011949 final ConnectivityReport report =
11950 new ConnectivityReport(
11951 reportEvent.mNai.network,
11952 reportEvent.mTimestampMillis,
11953 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011954 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011955 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011956 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011957
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011958 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011959 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011960 for (final IConnectivityDiagnosticsCallback cb : results) {
11961 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011962 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011963 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011964 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011965 }
11966 }
11967 }
11968
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011969 private void handleDataStallSuspected(
11970 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11971 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011972 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011973 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011974 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011975 new DataStallReport(
11976 nai.network,
11977 timestampMillis,
11978 detectionMethod,
11979 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011980 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011981 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011982 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011983 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011984 for (final IConnectivityDiagnosticsCallback cb : results) {
11985 try {
11986 cb.onDataStallSuspected(report);
11987 } catch (RemoteException ex) {
11988 loge("Error invoking onDataStallSuspected", ex);
11989 }
11990 }
11991 }
11992
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011993 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011994 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11995 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11996 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11997
11998 // If the Network is being re-validated as a result of this call to
11999 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
12000 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080012001 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070012002 getMatchingPermissionedCallbacks(
12003 nai,
12004 reportedNetworkConnectivityInfo.isNetworkRevalidating
12005 ? Process.INVALID_UID
12006 : reportedNetworkConnectivityInfo.reporterUid);
12007
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080012008 for (final IConnectivityDiagnosticsCallback cb : results) {
12009 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070012010 cb.onNetworkConnectivityReported(
12011 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080012012 } catch (RemoteException ex) {
12013 loge("Error invoking onNetworkConnectivityReported", ex);
12014 }
Cody Kestingf1120be2020-08-03 18:01:40 -070012015
12016 // If the Network isn't re-validating, also provide the cached report. If there is no
12017 // cached report, the Network is still being validated and a report will be sent once
12018 // validation is complete. Note that networks which never undergo validation will still
12019 // have a cached ConnectivityReport with RESULT_SKIPPED.
12020 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
12021 try {
12022 cb.onConnectivityReportAvailable(cachedReport);
12023 } catch (RemoteException ex) {
12024 loge("Error invoking onConnectivityReportAvailable", ex);
12025 }
12026 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080012027 }
12028 }
12029
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080012030 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090012031 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
12032 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080012033 sanitized.setUids(null);
12034 sanitized.setAdministratorUids(new int[0]);
12035 sanitized.setOwnerUid(Process.INVALID_UID);
12036 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080012037 }
12038
Cody Kestingf1120be2020-08-03 18:01:40 -070012039 /**
12040 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
12041 *
12042 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
12043 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012044 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070012045 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012046 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080012047 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012048 mConnectivityDiagnosticsCallbacks.entrySet()) {
12049 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
12050 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070012051
James Mattis64b8b0f2020-11-24 17:40:49 -080012052 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070012053 if (!nai.satisfies(nri.mRequests.get(0))) {
12054 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012055 }
Cody Kestingf1120be2020-08-03 18:01:40 -070012056
12057 // UID for this callback must either be:
12058 // - INVALID_UID (which sends callbacks to all UIDs), or
12059 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
12060 // notified as a result)
12061 if (uid != Process.INVALID_UID && uid != nri.mUid) {
12062 continue;
12063 }
12064
12065 if (!checkConnectivityDiagnosticsPermissions(
12066 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
12067 continue;
12068 }
12069
12070 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012071 }
12072 return results;
12073 }
12074
Cody Kesting7474f672021-05-11 14:22:40 -070012075 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
12076 @NonNull NetworkAgentInfo nai) {
12077 // TODO(b/188483916): replace with a transport-agnostic location-aware check
12078 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
12079 }
12080
Cody Kesting160ef392021-05-05 13:17:22 -070012081 private boolean hasLocationPermission(String packageName, int uid) {
12082 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
12083 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
12084 // call in a try-catch.
12085 try {
12086 if (!mLocationPermissionChecker.checkLocationPermission(
12087 packageName, null /* featureId */, uid, null /* message */)) {
12088 return false;
12089 }
12090 } catch (SecurityException e) {
12091 return false;
12092 }
12093
12094 return true;
12095 }
12096
12097 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
12098 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090012099 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070012100 && virtual.networkCapabilities.getOwnerUid() == uid
12101 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
12102 return true;
12103 }
12104 }
12105
12106 return false;
12107 }
12108
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012109 @VisibleForTesting
12110 boolean checkConnectivityDiagnosticsPermissions(
12111 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
12112 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
12113 return true;
12114 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090012115 if (mAllowSysUiConnectivityReports
12116 && checkSystemBarServicePermission(callbackPid, callbackUid)) {
12117 return true;
12118 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012119
Cody Kesting160ef392021-05-05 13:17:22 -070012120 // Administrator UIDs also contains the Owner UID
12121 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
12122 if (!CollectionUtils.contains(administratorUids, callbackUid)
12123 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012124 return false;
12125 }
12126
Cody Kesting7474f672021-05-11 14:22:40 -070012127 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
12128 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012129 }
12130
Cody Kestingd199a9d2019-12-17 12:55:28 -080012131 @Override
12132 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012133 @NonNull IConnectivityDiagnosticsCallback callback,
12134 @NonNull NetworkRequest request,
12135 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070012136 Objects.requireNonNull(callback, "callback must not be null");
12137 Objects.requireNonNull(request, "request must not be null");
12138 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
12139
Cody Kesting73708bf2019-12-18 10:57:50 -080012140 if (request.legacyType != TYPE_NONE) {
12141 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
12142 + " Please use NetworkCapabilities instead.");
12143 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090012144 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080012145 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080012146
12147 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
12148 // and administrator uids to be safe.
12149 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080012150 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080012151
12152 final NetworkRequest requestWithId =
12153 new NetworkRequest(
12154 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
12155
12156 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
12157 //
12158 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
12159 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
12160 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012161 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080012162 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012163 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080012164
12165 mConnectivityDiagnosticsHandler.sendMessage(
12166 mConnectivityDiagnosticsHandler.obtainMessage(
12167 ConnectivityDiagnosticsHandler
12168 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
12169 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080012170 }
12171
12172 @Override
12173 public void unregisterConnectivityDiagnosticsCallback(
12174 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012175 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080012176 mConnectivityDiagnosticsHandler.sendMessage(
12177 mConnectivityDiagnosticsHandler.obtainMessage(
12178 ConnectivityDiagnosticsHandler
12179 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090012180 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080012181 0,
12182 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080012183 }
Cody Kestingf53a0752020-04-15 12:33:28 -070012184
Yan Yanfe96dde2022-12-05 23:00:01 +000012185 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
12186 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
12187 if (underlyingNetworks == null) return false;
12188
12189 for (Network network : underlyingNetworks) {
12190 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
12191 return true;
12192 }
12193 }
12194 return false;
12195 }
12196
Cody Kestingf53a0752020-04-15 12:33:28 -070012197 @Override
12198 public void simulateDataStall(int detectionMethod, long timestampMillis,
12199 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070012200 Objects.requireNonNull(network, "network must not be null");
12201 Objects.requireNonNull(extras, "extras must not be null");
12202
paulhu3ffffe72021-09-16 10:15:22 +080012203 enforceAnyPermissionOf(mContext,
12204 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070012205 android.Manifest.permission.NETWORK_STACK);
12206 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000012207 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
12208 throw new SecurityException(
12209 "Data Stall simulation is only possible for test networks or networks built on"
12210 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070012211 }
12212
12213 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000012214 if (nai == null
12215 || (nai.creatorUid != mDeps.getCallingUid()
12216 && nai.creatorUid != Process.SYSTEM_UID)) {
12217 throw new SecurityException(
12218 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070012219 }
12220
Cody Kesting652e3ec2020-05-21 12:08:21 -070012221 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
12222 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
12223 // Data Stall information as a DataStallReportParcelable and passing to
12224 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
12225 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070012226 final DataStallReportParcelable p = new DataStallReportParcelable();
12227 p.timestampMillis = timestampMillis;
12228 p.detectionMethod = detectionMethod;
12229
12230 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
12231 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
12232 }
12233 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
12234 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
12235 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
12236 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
12237 }
12238
Serik Beketayevec8ad212020-12-07 22:43:07 -080012239 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070012240 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012241
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012242 /**
12243 * Class to hold the information for network activity change event from idle timers
12244 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
12245 */
12246 private static final class NetworkActivityParams {
12247 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012248 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
12249 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012250 public final int label;
12251 public final long timestampNs;
12252 // Uid represents the uid that was responsible for waking the radio.
12253 // -1 for no uid and uid is -1 if isActive is false.
12254 public final int uid;
12255
12256 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
12257 this.isActive = isActive;
12258 this.label = label;
12259 this.timestampNs = timestampNs;
12260 this.uid = uid;
12261 }
12262 }
12263
lucaslin66f44212021-02-23 01:12:55 +080012264 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
12265 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012266 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080012267 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012268 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
12269 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080012270 }
lucaslin37a16d92021-01-21 19:48:09 +080012271
12272 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090012273 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012274 mHandler.post(() -> {
12275 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090012276 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012277 }
12278 });
lucaslin37a16d92021-01-21 19:48:09 +080012279 }
12280
12281 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090012282 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012283 mHandler.post(() -> {
12284 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090012285 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012286 }
12287 });
lucaslin66f44212021-02-23 01:12:55 +080012288 }
12289 }
12290
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012291 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080012292 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
12293
12294 /**
12295 * Class used for updating network activity tracking with netd and notify network activity
12296 * changes.
12297 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012298 @VisibleForTesting
12299 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080012300 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080012301 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080012302 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012303 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080012304 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
12305 new RemoteCallbackList<>();
12306 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012307 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012308 // If there is no default network, default network is considered active to keep the existing
12309 // behavior. Initial value is used until first connect to the default network.
12310 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012311 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012312 // Key is netId. Value is configured idle timer information.
12313 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012314 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012315 // Store netIds of Wi-Fi networks whose idletimers report that they are active
12316 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
12317 // Store netIds of cellular networks whose idletimers report that they are active
12318 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080012319
Chalard Jean46bfbf02022-02-02 00:56:25 +090012320 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080012321 public final int timeout;
12322 public final int transportType;
12323
12324 IdleTimerParams(int timeout, int transport) {
12325 this.timeout = timeout;
12326 this.transportType = transport;
12327 }
12328 }
12329
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012330 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012331 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012332 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080012333 mNetd = netd;
12334 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012335 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080012336 }
12337
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012338 private void ensureRunningOnConnectivityServiceThread() {
12339 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
12340 throw new IllegalStateException("Not running on ConnectivityService thread: "
12341 + Thread.currentThread().getName());
lucaslin66f44212021-02-23 01:12:55 +080012342 }
12343 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012344
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012345 /**
12346 * Update network activity and call BatteryStats to update radio power state if the
12347 * mobile or Wi-Fi activity is changed.
12348 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
12349 * mobile network is active since BatteryStatsService only maintains a single power state
12350 * for the mobile network.
12351 * The Wi-Fi network is also the same.
12352 *
12353 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
12354 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
12355 * transports.
12356 */
12357 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
12358 final boolean isActive, final int uid) {
12359 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
12360 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
12361 + transportType);
12362 return;
12363 }
12364 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
12365 ? mActiveWifiNetworks : mActiveCellularNetworks;
12366
12367 final boolean wasEmpty = activeNetworks.isEmpty();
12368 if (isActive) {
12369 activeNetworks.add(netId);
12370 } else {
12371 activeNetworks.remove(netId);
12372 }
12373
12374 if (wasEmpty != activeNetworks.isEmpty()) {
12375 updateRadioPowerState(isActive, transportType, uid);
12376 }
12377 }
12378
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012379 private void handleDefaultNetworkActivity(final int transportType,
12380 final boolean isActive, final long timestampNs) {
12381 mIsDefaultNetworkActive = isActive;
12382 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
12383 isActive, timestampNs);
12384 if (isActive) {
12385 reportNetworkActive();
12386 }
12387 }
12388
12389 private void handleReportNetworkActivityWithNetIdLabel(
12390 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012391 final int netId = activityParams.label;
12392 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012393 if (idleTimerParams == null) {
12394 // This network activity change is not tracked anymore
12395 // This can happen if netd callback post activity change event message but idle
12396 // timer is removed before processing this message.
12397 return;
12398 }
12399 // TODO: if a network changes transports, storing the transport type in the
12400 // IdleTimerParams is not correct. Consider getting it from the network's
12401 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012402 final int transportType = idleTimerParams.transportType;
12403 maybeUpdateRadioPowerState(netId, transportType,
12404 activityParams.isActive, activityParams.uid);
12405
12406 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
12407 // This activity change is not for the default network.
12408 return;
12409 }
12410
12411 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012412 activityParams.timestampNs);
12413 }
12414
12415 private void handleReportNetworkActivityWithTransportTypeLabel(
12416 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012417 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012418 // This activity change is not for the current default network.
12419 // This can happen if netd callback post activity change event message but
12420 // the default network is lost before processing this message.
12421 return;
12422 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012423 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
12424 activityParams.timestampNs);
12425 }
12426
12427 /**
12428 * Handle network activity change
12429 */
12430 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
12431 ensureRunningOnConnectivityServiceThread();
12432 if (mTrackMultiNetworkActivities) {
12433 handleReportNetworkActivityWithNetIdLabel(activityParams);
12434 } else {
12435 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin1a8b4c62021-01-21 02:02:55 +080012436 }
12437 }
12438
lucaslin1193a5d2021-01-21 02:04:15 +080012439 private void reportNetworkActive() {
12440 final int length = mNetworkActivityListeners.beginBroadcast();
12441 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
12442 try {
12443 for (int i = 0; i < length; i++) {
12444 try {
12445 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
12446 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012447 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080012448 }
12449 }
12450 } finally {
12451 mNetworkActivityListeners.finishBroadcast();
12452 }
12453 }
12454
lucaslin1a8b4c62021-01-21 02:02:55 +080012455 // This is deprecated and only to support legacy use cases.
12456 private int transportTypeToLegacyType(int type) {
12457 switch (type) {
12458 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012459 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080012460 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012461 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080012462 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012463 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080012464 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012465 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080012466 default:
12467 loge("Unexpected transport in transportTypeToLegacyType: " + type);
12468 }
12469 return ConnectivityManager.TYPE_NONE;
12470 }
12471
12472 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12473 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12474 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12475 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12476 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12477 final long ident = Binder.clearCallingIdentity();
12478 try {
12479 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12480 RECEIVE_DATA_ACTIVITY_CHANGE,
12481 null /* resultReceiver */,
12482 null /* scheduler */,
12483 0 /* initialCode */,
12484 null /* initialData */,
12485 null /* initialExtra */);
12486 } finally {
12487 Binder.restoreCallingIdentity(ident);
12488 }
12489 }
12490
12491 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012492 * Get idle timer label
12493 */
12494 @VisibleForTesting
12495 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12496 final int netId, final int transportType) {
12497 return trackMultiNetworkActivities ? netId : transportType;
12498 }
12499
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012500 private boolean maybeCreateIdleTimer(
12501 String iface, int netId, int timeout, int transportType) {
12502 if (timeout <= 0 || iface == null) return false;
12503 try {
12504 final String label = Integer.toString(getIdleTimerLabel(
12505 mTrackMultiNetworkActivities, netId, transportType));
12506 mNetd.idletimerAddInterface(iface, timeout, label);
12507 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12508 return true;
12509 } catch (Exception e) {
12510 loge("Exception in createIdleTimer", e);
12511 return false;
12512 }
12513 }
12514
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012515 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012516 * Setup data activity tracking for the given network.
12517 *
12518 * Every {@code setupDataActivityTracking} should be paired with a
12519 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012520 *
12521 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012522 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012523 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012524 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012525 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012526 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012527
12528 final int timeout;
12529 final int type;
12530
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012531 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12532 // Do not track VPN network.
12533 return false;
12534 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012535 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12536 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012537 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012538 10);
12539 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12540 } else if (networkAgent.networkCapabilities.hasTransport(
12541 NetworkCapabilities.TRANSPORT_WIFI)) {
12542 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012543 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012544 15);
12545 type = NetworkCapabilities.TRANSPORT_WIFI;
12546 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012547 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012548 }
12549
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012550 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12551 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12552 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12553 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12554 // state only about a network that has an idletimer.
12555 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012556 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012557 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012558 }
12559
12560 /**
12561 * Remove data activity tracking when network disconnects.
12562 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012563 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12564 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012565 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012566 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012567 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12568
lucaslinb961efc2021-01-21 02:03:17 +080012569 if (iface == null) return;
12570
12571 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012572 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12573 // Do not track VPN network.
12574 return;
12575 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012576 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12577 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12578 type = NetworkCapabilities.TRANSPORT_WIFI;
12579 } else {
12580 return; // do not track any other networks
12581 }
12582
12583 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012584 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012585 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012586 if (params == null) {
12587 // IdleTimer is not added if the configured timeout is 0 or negative value
12588 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012589 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012590 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012591 final String label = Integer.toString(getIdleTimerLabel(
12592 mTrackMultiNetworkActivities, netId, params.transportType));
12593 // The call fails silently if no idle timer setup for this interface
12594 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012595 } catch (Exception e) {
12596 // You shall not crash!
12597 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012598 }
12599 }
12600
Motomu Utsumi6225d572023-05-29 15:08:57 +090012601 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12602 boolean hasIdleTimer) {
12603 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012604 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012605 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012606 // If only the default network is tracked, callbacks are called only when the
12607 // network has the idle timer.
12608 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012609 reportNetworkActive();
12610 }
12611 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012612 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012613 // If there is no default network, default network is considered active to keep the
12614 // existing behavior.
12615 mIsDefaultNetworkActive = true;
lucaslin1a8b4c62021-01-21 02:02:55 +080012616 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012617 }
12618
lucaslin1a8b4c62021-01-21 02:02:55 +080012619 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012620 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012621 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012622 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012623 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012624 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012625 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12626 // first connected and remove when the network is disconnected.
12627 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12628 // becomes the default network and remove when the network becomes no longer the default
12629 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012630 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012631 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012632 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012633 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012634 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012635 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012636 removeDataActivityTracking(oldNetwork);
12637 }
12638 }
lucaslinb961efc2021-01-21 02:03:17 +080012639
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012640 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012641 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12642 switch (transportType) {
12643 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012644 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012645 break;
12646 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012647 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012648 break;
12649 default:
12650 logw("Untracked transport type:" + transportType);
12651 }
12652 }
lucaslin1193a5d2021-01-21 02:04:15 +080012653
12654 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012655 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012656 }
12657
12658 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12659 mNetworkActivityListeners.register(l);
12660 }
12661
12662 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12663 mNetworkActivityListeners.unregister(l);
12664 }
lucaslin012f7a12021-01-21 02:04:35 +080012665
12666 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012667 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012668 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012669 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012670 pw.println("Idle timers:");
12671 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012672 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12673 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12674 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012675 pw.print(" timeout="); pw.print(params.timeout);
12676 pw.print(" type="); pw.println(params.transportType);
12677 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012678 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12679 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012680 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012681 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12682 // be accessed from handler thread, except dump(). As dump() is never called in
12683 // normal usage, it would be needlessly expensive to lock the collection only for
12684 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012685 // So catching the exception and logging.
12686 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012687 }
12688 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012689 }
James Mattis47db0582021-01-01 14:13:35 -080012690
Daniel Brightf9e945b2020-06-15 16:10:01 -070012691 /**
12692 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12693 *
12694 * @param socketInfo the socket information
12695 * @param callback the callback to register
12696 */
12697 @Override
12698 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12699 @NonNull final IQosCallback callback) {
12700 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12701 if (nai == null || nai.networkCapabilities == null) {
12702 try {
12703 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12704 } catch (final RemoteException ex) {
12705 loge("registerQosCallbackInternal: RemoteException", ex);
12706 }
12707 return;
12708 }
12709 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12710 }
12711
12712 /**
12713 * Register a {@link IQosCallback} with base {@link QosFilter}.
12714 *
12715 * @param filter the filter to register
12716 * @param callback the callback to register
12717 * @param nai the agent information related to the filter's network
12718 */
12719 @VisibleForTesting
12720 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12721 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012722 Objects.requireNonNull(filter, "filter must be non-null");
12723 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012724
12725 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012726 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12727 // on this network is unregistered when the app loses permission or b) no QoS
12728 // callbacks are sent for restricted networks unless the app currently has permission
12729 // to access restricted networks.
12730 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012731 }
12732 mQosCallbackTracker.registerCallback(callback, filter, nai);
12733 }
12734
12735 /**
12736 * Unregisters the given callback.
12737 *
12738 * @param callback the callback to unregister
12739 */
12740 @Override
12741 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012742 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012743 mQosCallbackTracker.unregisterCallback(callback);
12744 }
James Mattis47db0582021-01-01 14:13:35 -080012745
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012746 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12747 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12748 // Enterprise device can be fully managed like device owner and such use case
12749 // also should be supported. Calling app check for work profile and fully managed device
12750 // is already done in DevicePolicyManager.
12751 // This check is an extra caution to be sure device is fully managed or not.
12752 final UserManager um = mContext.getSystemService(UserManager.class);
12753 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12754 if (um.isManagedProfile(profile.getIdentifier())) {
12755 return true;
12756 }
Chalard Jean03552c42023-05-29 17:02:43 +090012757 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012758 return false;
12759 }
12760
James Mattis45d81842021-01-10 14:24:24 -080012761 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012762 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012763 *
12764 * See the documentation for the individual preferences for a description of the supported
12765 * behaviors.
12766 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012767 * @param profile If the device owner is set, any profile is allowed.
12768 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012769 * @param preferences the list of profile network preferences for the
12770 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012771 * @param listener an optional listener to listen for completion of the operation.
12772 */
12773 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012774 public void setProfileNetworkPreferences(
12775 @NonNull final UserHandle profile,
12776 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012777 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012778 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012779 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012780
12781 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012782 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12783 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12784 .build();
12785 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012786 }
12787
paulhu3ffffe72021-09-16 10:15:22 +080012788 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012789 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012790 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012791 }
12792 if (profile.getIdentifier() < 0) {
12793 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12794 + "UserHandle.CURRENT not supported)");
12795 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012796 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12797 throw new IllegalArgumentException("Profile must be a managed profile "
12798 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012799 }
paulhuaa0743d2021-05-26 21:56:03 +080012800
Chalard Jean0606fc82022-12-14 20:34:43 +090012801 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012802 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012803 for (final ProfileNetworkPreference preference : preferences) {
12804 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012805 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012806 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012807 switch (preference.getPreference()) {
12808 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12809 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012810 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012811 if (preference.getPreferenceEnterpriseId() != 0) {
12812 throw new IllegalArgumentException(
12813 "Invalid enterprise identifier in setProfileNetworkPreferences");
12814 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012815 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012816 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12817 blockingNonEnterprise = true;
12818 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012819 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12820 allowFallback = false;
12821 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012822 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012823 // This code is needed even though there is a check later on,
12824 // because isRangeAlreadyInPreferenceList assumes that every preference
12825 // has a UID list.
12826 if (hasDefaultPreference) {
12827 throw new IllegalArgumentException(
12828 "Default profile preference should not be set along with other "
12829 + "preference");
12830 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012831 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12832 throw new IllegalArgumentException(
12833 "Invalid enterprise identifier in setProfileNetworkPreferences");
12834 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012835 final Set<UidRange> uidRangeSet =
12836 getUidListToBeAppliedForNetworkPreference(profile, preference);
12837 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12838 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12839 } else {
12840 throw new IllegalArgumentException(
12841 "Overlapping uid range in setProfileNetworkPreferences");
12842 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012843 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012844 nc.addEnterpriseId(
12845 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012846 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12847 break;
12848 default:
12849 throw new IllegalArgumentException(
12850 "Invalid preference in setProfileNetworkPreferences");
12851 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012852 preferenceList.add(new ProfileNetworkPreferenceInfo(
12853 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012854 if (hasDefaultPreference && preferenceList.size() > 1) {
12855 throw new IllegalArgumentException(
12856 "Default profile preference should not be set along with other preference");
12857 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012858 }
12859 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012860 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012861 }
12862
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012863 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12864 @NonNull final UserHandle profile,
12865 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12866 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012867 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12868 profileNetworkPreference.getIncludedUids());
12869
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012870 if (uidRangeSet.size() > 0) {
12871 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12872 throw new IllegalArgumentException(
12873 "Allow uid range is outside the uid range of profile.");
12874 }
12875 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012876 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012877 profileNetworkPreference.getExcludedUids());
12878 if (disallowUidRangeSet.size() > 0) {
12879 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12880 throw new IllegalArgumentException(
12881 "disallow uid range is outside the uid range of profile.");
12882 }
12883 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12884 disallowUidRangeSet);
12885 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012886 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012887 uidRangeSet.add(profileUids);
12888 }
12889 }
12890 return uidRangeSet;
12891 }
12892
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012893 private boolean isEnterpriseIdentifierValid(
12894 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012895 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012896 return true;
12897 }
12898 return false;
12899 }
12900
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012901 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012902 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012903 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012904 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012905 // The NRI for a user should contain the request for capabilities.
12906 // If fallback to default network is needed then NRI should include
12907 // the request for the default network. Create an image of it to
12908 // have the correct UIDs in it (also a request can only be part of one NRI, because
12909 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012910 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12911 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012912 if (pref.allowFallback) {
12913 nrs.add(createDefaultInternetRequestForTransport(
12914 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12915 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012916 if (VDBG) {
12917 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12918 pref.capabilities.getUids()));
12919 }
12920
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012921 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012922 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012923 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012924 result.add(nri);
12925 }
12926 return result;
12927 }
12928
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012929 /**
12930 * Compare if the given UID range sets have the same UIDs.
12931 *
12932 */
12933 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012934 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012935 @NonNull Set<UidRange> uidRangeSet) {
12936 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12937 return false;
12938 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012939 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012940 if (UidRangeUtils.doesRangeSetOverlap(
12941 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12942 return true;
12943 }
12944 }
12945 return false;
12946 }
12947
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012948 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012949 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012950 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012951 /*
12952 * handleSetProfileNetworkPreference is always called for single user.
12953 * preferenceList only contains preferences for different uids within the same user
12954 * (enforced by getUidListToBeAppliedForNetworkPreference).
12955 * Clear all the existing preferences for the user before applying new preferences.
12956 *
12957 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012958 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12959 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012960 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12961 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012962
paulhu74128522021-09-28 02:29:03 +000012963 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12964 addPerAppDefaultNetworkRequests(
12965 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012966 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012967
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012968 // Finally, rematch.
12969 rematchAllNetworksAndRequests();
12970
12971 if (null != listener) {
12972 try {
12973 listener.onComplete();
12974 } catch (RemoteException e) {
12975 loge("Listener for setProfileNetworkPreference has died");
12976 }
12977 }
12978 }
12979
paulhu51f77dc2021-06-07 02:34:20 +000012980 @VisibleForTesting
12981 @NonNull
12982 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12983 @NonNull final Set<Integer> uids) {
12984 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12985 if (uids.size() == 0) {
12986 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12987 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12988 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12989 return nris;
12990 }
12991
12992 final List<NetworkRequest> requests = new ArrayList<>();
12993 // The NRI should be comprised of two layers:
12994 // - The request for the mobile network preferred.
12995 // - The request for the default network, for fallback.
12996 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012997 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012998 requests.add(createDefaultInternetRequestForTransport(
12999 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
13000 final Set<UidRange> ranges = new ArraySet<>();
13001 for (final int uid : uids) {
13002 ranges.add(new UidRange(uid, uid));
13003 }
13004 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080013005 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080013006 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000013007 return nris;
13008 }
13009
13010 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000013011 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000013012 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
13013 addPerAppDefaultNetworkRequests(
13014 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000013015 // Finally, rematch.
13016 rematchAllNetworksAndRequests();
13017 }
13018
Patrick Rohr2857ac42022-01-21 14:58:16 +010013019 private void handleIngressRateLimitChanged() {
13020 final long oldIngressRateLimit = mIngressRateLimit;
13021 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
13022 mContext);
13023 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
13024 if (canNetworkBeRateLimited(networkAgent)) {
13025 // If rate limit has previously been enabled, remove the old limit first.
13026 if (oldIngressRateLimit >= 0) {
13027 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
13028 }
13029 if (mIngressRateLimit >= 0) {
13030 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
13031 mIngressRateLimit);
13032 }
13033 }
13034 }
13035 }
13036
13037 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090013038 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jean03552c42023-05-29 17:02:43 +090013039 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090013040
Patrick Rohrff3b3f82022-02-09 15:15:52 +010013041 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
13042 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
13043 // internet connectivity can be rate limited.
13044 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
13045 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010013046 return false;
13047 }
13048
13049 final String iface = networkAgent.linkProperties.getInterfaceName();
13050 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010013051 // This may happen in tests, but if there is no interface then there is nothing that
13052 // can be rate limited.
13053 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010013054 return false;
13055 }
13056 return true;
13057 }
13058
James Mattis45d81842021-01-10 14:24:24 -080013059 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080013060 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
13061 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080013062 }
13063
13064 /**
13065 * Used by automotive devices to set the network preferences used to direct traffic at an
13066 * application level as per the given OemNetworkPreferences. An example use-case would be an
13067 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
13068 * vehicle via a particular network.
13069 *
13070 * Calling this will overwrite the existing preference.
13071 *
James Mattisda32cfe2021-01-26 16:23:52 -080013072 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090013073 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080013074 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080013075 */
James Mattis47db0582021-01-01 14:13:35 -080013076 @Override
James Mattis45d81842021-01-10 14:24:24 -080013077 public void setOemNetworkPreference(
13078 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090013079 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080013080
James Mattisfa270db2021-05-31 17:11:10 -070013081 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
13082 // Only bypass the permission/device checks if this is a valid test request.
13083 if (isValidTestOemNetworkPreference(preference)) {
13084 enforceManageTestNetworksPermission();
13085 } else {
13086 enforceAutomotiveDevice();
13087 enforceOemNetworkPreferencesPermission();
13088 validateOemNetworkPreferences(preference);
13089 }
James Mattis45d81842021-01-10 14:24:24 -080013090
James Mattis45d81842021-01-10 14:24:24 -080013091 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
13092 new Pair<>(preference, listener)));
13093 }
13094
James Mattisfa270db2021-05-31 17:11:10 -070013095 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000013096 * Sets the specified UIDs to get/receive the VPN as the only default network.
13097 *
13098 * Calling this will overwrite the existing network preference for this session, and the
13099 * specified UIDs won't get any default network when no VPN is connected.
13100 *
13101 * @param session The VPN session which manages the passed UIDs.
13102 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
13103 * setting for this session if the array is empty. Null is not allowed, the
13104 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
13105 * @hide
13106 */
13107 @Override
13108 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
13109 Objects.requireNonNull(ranges);
13110 enforceNetworkStackOrSettingsPermission();
13111 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
13112 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
13113 throw new IllegalArgumentException(
13114 "setVpnNetworkPreference: Passed UID ranges overlap");
13115 }
13116
13117 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
13118 new VpnNetworkPreferenceInfo(session,
13119 new ArraySet<UidRange>(Arrays.asList(ranges)))));
13120 }
13121
13122 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
13123 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
13124
13125 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
13126 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
13127
13128 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
13129 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
13130 // Finally, rematch.
13131 rematchAllNetworksAndRequests();
13132 }
13133
13134 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
13135 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
13136 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
13137 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
13138 final List<NetworkRequest> requests = new ArrayList<>();
13139 // Request VPN only, so other networks won't be the fallback options when VPN is not
13140 // connected temporarily.
13141 requests.add(createVpnRequest());
13142 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
13143 setNetworkRequestUids(requests, uidRanges);
13144 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
13145 }
13146 return nris;
13147 }
13148
13149 /**
James Mattisfa270db2021-05-31 17:11:10 -070013150 * Check the validity of an OEM network preference to be used for testing purposes.
13151 * @param preference the preference to validate
13152 * @return true if this is a valid OEM network preference test request.
13153 */
13154 private boolean isValidTestOemNetworkPreference(
13155 @NonNull final OemNetworkPreferences preference) {
13156 // Allow for clearing of an existing OemNetworkPreference used for testing.
13157 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
13158 // changes after this check is complete. This is an unlikely scenario as calling of this API
13159 // is controlled by the OEM therefore the added complexity is not worth adding given those
13160 // circumstances. That said, it is an edge case to be aware of hence this comment.
13161 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
13162 && isTestOemNetworkPreference(mOemNetworkPreferences);
13163 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
13164 }
13165
13166 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
13167 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
13168 return prefMap.size() == 1
13169 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
13170 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
13171 }
13172
James Mattis45d81842021-01-10 14:24:24 -080013173 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
13174 for (@OemNetworkPreferences.OemNetworkPreference final int pref
13175 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070013176 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
13177 throw new IllegalArgumentException(
13178 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
13179 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080013180 }
13181 }
13182 }
13183
13184 private void handleSetOemNetworkPreference(
13185 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090013186 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080013187 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
13188 if (DBG) {
13189 log("set OEM network preferences :" + preference.toString());
13190 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090013191
James Mattiscb1e0362021-04-06 17:07:42 -070013192 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000013193 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
13194 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
13195 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080013196 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080013197
13198 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090013199 try {
13200 listener.onComplete();
13201 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080013202 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090013203 }
James Mattis45d81842021-01-10 14:24:24 -080013204 }
13205 }
13206
paulhu74128522021-09-28 02:29:03 +000013207 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080013208 // Skip the requests which are set by other network preference. Because the uid range rules
13209 // should stay in netd.
13210 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080013211 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080013212 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080013213 }
13214
James Mattis3ce3d3c2021-02-09 18:18:28 -080013215 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
13216 ensureRunningOnConnectivityServiceThread();
13217 mDefaultNetworkRequests.addAll(nris);
13218 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
13219 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080013220 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000013221 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
13222 nrisToRegister.addAll(
13223 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
13224 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013225 }
13226
13227 /**
13228 * All current requests that are tracking the default network need to be assessed as to whether
13229 * or not the current set of per-application default requests will be changing their default
13230 * network. If so, those requests will need to be updated so that they will send callbacks for
13231 * default network changes at the appropriate time. Additionally, those requests tracking the
13232 * default that were previously updated by this flow will need to be reassessed.
13233 * @return the nris which will need to be updated.
13234 */
13235 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
13236 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
13237 // Get the distinct nris to check since for multilayer requests, it is possible to have the
13238 // same nri in the map's values for each of its NetworkRequest objects.
13239 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080013240 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013241 // Include this nri if it is currently being tracked.
13242 if (isPerAppTrackedNri(nri)) {
13243 defaultCallbackRequests.add(nri);
13244 continue;
13245 }
13246 // We only track callbacks for requests tracking the default.
13247 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
13248 continue;
13249 }
13250 // Include this nri if it will be tracked by the new per-app default requests.
13251 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013252 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080013253 if (isNriGoingToBeTracked) {
13254 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080013255 }
13256 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080013257 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080013258 }
13259
James Mattis3ce3d3c2021-02-09 18:18:28 -080013260 /**
13261 * Create nris for those network requests that are currently tracking the default network that
13262 * are being controlled by a per-application default.
13263 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
13264 * foundation when creating the nri. Important items include the calling uid's original
13265 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
13266 * requests are assumed to have already been validated as needing to be updated.
13267 * @return the Set of nris to use when registering network requests.
13268 */
13269 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
13270 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
13271 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
13272 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
13273 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013274 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013275
Chalard Jean9473c982021-07-29 20:03:04 +090013276 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080013277 if (trackingNri == mDefaultRequest) {
13278 callbackRequestsToRegister.add(new NetworkRequestInfo(
13279 callbackRequest,
13280 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
13281 continue;
13282 }
13283
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013284 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013285 callbackRequestsToRegister.add(new NetworkRequestInfo(
13286 callbackRequest,
13287 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013288 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090013289 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080013290 }
13291 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080013292 }
13293
Chalard Jean17215832021-03-01 14:06:28 +090013294 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
13295 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090013296 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000013297 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090013298 }
13299 }
13300
James Mattis45d81842021-01-10 14:24:24 -080013301 /**
13302 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
13303 */
13304 @VisibleForTesting
13305 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013306 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080013307 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013308 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080013309 final SparseArray<Set<Integer>> uids =
13310 createUidsFromOemNetworkPreferences(preference);
13311 for (int i = 0; i < uids.size(); i++) {
13312 final int key = uids.keyAt(i);
13313 final Set<Integer> value = uids.valueAt(i);
13314 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
13315 // No need to add an nri without any requests.
13316 if (0 == nri.mRequests.size()) {
13317 continue;
13318 }
13319 nris.add(nri);
13320 }
13321
13322 return nris;
13323 }
13324
13325 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
13326 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070013327 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080013328 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080013329 final List<UserHandle> users =
13330 mContext.getSystemService(UserManager.class).getUserHandles(true);
13331 if (null == users || users.size() == 0) {
13332 if (VDBG || DDBG) {
13333 log("No users currently available for setting the OEM network preference.");
13334 }
James Mattisb6b6a432021-06-01 22:30:36 -070013335 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080013336 }
James Mattis45d81842021-01-10 14:24:24 -080013337 for (final Map.Entry<String, Integer> entry :
13338 preference.getNetworkPreferences().entrySet()) {
13339 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070013340 // Add the rules for all users as this policy is device wide.
13341 for (final UserHandle user : users) {
13342 try {
13343 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
13344 if (!prefToUids.contains(pref)) {
13345 prefToUids.put(pref, new ArraySet<>());
13346 }
13347 prefToUids.get(pref).add(uid);
13348 } catch (PackageManager.NameNotFoundException e) {
13349 // Although this may seem like an error scenario, it is ok that uninstalled
13350 // packages are sent on a network preference as the system will watch for
13351 // package installations associated with this network preference and update
13352 // accordingly. This is done to minimize race conditions on app install.
13353 continue;
James Mattis45d81842021-01-10 14:24:24 -080013354 }
James Mattis45d81842021-01-10 14:24:24 -080013355 }
13356 }
James Mattisb6b6a432021-06-01 22:30:36 -070013357 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080013358 }
13359
13360 private NetworkRequestInfo createNriFromOemNetworkPreferences(
13361 @OemNetworkPreferences.OemNetworkPreference final int preference,
13362 @NonNull final Set<Integer> uids) {
13363 final List<NetworkRequest> requests = new ArrayList<>();
13364 // Requests will ultimately be evaluated by order of insertion therefore it matters.
13365 switch (preference) {
13366 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
13367 requests.add(createUnmeteredNetworkRequest());
13368 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070013369 requests.add(createDefaultInternetRequestForTransport(
13370 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080013371 break;
13372 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
13373 requests.add(createUnmeteredNetworkRequest());
13374 requests.add(createOemPaidNetworkRequest());
13375 break;
13376 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
13377 requests.add(createOemPaidNetworkRequest());
13378 break;
13379 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
13380 requests.add(createOemPrivateNetworkRequest());
13381 break;
James Mattisfa270db2021-05-31 17:11:10 -070013382 case OEM_NETWORK_PREFERENCE_TEST:
13383 requests.add(createUnmeteredNetworkRequest());
13384 requests.add(createTestNetworkRequest());
13385 requests.add(createDefaultRequest());
13386 break;
13387 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
13388 requests.add(createTestNetworkRequest());
13389 break;
James Mattis45d81842021-01-10 14:24:24 -080013390 default:
13391 // This should never happen.
13392 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
13393 + " called with invalid preference of " + preference);
13394 }
13395
James Mattisfa270db2021-05-31 17:11:10 -070013396 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090013397 for (final int uid : uids) {
13398 ranges.add(new UidRange(uid, uid));
13399 }
13400 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080013401 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080013402 }
13403
13404 private NetworkRequest createUnmeteredNetworkRequest() {
13405 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13406 .addCapability(NET_CAPABILITY_NOT_METERED)
13407 .addCapability(NET_CAPABILITY_VALIDATED);
13408 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
13409 }
13410
13411 private NetworkRequest createOemPaidNetworkRequest() {
13412 // NET_CAPABILITY_OEM_PAID is a restricted capability.
13413 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13414 .addCapability(NET_CAPABILITY_OEM_PAID)
13415 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13416 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13417 }
13418
13419 private NetworkRequest createOemPrivateNetworkRequest() {
13420 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
13421 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13422 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
13423 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13424 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13425 }
13426
13427 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070013428 final NetworkCapabilities netcap = new NetworkCapabilities();
13429 netcap.addCapability(NET_CAPABILITY_INTERNET);
13430 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
13431 return netcap;
13432 }
13433
13434 private NetworkRequest createTestNetworkRequest() {
13435 final NetworkCapabilities netcap = new NetworkCapabilities();
13436 netcap.clearAll();
13437 netcap.addTransportType(TRANSPORT_TEST);
13438 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080013439 }
James Mattis47db0582021-01-01 14:13:35 -080013440 }
markchien738ad912021-12-09 18:15:45 +080013441
Junyu Lai38c75032023-12-04 07:52:19 +000013442 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080013443 @Override
Junyu Laidf210362023-10-24 02:47:50 +000013444 public void setDataSaverEnabled(final boolean enable) {
13445 enforceNetworkStackOrSettingsPermission();
13446 try {
13447 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
13448 if (!ret) {
13449 throw new IllegalStateException("Error when changing iptables: " + enable);
13450 }
13451 } catch (RemoteException e) {
13452 // Lack of permission or binder errors.
13453 throw new IllegalStateException(e);
13454 }
Ken Chen24330172023-10-20 13:02:14 +080013455
13456 try {
13457 mBpfNetMaps.setDataSaverEnabled(enable);
13458 } catch (ServiceSpecificException | UnsupportedOperationException e) {
13459 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
13460 }
Junyu Laidf210362023-10-24 02:47:50 +000013461 }
13462
markchien738ad912021-12-09 18:15:45 +080013463 @Override
13464 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
13465 enforceNetworkStackOrSettingsPermission();
13466
13467 try {
13468 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013469 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013470 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013471 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013472 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013473 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013474 throw new IllegalStateException(e);
13475 }
13476 }
13477
13478 @Override
13479 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13480 enforceNetworkStackOrSettingsPermission();
13481
13482 try {
13483 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013484 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013485 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013486 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013487 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013488 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013489 throw new IllegalStateException(e);
13490 }
13491 }
markchiene1561fa2021-12-09 22:00:56 +080013492
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013493 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13494 throws PackageManager.NameNotFoundException {
13495 final PackageManager pm = mContext.getPackageManager();
13496 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13497 if (appId < Process.FIRST_APPLICATION_UID) {
13498 throw new RuntimeException("Can't set package firewall rule for system app "
13499 + packageName + " with appId " + appId);
13500 }
13501 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13502 final int uid = uh.getUid(appId);
13503 setUidFirewallRule(chain, uid, rule);
13504 }
13505 return appId;
13506 }
13507
markchiene1561fa2021-12-09 22:00:56 +080013508 @Override
markchien3c04e662022-03-22 16:29:56 +080013509 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013510 enforceNetworkStackOrSettingsPermission();
13511
markchien3c04e662022-03-22 16:29:56 +080013512 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13513 int firewallRule = getFirewallRuleType(chain, rule);
13514
13515 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13516 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13517 }
13518
markchiene1561fa2021-12-09 22:00:56 +080013519 try {
markchien3c04e662022-03-22 16:29:56 +080013520 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013521 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013522 throw new IllegalStateException(e);
13523 }
13524 }
markchien98a6f952022-01-13 23:43:53 +080013525
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013526 private int getPackageFirewallRule(final int chain, final String packageName)
13527 throws PackageManager.NameNotFoundException {
13528 final PackageManager pm = mContext.getPackageManager();
13529 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13530 return getUidFirewallRule(chain, appId);
13531 }
13532
Motomu Utsumi900b8062023-01-19 16:16:49 +090013533 @Override
13534 public int getUidFirewallRule(final int chain, final int uid) {
13535 enforceNetworkStackOrSettingsPermission();
13536 return mBpfNetMaps.getUidRule(chain, uid);
13537 }
13538
markchien3c04e662022-03-22 16:29:56 +080013539 private int getFirewallRuleType(int chain, int rule) {
13540 final int defaultRule;
13541 switch (chain) {
13542 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013543 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13544 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013545 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013546 defaultRule = FIREWALL_RULE_ALLOW;
13547 break;
13548 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13549 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13550 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13551 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013552 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013553 defaultRule = FIREWALL_RULE_DENY;
13554 break;
13555 default:
13556 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13557 }
13558 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13559
13560 return rule;
13561 }
13562
Motomu Utsumied1848c2023-03-28 18:08:12 +090013563 private void closeSocketsForFirewallChainLocked(final int chain)
13564 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013565 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumied1848c2023-03-28 18:08:12 +090013566 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13567 // So, close all non-system socket owned by uids that are not explicitly allowed
13568 Set<Range<Integer>> ranges = new ArraySet<>();
13569 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13570 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13571 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13572 } else {
13573 // Denylist means the firewall allows all by default, uids must be explicitly denied
13574 // So, close socket owned by uids that are explicitly denied
13575 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13576 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13577 }
13578 }
13579
markchien98a6f952022-01-13 23:43:53 +080013580 @Override
13581 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13582 enforceNetworkStackOrSettingsPermission();
13583
13584 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013585 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013586 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013587 throw new IllegalStateException(e);
13588 }
Motomu Utsumied1848c2023-03-28 18:08:12 +090013589
Chalard Jean03552c42023-05-29 17:02:43 +090013590 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumied1848c2023-03-28 18:08:12 +090013591 try {
13592 closeSocketsForFirewallChainLocked(chain);
13593 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13594 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13595 }
13596 }
markchien98a6f952022-01-13 23:43:53 +080013597 }
13598
markchien00a0bed2022-01-13 23:46:13 +080013599 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013600 public boolean getFirewallChainEnabled(final int chain) {
13601 enforceNetworkStackOrSettingsPermission();
13602
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013603 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013604 }
13605
13606 @Override
markchien00a0bed2022-01-13 23:46:13 +080013607 public void replaceFirewallChain(final int chain, final int[] uids) {
13608 enforceNetworkStackOrSettingsPermission();
13609
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013610 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013611 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013612
13613 @Override
13614 public IBinder getCompanionDeviceManagerProxyService() {
13615 enforceNetworkStackPermission(mContext);
13616 return mCdmps;
13617 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013618
13619 @Override
13620 public IBinder getRoutingCoordinatorService() {
13621 enforceNetworkStackPermission(mContext);
13622 return mRoutingCoordinatorService;
13623 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013624}