blob: 339132327560ddee38734af666cc52ad4552ba94 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Mark Fasheh7c999d82023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
Chalard Jeane0aaca52023-10-17 13:23:07 +090022import static android.content.pm.PackageManager.FEATURE_LEANBACK;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090023import static android.content.pm.PackageManager.FEATURE_WATCH;
24import static android.content.pm.PackageManager.FEATURE_WIFI;
25import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090026import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090027import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
29import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
34import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Junyu Lai38c75032023-12-04 07:52:19 +000035import static android.net.ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090036import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
37import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000038import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang9fe47be2021-06-08 13:11:45 +080039import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070040import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080041import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
42import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
43import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090044import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090045import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090046import static android.net.ConnectivityManager.TYPE_MOBILE;
47import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
49import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
50import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
51import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
52import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
53import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
54import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
55import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070056import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090057import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070058import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090059import static android.net.ConnectivityManager.TYPE_WIFI;
60import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070061import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070062import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080063import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070066import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080067import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040068import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
75import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090077import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090079import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080080import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
81import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080082import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090083import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090084import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080085import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
86import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080087import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
88import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
89import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090090import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090091import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060092import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070093import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080094import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090095import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070096import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
97import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070098import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080099import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100100import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700101import static android.system.OsConstants.IPPROTO_TCP;
102import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900103
Junyu Lai155760b2023-10-05 14:51:00 +0800104import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
105import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
106import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
107import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
108import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Xiao Ma60142372022-07-16 17:30:20 +0900109import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800110import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800111import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
112import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
113import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900114import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900115
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800116import static java.util.Map.Entry;
117
Chalard Jean5b639762020-03-09 21:25:37 +0900118import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000119import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800120import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600121import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800122import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000123import android.app.ActivityManager;
124import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800125import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800126import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700127import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700128import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900129import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800130import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700131import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800132import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800133import android.content.ContentResolver;
134import android.content.Context;
135import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700136import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800137import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900138import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700139import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800140import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900141import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900142import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700143import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800144import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800145import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800146import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900147import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800148import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900149import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800150import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900151import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800152import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700153import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900154import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800155import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800157import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800158import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800159import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900160import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900161import android.net.INetworkMonitor;
162import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900163import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900164import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700165import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800166import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900167import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900168import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900169import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800170import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900171import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900172import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100173import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800174import android.net.NativeNetworkConfig;
175import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800176import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700177import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700178import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900179import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700180import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800181import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700182import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900183import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900184import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000185import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900186import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700187import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900188import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700189import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900190import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700191import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800192import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900193import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700194import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000195import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800196import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900197import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800198import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400199import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700200import android.net.QosCallbackException;
201import android.net.QosFilter;
202import android.net.QosSocketFilter;
203import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700204import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800205import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800206import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900207import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400208import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800209import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800210import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400211import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800212import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900213import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900214import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900215import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900216import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800217import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900218import android.net.networkstack.ModuleNetworkStackClient;
219import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900220import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800221import android.net.resolv.aidl.DnsHealthEventParcel;
222import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
223import android.net.resolv.aidl.Nat64PrefixEventParcel;
224import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900225import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900226import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800227import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800228import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800229import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700230import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000231import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700233import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700234import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800235import android.os.Looper;
236import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700237import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700238import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900239import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800240import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700241import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700242import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800243import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700244import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900245import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900246import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700247import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700248import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400249import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800250import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900251import android.stats.connectivity.MeteredState;
252import android.stats.connectivity.RequestType;
253import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900254import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700255import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700256import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700257import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800258import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900259import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000260import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600261import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900262import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900263import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700264import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700265import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900266import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800267
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800268import androidx.annotation.RequiresApi;
269
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900270import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400271import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400272import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700273import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900274import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900275import com.android.metrics.ConnectionDurationForTransports;
276import com.android.metrics.ConnectionDurationPerTransports;
277import com.android.metrics.ConnectivitySampleMetricsHelper;
278import com.android.metrics.ConnectivityStateSample;
279import com.android.metrics.NetworkCountForTransports;
280import com.android.metrics.NetworkCountPerTransports;
281import com.android.metrics.NetworkDescription;
282import com.android.metrics.NetworkList;
283import com.android.metrics.NetworkRequestCount;
284import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800285import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900286import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800287import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000288import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900289import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800290import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900291import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900292import com.android.net.module.util.DeviceConfigUtils;
Junyu Lai2ff42d22023-12-07 16:57:13 +0800293import com.android.net.module.util.HandlerUtils;
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 VANbee2ee12023-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;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900318import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900319import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000320import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100321import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700322import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900323import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700324import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600325import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900326import com.android.server.connectivity.NetworkNotificationManager;
327import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900328import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900329import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900330import com.android.server.connectivity.NetworkRanker;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000331import com.android.server.connectivity.NetworkRequestStateStatsMetrics;
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 Utsumi93a22182023-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 Utsumi93a22182023-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;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800373
374/**
375 * @hide
376 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800377public class ConnectivityService extends IConnectivityManager.Stub
378 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900379 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800380
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900381 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900382 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900383 private static final String NETWORK_ARG = "networks";
384 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800385 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900386
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900387 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900388 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
389 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800390
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900391 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700392
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100393 /**
394 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
395 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800396 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100397 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
398 * (preferably via runtime resource overlays).
399 */
400 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
401 "http://connectivitycheck.gstatic.com/generate_204";
402
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700403 // TODO: create better separation between radio types and network types
404
Robert Greenwalt2034b912009-08-12 16:08:25 -0700405 // how long to wait before switching back to a radio's default network
406 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
407 // system property that can override the above value
408 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
409 "android.telephony.apn-restore";
410
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900411 // How long to wait before putting up a "This network doesn't have an Internet connection,
412 // connect anyway?" dialog after the user selects a network that doesn't validate.
413 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
414
Chalard Jean5fb43c72022-09-08 19:03:14 +0900415 // How long to wait before considering that a network is bad in the absence of any form
416 // of connectivity (valid, partial, captive portal). If none has been detected after this
417 // delay, the stack considers this network bad, which may affect how it's handled in ranking
418 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900419 // Timeout in case the "actively prefer bad wifi" feature is on
420 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
421 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900422 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900423
junyulai0ac374f2020-12-14 18:41:52 +0800424 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900425 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
426 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800427 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700428
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800429 // Delimiter used when creating the broadcast delivery group for sending
430 // CONNECTIVITY_ACTION broadcast.
431 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
432
he_won.hwang881307a2022-03-15 21:23:52 +0900433 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900434 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900435
Daniel Brightf9e945b2020-06-15 16:10:01 -0700436 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900437 @VisibleForTesting
438 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700439
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900440 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700441 @VisibleForTesting
442 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900443
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900444 @VisibleForTesting
445 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800446 @VisibleForTesting
447 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900448 // True if the cell radio of the device is capable of time-sharing.
449 @VisibleForTesting
450 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900451
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800452 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800453 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800454 private final int mReleasePendingIntentDelayMs;
455
Chalard Jean46bfbf02022-02-02 00:56:25 +0900456 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900457
Motomu Utsumif360aa62023-01-30 17:52:20 +0900458 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700459
Chalard Jean9473c982021-07-29 20:03:04 +0900460 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800461 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700462 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800463 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700464
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900465 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700466
junyulaif2c67e42018-08-07 19:50:45 +0800467 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000468 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
469 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800470 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900471 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800472
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900473 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900474 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000475 private final int mWakeUpMark;
476 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000477 // The Context is created for UserHandle.ALL.
478 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900479 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900480 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700481 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700482 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800483
Chenbo Feng15416292018-11-08 17:36:21 -0800484 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800485 protected IDnsResolver mDnsResolver;
486 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800487 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700488 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900489 private final NetworkStatsManager mStatsManager;
490 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800491 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700492
Benedict Wong493e04b2018-11-09 14:45:34 -0800493 /**
494 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
495 * instances.
496 */
497 @GuardedBy("mTNSLock")
498 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800499 private final CompanionDeviceManagerProxyService mCdmps;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900500 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800501
502 private final Object mTNSLock = new Object();
503
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700504 private String mCurrentTcpBufferSizes;
505
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900506 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000507 new Class[] {
508 ConnectivityService.class,
509 NetworkAgent.class,
510 NetworkAgentInfo.class,
511 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900512
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500513 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400514 // Tear down networks that have no chance (e.g. even if validated) of becoming
515 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500516 // all networks have been rematched against all NetworkRequests.
517 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400518 // Don't reap networks. This should be passed when some networks have not yet been
519 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500520 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900521 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500522
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900523 private enum UnneededFor {
524 LINGER, // Determine whether this network is unneeded and should be lingered.
525 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
526 }
527
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700528 /**
paulhuaa0743d2021-05-26 21:56:03 +0800529 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800530 * should have priority. The order is passed to netd which will use it together
531 * with UID ranges to generate the corresponding IP rule. This serves to
532 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800533 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800534 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000535 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800536 *
paulhu48291862021-07-14 14:53:57 +0800537 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
538 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800539 */
paulhu48291862021-07-14 14:53:57 +0800540 // Used when sending to netd to code for "no order".
541 static final int PREFERENCE_ORDER_NONE = 0;
542 // Order for requests that don't code for a per-app preference. As it is
543 // out of the valid range, the corresponding order should be
544 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800545 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800546 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800547 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800548 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
549 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800550 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800551 static final int PREFERENCE_ORDER_OEM = 10;
552 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800553 // See {@link #setProfileNetworkPreference}.
554 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800555 static final int PREFERENCE_ORDER_PROFILE = 20;
556 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800557 // better scores are connected.
558 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800559 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800560 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900561 // Preference order that signifies the network shouldn't be set as a default network for
562 // the UIDs, only give them access to it. TODO : replace this with a boolean
563 // in NativeUidRangeConfig
564 @VisibleForTesting
565 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
566 // Bound for the lowest valid preference order.
567 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800568
569 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700570 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700571 * from one net to another. Clear happens when we get a new
572 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
573 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700574 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700575 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700576
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700577 /**
578 * used internally to reload global proxy settings
579 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700580 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700581
Robert Greenwalt34848c02011-03-25 13:09:25 -0700582 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400583 * PAC manager has received new port.
584 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800585 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400586
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700587 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900588 * used internally when registering NetworkProviders
589 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700590 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900591 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700592
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700593 /**
594 * used internally when registering NetworkAgents
595 * obj = Messenger
596 */
597 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
598
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700599 /**
600 * used to add a network request
601 * includes a NetworkRequestInfo
602 */
603 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
604
605 /**
606 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900607 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700608 * cancel it.
609 * includes a NetworkRequestInfo
610 */
611 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
612
613 /**
614 * used to add a network listener - no request
615 * includes a NetworkRequestInfo
616 */
617 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
618
619 /**
620 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400621 * arg1 = UID of caller
622 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700623 */
624 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
625
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700626 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900627 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700628 * obj = Messenger
629 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900630 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700631
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700632 /**
633 * used internally to expire a wakelock when transitioning
634 * from one net to another. Expire happens when we fail to find
635 * a new network (typically after 1 minute) -
636 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
637 * a replacement network.
638 */
639 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
640
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700641 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800642 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400643 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800644 */
645 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
646
647 /**
648 * used to remove a pending intent and its associated network request.
649 * arg1 = UID of caller
650 * obj = PendingIntent
651 */
652 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
653
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900654 /**
655 * used to specify whether a network should be used even if unvalidated.
656 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
657 * arg2 = whether to remember this choice in the future (1 or 0)
658 * obj = network
659 */
660 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
661
662 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700663 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900664 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700665 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900666
Paul Jensenc8873fc2015-06-17 14:15:39 -0400667 /**
668 * used to add a network listener with a pending intent
669 * obj = NetworkRequestInfo
670 */
671 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
672
Hugo Benichid6b510a2017-04-06 17:22:18 +0900673 /**
674 * used to specify whether a network should not be penalized when it becomes unvalidated.
675 */
676 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
677
678 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700679 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900680 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700681 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900682
Erik Kline31b4a9e2018-01-11 21:07:29 +0900683 // Handle changes in Private DNS settings.
684 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
685
dalyk1720e542018-03-05 12:42:22 -0500686 // Handle private DNS validation status updates.
687 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
688
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900689 /**
690 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
691 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800692 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
693 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
694 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900695 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900696 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900697
698 /**
699 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
700 * config was resolved.
701 * obj = PrivateDnsConfig
702 * arg2 = netid
703 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900704 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900705
706 /**
707 * Request ConnectivityService display provisioning notification.
708 * arg1 = Whether to make the notification visible.
709 * arg2 = NetID.
710 * obj = Intent to be launched when notification selected by user, null if !arg1.
711 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900712 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900713
714 /**
lucaslin2240ef62019-03-12 13:08:03 +0800715 * Used to specify whether a network should be used even if connectivity is partial.
716 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
717 * false)
718 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
719 * obj = network
720 */
lucaslin444d43a2020-02-20 16:56:59 +0800721 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800722
723 /**
lucasline117e2e2019-10-22 18:27:33 +0800724 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
725 * Both of the arguments are bitmasks, and the value of bits come from
726 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900727 * arg1 = unused
728 * arg2 = netId
729 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800730 */
lucaslin444d43a2020-02-20 16:56:59 +0800731 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800732
733 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900734 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
735 * arg1 = unused
736 * arg2 = netId
737 * obj = captive portal data
738 */
lucaslin444d43a2020-02-20 16:56:59 +0800739 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900740
741 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900742 * Used by setRequireVpnForUids.
743 * arg1 = whether the specified UID ranges are required to use a VPN.
744 * obj = Array of UidRange objects.
745 */
746 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
747
748 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900749 * Used internally when setting the default networks for OemNetworkPreferences.
750 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800751 */
752 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
753
754 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800755 * Used to indicate the system default network becomes active.
756 */
757 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
758
759 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900760 * Used internally when setting a network preference for a user profile.
761 * obj = Pair<ProfileNetworkPreference, Listener>
762 */
763 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
764
765 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000766 * Event to specify that reasons for why an uid is blocked changed.
767 * arg1 = uid
768 * arg2 = blockedReasons
769 */
770 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
771
772 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900773 * Event to register a new network offer
774 * obj = NetworkOffer
775 */
776 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
777
778 /**
779 * Event to unregister an existing network offer
780 * obj = INetworkOfferCallback
781 */
782 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
783
784 /**
paulhu51f77dc2021-06-07 02:34:20 +0000785 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
786 */
787 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
788
789 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800790 * Event to set temporary allow bad wifi within a limited time to override
791 * {@code config_networkAvoidBadWifi}.
792 */
793 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
794
795 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100796 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
797 */
798 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
799
800 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900801 * The initial evaluation period is over for this network.
802 *
803 * If no form of connectivity has been found on this network (valid, partial, captive portal)
804 * then the stack will now consider it to have been determined bad.
805 */
806 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
807
808 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000809 * Used internally when the user does not want the network from captive portal app.
810 * obj = Network
811 */
812 private static final int EVENT_USER_DOES_NOT_WANT = 58;
813
814 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000815 * Event to set VPN as preferred network for specific apps.
816 * obj = VpnNetworkPreferenceInfo
817 */
818 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
819
820 /**
chiachangwange0192a72023-02-06 13:25:01 +0000821 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
822 */
823 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
824
825 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000826 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
827 */
828 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
829
830 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900831 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
832 * should be shown.
833 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900834 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900835
836 /**
837 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
838 * should be hidden.
839 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900840 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900841
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800842 /**
843 * The maximum alive time to allow bad wifi configuration for testing.
844 */
845 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
846
Patrick Rohr2857ac42022-01-21 14:58:16 +0100847 /**
chiachangwange0192a72023-02-06 13:25:01 +0000848 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
849 * testing.
850 */
851 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
852
853 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100854 * The priority of the tc police rate limiter -- smaller value is higher priority.
855 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
856 */
857 private static final short TC_PRIO_POLICE = 1;
858
859 /**
860 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
861 */
862 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700863 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100864
Hugo Benichi47011212017-03-30 10:46:05 +0900865 private static String eventName(int what) {
866 return sMagicDecoderRing.get(what, Integer.toString(what));
867 }
868
paulhua10d8212020-11-10 15:32:56 +0800869 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900870 final DnsResolverServiceManager dsm = context.getSystemService(
871 DnsResolverServiceManager.class);
872 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800873 }
874
Cody Kesting73708bf2019-12-18 10:57:50 -0800875 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900876 @VisibleForTesting
877 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700878 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700879 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700880 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700881 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800882 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
883 @VisibleForTesting
884 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
885
Erik Kline32120082017-12-13 19:40:49 +0900886 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900887 @VisibleForTesting
888 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700889
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400890 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800891 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400892
Chalard Jean46bfbf02022-02-02 00:56:25 +0900893 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800894 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700895
Chalard Jean5d70ba42018-06-07 16:44:04 +0900896 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
897 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800898 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400899
Erik Kline05f2b402015-04-30 12:58:40 +0900900 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700901
Chalard Jean46bfbf02022-02-02 00:56:25 +0900902 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400903
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700904 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900905 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700906
Valentin Iftime9fa35092019-09-24 13:32:13 +0200907 private Set<String> mWolSupportedInterfaces;
908
Roshan Pius08c94fb2020-01-16 12:17:17 -0800909 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800910 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800911 private final AppOpsManager mAppOpsManager;
912
913 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400914
chiachangwang3d60bac2023-01-17 14:38:08 +0000915 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900916 private final QosCallbackTracker mQosCallbackTracker;
917 private final NetworkNotificationManager mNotifier;
918 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900919
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700920 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800921 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700922
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900923 // Sequence number for NetworkProvider IDs.
924 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
925 NetworkProvider.FIRST_PROVIDER_ID);
926
Erik Klineedf878b2015-07-09 18:24:03 +0900927 // NetworkRequest activity String log entries.
928 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
929 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
930
Hugo Benichid159fdd2016-07-11 11:05:12 +0900931 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900932 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900933 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
934
Hugo Benichi47011212017-03-30 10:46:05 +0900935 private static final int MAX_WAKELOCK_LOGS = 20;
936 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900937 private int mTotalWakelockAcquisitions = 0;
938 private int mTotalWakelockReleases = 0;
939 private long mTotalWakelockDurationMs = 0;
940 private long mMaxWakelockDurationMs = 0;
941 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900942
Hugo Benichi208c0102016-07-28 17:53:06 +0900943 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900944
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000945 @Nullable private final NetworkRequestStateStatsMetrics mNetworkRequestStateStatsMetrics;
946
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700947 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900948 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700949
Erik Kline95ecfee2016-10-02 18:02:14 +0900950 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900951 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900952
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900953 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800954 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
955 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800956
Patrick Rohr2857ac42022-01-21 14:58:16 +0100957 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
958 // configured via {@link
959 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
960 // Only the handler thread is allowed to access this field.
961 private long mIngressRateLimit = -1;
962
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900963 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
964 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900965 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900966 @GuardedBy("mSelfCertifiedCapabilityCache")
967 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
968 mSelfCertifiedCapabilityCache = new HashMap<>();
969
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900970 // Flag to enable the feature of closing frozen app sockets.
971 private final boolean mDestroyFrozenSockets;
972
973 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
974 private final boolean mDelayDestroyFrozenSockets;
975
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900976 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
977 private final boolean mAllowSysUiConnectivityReports;
978
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900979 // Uids that ConnectivityService is pending to close sockets of.
980 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
981
Robert Greenwalt802c1102014-06-02 15:32:02 -0700982 /**
983 * Implements support for the legacy "one network per network type" model.
984 *
985 * We used to have a static array of NetworkStateTrackers, one for each
986 * network type, but that doesn't work any more now that we can have,
987 * for example, more that one wifi network. This class stores all the
988 * NetworkAgentInfo objects that support a given type, but the legacy
989 * API will only see the first one.
990 *
991 * It serves two main purposes:
992 *
993 * 1. Provide information about "the network for a given type" (since this
994 * API only supports one).
995 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
996 * the first network for a given type changes, or if the default network
997 * changes.
998 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900999 @VisibleForTesting
1000 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001001
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09001002 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001003 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001004
Robert Greenwalt802c1102014-06-02 15:32:02 -07001005 /**
1006 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1007 * Each list holds references to all NetworkAgentInfos that are used to
1008 * satisfy requests for that network type.
1009 *
1010 * This array is built out at startup such that an unsupported network
1011 * doesn't get an ArrayList instance, making this a tristate:
1012 * unsupported, supported but not active and active.
1013 *
1014 * The actual lists are populated when we scan the network types that
1015 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001016 *
1017 * Threading model:
1018 * - addSupportedType() is only called in the constructor
1019 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1020 * They are therefore not thread-safe with respect to each other.
1021 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1022 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001023 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001024 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001025 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001026 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001027 @NonNull
1028 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001029
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001030 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1031 // an entry have no timer (equivalent to -1). Lazily loaded.
1032 @NonNull
1033 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1034
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001035 LegacyTypeTracker(@NonNull ConnectivityService service) {
1036 mService = service;
1037 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001038 }
1039
Chiachang Wang3bc52762021-11-25 14:17:57 +08001040 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1041 // addressed.
1042 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001043 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1044 final PackageManager pm = ctx.getPackageManager();
1045 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1046 addSupportedType(TYPE_WIFI);
1047 }
1048 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1049 addSupportedType(TYPE_WIFI_P2P);
1050 }
1051 if (tm.isDataCapable()) {
1052 // Telephony does not have granular support for these types: they are either all
1053 // supported, or none is supported
1054 addSupportedType(TYPE_MOBILE);
1055 addSupportedType(TYPE_MOBILE_MMS);
1056 addSupportedType(TYPE_MOBILE_SUPL);
1057 addSupportedType(TYPE_MOBILE_DUN);
1058 addSupportedType(TYPE_MOBILE_HIPRI);
1059 addSupportedType(TYPE_MOBILE_FOTA);
1060 addSupportedType(TYPE_MOBILE_IMS);
1061 addSupportedType(TYPE_MOBILE_CBS);
1062 addSupportedType(TYPE_MOBILE_IA);
1063 addSupportedType(TYPE_MOBILE_EMERGENCY);
1064 }
1065 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1066 addSupportedType(TYPE_BLUETOOTH);
1067 }
1068 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1069 // TYPE_PROXY is only used on Wear
1070 addSupportedType(TYPE_PROXY);
1071 }
1072 // Ethernet is often not specified in the configs, although many devices can use it via
1073 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001074 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001075 addSupportedType(TYPE_ETHERNET);
1076 }
1077
1078 // Always add TYPE_VPN as a supported type
1079 addSupportedType(TYPE_VPN);
1080 }
1081
1082 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001083 if (mTypeLists[type] != null) {
1084 throw new IllegalStateException(
1085 "legacy list for type " + type + "already initialized");
1086 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001087 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001088 }
1089
Robert Greenwalt802c1102014-06-02 15:32:02 -07001090 public boolean isTypeSupported(int type) {
1091 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1092 }
1093
1094 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001095 synchronized (mTypeLists) {
1096 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1097 return mTypeLists[type].get(0);
1098 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001099 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001100 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001101 }
1102
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001103 public int getRestoreTimerForType(int type) {
1104 synchronized (mTypeLists) {
1105 if (mRestoreTimers == null) {
1106 mRestoreTimers = loadRestoreTimers();
1107 }
1108 return mRestoreTimers.getOrDefault(type, -1);
1109 }
1110 }
1111
1112 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1113 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001114 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001115 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1116 for (final String config : configs) {
1117 final String[] splits = TextUtils.split(config, ",");
1118 if (splits.length != 2) {
1119 logwtf("Invalid restore timer token count: " + config);
1120 continue;
1121 }
1122 try {
1123 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1124 } catch (NumberFormatException e) {
1125 logwtf("Invalid restore timer number format: " + config, e);
1126 }
1127 }
1128 return ret;
1129 }
1130
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001131 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001132 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001133 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001134 log("Sending " + state
1135 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001136 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001137 }
1138 }
1139
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001140 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1141 // network type, to preserve previous behaviour.
1142 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1143 if (vpnNai != mService.getLegacyLockdownNai()) return;
1144
1145 if (vpnNai.declaredUnderlyingNetworks == null
1146 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1147 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1148 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1149 return;
1150 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001151 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001152 vpnNai.declaredUnderlyingNetworks[0]);
1153 if (underlyingNai == null) return;
1154
1155 final int type = underlyingNai.networkInfo.getType();
1156 final DetailedState state = DetailedState.CONNECTED;
1157 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1158 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1159 }
1160
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001161 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001162 public void add(int type, NetworkAgentInfo nai) {
1163 if (!isTypeSupported(type)) {
1164 return; // Invalid network type.
1165 }
1166 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1167
1168 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1169 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001170 return;
1171 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001172 synchronized (mTypeLists) {
1173 list.add(nai);
1174 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001175
Chalard Jean5b409c72021-02-04 13:12:59 +09001176 // Send a broadcast if this is the first network of its type or if it's the default.
1177 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001178
1179 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1180 // to preserve previous behaviour.
1181 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001182 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001183 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1184 mService.sendLegacyNetworkBroadcast(nai, state, type);
1185 }
1186
1187 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1188 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001189 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001190 }
1191
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001192 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001193 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001194 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1195 if (list == null || list.isEmpty()) {
1196 return;
1197 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001198 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001199
Hugo Benichi389633f2016-06-21 09:48:07 +09001200 synchronized (mTypeLists) {
1201 if (!list.remove(nai)) {
1202 return;
1203 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001204 }
1205
Lorenzo Colitti49767722015-05-01 00:30:10 +09001206 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001207 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1208 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001209 }
1210
1211 if (!list.isEmpty() && wasFirstNetwork) {
1212 if (DBG) log("Other network available for type " + type +
1213 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001214 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001215 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001216 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001217 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001218 }
1219 }
1220
1221 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001222 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1223 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001224 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001225 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001226 }
1227 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001228
Chalard Jean46bfbf02022-02-02 00:56:25 +09001229 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001230 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001231 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001232 final DetailedState state = nai.networkInfo.getDetailedState();
1233 for (int type = 0; type < mTypeLists.length; type++) {
1234 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001235 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001236 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001237 if (isFirst || contains && isDefault) {
1238 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001239 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001240 }
1241 }
1242 }
1243
Robert Greenwalt94e22142014-07-30 16:31:24 -07001244 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001245 pw.println("mLegacyTypeTracker:");
1246 pw.increaseIndent();
1247 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001248 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001249 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001250 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001251 pw.println();
1252 pw.println("Current state:");
1253 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001254 synchronized (mTypeLists) {
1255 for (int type = 0; type < mTypeLists.length; type++) {
1256 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1257 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001258 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001259 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001260 }
1261 }
1262 pw.decreaseIndent();
1263 pw.decreaseIndent();
1264 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001265 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001266 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001267 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001268
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001269 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001270 /**
1271 * Helper class which parses out priority arguments and dumps sections according to their
1272 * priority. If priority arguments are omitted, function calls the legacy dump command.
1273 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001274 private class LocalPriorityDump {
1275 private static final String PRIORITY_ARG = "--dump-priority";
1276 private static final String PRIORITY_ARG_HIGH = "HIGH";
1277 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001278 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001279
1280 LocalPriorityDump() {}
1281
1282 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001283 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> {
Junyu Laif8dba342023-10-12 17:01:03 +08001284 doDump(fd, pw, new String[]{DIAG_ARG});
1285 doDump(fd, pw, new String[]{SHORT_ARG});
1286 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1287 pw.println("dumpHigh timeout");
1288 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001289 }
1290
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001291 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001292 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> doDump(fd, pw, args),
Junyu Laif8dba342023-10-12 17:01:03 +08001293 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1294 pw.println("dumpNormal timeout");
1295 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001296 }
1297
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001298 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1299 if (args == null) {
1300 dumpNormal(fd, pw, args);
1301 return;
1302 }
1303
1304 String priority = null;
1305 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1306 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1307 argIndex++;
1308 priority = args[argIndex];
1309 }
1310 }
1311
1312 if (PRIORITY_ARG_HIGH.equals(priority)) {
1313 dumpHigh(fd, pw);
1314 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1315 dumpNormal(fd, pw, args);
1316 } else {
1317 // ConnectivityService publishes binder service using publishBinderService() with
1318 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001319 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1320 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001321 // TODO: Integrate into signal dump.
1322 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001323 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001324 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001325 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001326
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001327 /**
1328 * Dependencies of ConnectivityService, for injection in tests.
1329 */
1330 @VisibleForTesting
1331 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001332 public int getCallingUid() {
1333 return Binder.getCallingUid();
1334 }
1335
Chalard Jeandf29a852023-05-29 17:02:43 +09001336 public boolean isAtLeastS() {
1337 return SdkLevel.isAtLeastS();
1338 }
1339
1340 public boolean isAtLeastT() {
1341 return SdkLevel.isAtLeastT();
1342 }
1343
1344 public boolean isAtLeastU() {
1345 return SdkLevel.isAtLeastU();
1346 }
1347
Chalard Jeaneb663892023-10-07 15:17:07 +09001348 public boolean isAtLeastV() {
1349 return SdkLevel.isAtLeastV();
1350 }
1351
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001352 /**
1353 * Get system properties to use in ConnectivityService.
1354 */
1355 public MockableSystemProperties getSystemProperties() {
1356 return new MockableSystemProperties();
1357 }
1358
1359 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001360 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1361 */
1362 public ConnectivityResources getResources(@NonNull Context ctx) {
1363 return new ConnectivityResources(ctx);
1364 }
1365
1366 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001367 * Create a HandlerThread to use in ConnectivityService.
1368 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001369 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1370 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001371 }
1372
1373 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001374 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001375 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001376 public NetworkStackClientBase getNetworkStack() {
1377 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001378 }
1379
1380 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001381 * @see ProxyTracker
1382 */
1383 public ProxyTracker makeProxyTracker(@NonNull Context context,
1384 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001385 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001386 }
1387
1388 /**
1389 * @see NetIdManager
1390 */
1391 public NetIdManager makeNetIdManager() {
1392 return new NetIdManager();
1393 }
1394
1395 /**
1396 * @see NetworkUtils#queryUserAccess(int, int)
1397 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001398 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1399 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001400 }
1401
1402 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001403 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1404 * requires CAP_NET_ADMIN, which the unit tests do not have.
1405 */
1406 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1407 InetSocketAddress remote) {
1408 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1409 }
1410
1411 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001412 * @see MultinetworkPolicyTracker
1413 */
1414 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1415 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1416 return new MultinetworkPolicyTracker(c, h, r);
1417 }
1418
Aaron Huang330a4c02020-10-27 03:36:19 +08001419 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001420 * @see AutomaticOnOffKeepaliveTracker
1421 */
1422 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1423 @NonNull Context c, @NonNull Handler h) {
1424 return new AutomaticOnOffKeepaliveTracker(c, h);
1425 }
1426
1427 /**
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001428 * @see NetworkRequestStateStatsMetrics
1429 */
1430 public NetworkRequestStateStatsMetrics makeNetworkRequestStateStatsMetrics(
1431 Context context) {
1432 // We currently have network requests metric for Watch devices only
1433 if (context.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
1434 return new NetworkRequestStateStatsMetrics();
1435 } else {
1436 return null;
1437 }
1438 }
1439
1440 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001441 * @see BatteryStatsManager
1442 */
1443 public void reportNetworkInterfaceForTransports(Context context, String iface,
1444 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001445 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001446 context.getSystemService(BatteryStatsManager.class);
1447 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1448 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001449
1450 public boolean getCellular464XlatEnabled() {
1451 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1452 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001453
1454 /**
1455 * @see PendingIntent#intentFilterEquals
1456 */
1457 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1458 return a.intentFilterEquals(b);
1459 }
1460
1461 /**
1462 * @see LocationPermissionChecker
1463 */
1464 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1465 return new LocationPermissionChecker(context);
1466 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001467
1468 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001469 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001470 *
1471 * This method returns null in versions before T, where carrier privilege
1472 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001473 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001474 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001475 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1476 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001477 if (isAtLeastT()) {
Chalard Jean96ff9542023-11-02 14:24:47 +09001478 return new CarrierPrivilegeAuthenticator(context, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001479 } else {
1480 return null;
1481 }
1482 }
1483
1484 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001485 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001486 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001487 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001488 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001489 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001490
1491 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001492 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1493 */
1494 public boolean isFeatureNotChickenedOut(Context context, String name) {
1495 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1496 }
1497
1498 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001499 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001500 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001501 * @return BpfNetMaps implementation.
1502 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001503 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1504 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001505 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001506
1507 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001508 * @see ClatCoordinator
1509 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001510 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001511 public ClatCoordinator getClatCoordinator(INetd netd) {
1512 return new ClatCoordinator(
1513 new ClatCoordinator.Dependencies() {
1514 @NonNull
1515 public INetd getNetd() {
1516 return netd;
1517 }
1518 });
1519 }
1520
1521 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001522 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1523 */
1524 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1525 final InterfaceParams params = InterfaceParams.getByName(iface);
1526 if (params == null) {
1527 // the interface might have disappeared.
1528 logw("Failed to get interface params for interface " + iface);
1529 return;
1530 }
1531 try {
1532 // converting rateInBytesPerSecond from long to int is safe here because the
1533 // setting's range is limited to INT_MAX.
1534 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001535 Log.i(TAG,
1536 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001537 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1538 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1539 } catch (IOException e) {
1540 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1541 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1542 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1543 + ") failure: ", e);
1544 }
1545 }
1546
1547 /**
1548 * Wraps {@link TcUtils#tcFilterDelDev}
1549 */
1550 public void disableIngressRateLimit(String iface) {
1551 final InterfaceParams params = InterfaceParams.getByName(iface);
1552 if (params == null) {
1553 // the interface might have disappeared.
1554 logw("Failed to get interface params for interface " + iface);
1555 return;
1556 }
1557 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001558 Log.i(TAG,
1559 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001560 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1561 } catch (IOException e) {
1562 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1563 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1564 }
1565 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001566
1567 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001568 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1569 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001570 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001571 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001572 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001573 }
1574
1575 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001576 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1577 */
1578 // TODO: when available in all active branches:
1579 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1580 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1581 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1582 return BroadcastOptionsShimImpl.newInstance(options);
1583 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001584
1585 /**
1586 * Wrapper method for
1587 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1588 *
1589 * @param changeId The ID of the compatibility change in question.
1590 * @param packageName The package name of the app in question.
1591 * @param user The user that the operation is done for.
1592 * @return {@code true} if the change is enabled for the specified package.
1593 */
1594 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1595 @NonNull final UserHandle user) {
1596 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1597 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001598
1599 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001600 * As above but with a UID.
1601 * @see CompatChanges#isChangeEnabled(long, int)
1602 */
1603 public boolean isChangeEnabled(final long changeId, final int uid) {
1604 return CompatChanges.isChangeEnabled(changeId, uid);
1605 }
1606
1607 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001608 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1609 *
1610 * @param ranges target uid ranges
1611 * @param exemptUids uids to skip close socket
1612 */
1613 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1614 @NonNull final Set<Integer> exemptUids)
1615 throws SocketException, InterruptedIOException, ErrnoException {
1616 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1617 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001618
1619 /**
1620 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1621 *
1622 * @param ownerUids target uids to close sockets
1623 */
1624 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1625 throws SocketException, InterruptedIOException, ErrnoException {
1626 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1627 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001628
1629 /**
1630 * Schedule the evaluation timeout.
1631 *
1632 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1633 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1634 * of these events happen, this time will run out, after which the network is considered
1635 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1636 * on this network and considers it won't provide connectivity. In particular, that means
1637 * it's when the system prefers it to cell if it's wifi and configuration says it should
1638 * prefer bad wifi to cell.
1639 */
1640 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1641 @NonNull final Network network, final long delayMs) {
1642 handler.sendMessageDelayed(
1643 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1644 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001645 }
1646
junyulaie7c7d2a2021-01-26 15:29:15 +08001647 public ConnectivityService(Context context) {
1648 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001649 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1650 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001651 }
1652
1653 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001654 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1655 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001656 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001657
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001658 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001659 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001660 mSystemProperties = mDeps.getSystemProperties();
1661 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001662 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001663 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001664 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1665 // Pass limit - 1 to maintain backward compatibility.
1666 // TODO: Remove the workaround.
1667 mNetworkRequestCounter =
1668 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1669 mSystemNetworkRequestCounter =
1670 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001671
Hugo Benichi208c0102016-07-28 17:53:06 +09001672 mMetricsLog = logger;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001673 mNetworkRequestStateStatsMetrics = mDeps.makeNetworkRequestStateStatsMetrics(mContext);
James Mattis45d81842021-01-10 14:24:24 -08001674 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1675 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001676 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001677 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001678 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001679 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1680 mDefaultNetworkRequests.add(mDefaultRequest);
1681 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001682
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001683 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001684 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001685
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001686 // The default WiFi request is a background request so that apps using WiFi are
1687 // migrated to a better network (typically ethernet) when one comes up, instead
1688 // of staying on WiFi forever.
1689 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1690 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1691
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001692 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1693 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1694 NetworkRequest.Type.BACKGROUND_REQUEST);
1695
Chalard Jean0702f982021-09-16 21:50:07 +09001696 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1697 // TODO: Consider making the timer customizable.
1698 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1699 mCellularRadioTimesharingCapable =
1700 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1701
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001702 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1703 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1704
1705 if (SdkLevel.isAtLeastU()) {
1706 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1707 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1708 final int defaultUMarkMask = 0x80000000; // u32
1709
1710 if ((mark == 0) || (mask == 0)) {
1711 // simply treat unset/disabled as the default U value
1712 mark = defaultUMarkMask;
1713 mask = defaultUMarkMask;
1714 }
1715 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1716 // invalid device overlay settings
1717 throw new IllegalArgumentException(
1718 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1719 }
1720 }
1721
1722 mWakeUpMark = mark;
1723 mWakeUpMask = mask;
1724
Paul Hu51f816b2022-08-11 14:43:47 +00001725 mNetd = netd;
1726 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Chalard Jean96ff9542023-11-02 14:24:47 +09001727 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Paul Hu51f816b2022-08-11 14:43:47 +00001728 mPermissionMonitor =
1729 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001730 mHandlerThread.start();
1731 mHandler = new InternalHandler(mHandlerThread.getLooper());
1732 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001733 mConnectivityDiagnosticsHandler =
1734 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001735
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001736 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001737 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001738
junyulaie7c7d2a2021-01-26 15:29:15 +08001739 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001740 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001741 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001742 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001743
Wink Saville32506bc2013-06-29 21:10:57 -07001744 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001745 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001746 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001747 mCarrierPrivilegeAuthenticator =
1748 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001749
Sudheer Shanka9967d462021-03-18 19:09:25 +00001750 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001751 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1752 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001753 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001754
1755 final PowerManager powerManager = (PowerManager) context.getSystemService(
1756 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001757 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001758 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001759
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001760 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1761 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001762 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001763 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001764 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001765 mProtectedNetworks.add(p);
1766 } else {
1767 if (DBG) loge("Ignoring protectedNetwork " + p);
1768 }
1769 }
1770
soma, kawata29444ae2019-05-23 09:30:40 +09001771 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1772
James Mattis02220e22021-03-13 19:27:21 -08001773 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001774 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001775 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001776 final IntentFilter userIntentFilter = new IntentFilter();
1777 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1778 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1779 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1780 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001781
James Mattis02220e22021-03-13 19:27:21 -08001782 // Listen to package add/removes for netd
1783 final IntentFilter packageIntentFilter = new IntentFilter();
1784 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1785 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1786 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1787 packageIntentFilter.addDataScheme("package");
1788 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001789 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001790
Junyu Lai38c75032023-12-04 07:52:19 +00001791 // This is needed for pre-V devices to propagate the data saver status
1792 // to the BPF map. This isn't supported before Android T because BPF maps are
1793 // unsupported, and it's also unnecessary on Android V and later versions,
1794 // as the platform code handles data saver bit updates. Additionally, checking
1795 // the initial data saver status here is superfluous because the intent won't
1796 // be sent until the system is ready.
1797 if (mDeps.isAtLeastT() && !mDeps.isAtLeastV()) {
1798 final IntentFilter dataSaverIntentFilter =
1799 new IntentFilter(ACTION_RESTRICT_BACKGROUND_CHANGED);
1800 mUserAllContext.registerReceiver(mDataSaverReceiver, dataSaverIntentFilter,
1801 null /* broadcastPermission */, mHandler);
1802 }
1803
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09001804 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
1805 // But reading the trunk stable flags from mainline modules is not supported yet.
1806 // So enabling this feature on V+ release.
1807 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
1808 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
1809 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001810
Chalard Jean46bfbf02022-02-02 00:56:25 +09001811 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001812 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001813 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001814 } catch (RemoteException | ServiceSpecificException e) {
1815 loge("Error registering event listener :" + e);
1816 }
1817
Erik Kline05f2b402015-04-30 12:58:40 +09001818 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1819 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001820
chiachangwang7c17c282023-02-02 05:58:59 +00001821 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001822 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001823 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001824
1825 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001826 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001827 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1828 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001829 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001830 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1831 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001832
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001833 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001834 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001835 mNetworkRanker =
1836 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1837
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001838 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001839
Chiachang Wangc1215d32020-10-20 15:38:58 +08001840 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001841 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001842
Chalard Jean28018572020-12-21 18:36:52 +09001843 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1844 // request that doesn't allow fallback to the default network. It should never be visible
1845 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1846 // arguments like the handler or the DnsResolver.
1847 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001848 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001849 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001850 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001851 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001852 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001853 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1854 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001855
1856 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001857 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1858 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1859 // Even if it could, running on S would at least require mocking out the BPF map,
1860 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1861 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001862 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001863 mDscpPolicyTracker = new DscpPolicyTracker();
1864 }
Tyler Wear72388212021-09-09 14:49:02 -07001865 } catch (ErrnoException e) {
1866 loge("Unable to create DscpPolicyTracker");
1867 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001868
1869 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1870 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001871
Chalard Jeandf29a852023-05-29 17:02:43 +09001872 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001873 mCdmps = new CompanionDeviceManagerProxyService(context);
1874 } else {
1875 mCdmps = null;
1876 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001877
Chalard Jean2fb66f12023-08-25 12:50:37 +09001878 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
1879
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001880 mDestroyFrozenSockets = mDeps.isAtLeastU()
1881 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1882 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1883 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001884 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1885 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001886 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001887 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1888 new UidFrozenStateChangedCallback() {
1889 @Override
1890 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1891 if (uids.length != frozenStates.length) {
1892 Log.wtf(TAG, "uids has length " + uids.length
1893 + " but frozenStates has length " + frozenStates.length);
1894 return;
1895 }
1896
1897 final UidFrozenStateChangedArgs args =
1898 new UidFrozenStateChangedArgs(uids, frozenStates);
1899
1900 mHandler.sendMessage(
1901 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1902 }
1903 };
1904
1905 final ActivityManager activityManager =
1906 mContext.getSystemService(ActivityManager.class);
1907 activityManager.registerUidFrozenStateChangedCallback(
1908 (Runnable r) -> r.run(), frozenStateChangedCallback);
1909 }
Yuyang Huang41557552023-11-28 12:47:22 +09001910
1911 if (mDeps.isFeatureNotChickenedOut(mContext, LOG_BPF_RC)) {
1912 mHandler.post(BpfLoaderRcUtils::checkBpfLoaderRc);
1913 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001914 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001915
Xiao Ma0a171c02022-01-23 16:14:51 +00001916 /**
1917 * Check whether or not the device supports Ethernet transport.
1918 */
1919 public static boolean deviceSupportsEthernet(final Context context) {
1920 final PackageManager pm = context.getPackageManager();
1921 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1922 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1923 }
1924
Chalard Jean46adcf32018-04-18 20:18:38 +09001925 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001926 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1927 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001928 }
1929
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001930 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1931 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001932 final NetworkCapabilities netCap = new NetworkCapabilities();
1933 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001934 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001935 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001936 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001937 return netCap;
1938 }
1939
James Mattis45d81842021-01-10 14:24:24 -08001940 private NetworkRequest createDefaultRequest() {
1941 return createDefaultInternetRequestForTransport(
1942 TYPE_NONE, NetworkRequest.Type.REQUEST);
1943 }
1944
lucaslin3ba7cc22022-12-19 02:35:33 +00001945 private NetworkRequest createVpnRequest() {
1946 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1947 .withoutDefaultCapabilities()
1948 .addTransportType(TRANSPORT_VPN)
1949 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1950 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1951 .build();
1952 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1953 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1954 }
1955
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001956 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001957 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001958 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001959 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001960 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001961 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001962 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001963 netCap.addTransportType(transportType);
1964 }
James Mattis45d81842021-01-10 14:24:24 -08001965 return createNetworkRequest(type, netCap);
1966 }
1967
1968 private NetworkRequest createNetworkRequest(
1969 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001970 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001971 }
1972
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001973 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1974 NetworkRequest.Type type) {
1975 final NetworkCapabilities netCap = new NetworkCapabilities();
1976 netCap.clearAll();
1977 netCap.addCapability(capability);
1978 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1979 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1980 }
1981
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001982 // Used only for testing.
1983 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001984 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001985 // changing ContentResolver to make registerContentObserver non-final).
1986 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1987 // by subclassing SettingsObserver.
1988 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001989 void updateAlwaysOnNetworks() {
1990 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001991 }
1992
Erik Kline9a62f012018-03-21 07:18:33 -07001993 // See FakeSettingsProvider comment above.
1994 @VisibleForTesting
1995 void updatePrivateDnsSettings() {
1996 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1997 }
1998
paulhu51f77dc2021-06-07 02:34:20 +00001999 @VisibleForTesting
2000 void updateMobileDataPreferredUids() {
2001 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
2002 }
2003
Patrick Rohr2857ac42022-01-21 14:58:16 +01002004 @VisibleForTesting
2005 void updateIngressRateLimit() {
2006 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
2007 }
2008
Aaron Huang40b52442021-06-08 04:34:24 +08002009 @VisibleForTesting
2010 void simulateUpdateProxyInfo(@Nullable final Network network,
2011 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08002012 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08002013 new Pair<>(network, proxyInfo)).sendToTarget();
2014 }
2015
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002016 private void handleAlwaysOnNetworkRequest(
2017 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002018 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002019 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002020 handleAlwaysOnNetworkRequest(networkRequest, enable);
2021 }
2022
2023 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002024 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002025 if (enable == isEnabled) {
2026 return; // Nothing to do.
2027 }
2028
2029 if (enable) {
2030 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002031 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002032 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002033 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002034 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002035 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2036 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002037 }
2038 }
2039
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002040 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002041 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2042 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2043 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2044 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002045 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2046 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002047 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002048 }
2049
paulhu51f77dc2021-06-07 02:34:20 +00002050 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002051 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002052 private void registerSettingsCallbacks() {
2053 // Watch for global HTTP proxy changes.
2054 mSettingsObserver.observe(
2055 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2056 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2057
Chalard Jean46bfbf02022-02-02 00:56:25 +09002058 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002059 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002060 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002061 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2062
Chalard Jean46bfbf02022-02-02 00:56:25 +09002063 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002064 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002065 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002066 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002067
2068 // Watch for mobile data preferred uids changes.
2069 mSettingsObserver.observe(
2070 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2071 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002072
2073 // Watch for ingress rate limit changes.
2074 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002075 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002076 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2077 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002078 }
2079
Erik Kline31b4a9e2018-01-11 21:07:29 +09002080 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002081 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2082 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002083 }
2084 }
2085
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002086 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002087 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2088 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002089 return mNextNetworkRequestId++;
2090 }
2091
junyulai74f9a8b2018-06-13 15:00:37 +08002092 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002093 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002094 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002095 if (network == null) {
2096 return null;
2097 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002098 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002099 }
2100
2101 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002102 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002103 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002104 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002105 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002106
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002107 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002108 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002109 private NetworkAgentInfo getVpnForUid(int uid) {
2110 synchronized (mNetworkForNetId) {
2111 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2112 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002113 if (nai.isVPN() && nai.everConnected()
2114 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002115 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002116 }
2117 }
2118 }
2119 return null;
2120 }
2121
Chalard Jean46bfbf02022-02-02 00:56:25 +09002122 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002123 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002124 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002125 final NetworkAgentInfo nai = getVpnForUid(uid);
2126 if (nai != null) return nai.declaredUnderlyingNetworks;
2127 return null;
2128 }
2129
Lorenzo Colittia7574052021-01-19 01:33:05 +09002130 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002131 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002132
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002133 final Network[] networks = getVpnUnderlyingNetworks(uid);
2134 if (networks != null) {
2135 // getUnderlyingNetworks() returns:
2136 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2137 // empty array => the VPN explicitly said "no default network".
2138 // non-empty array => the VPN specified one or more default networks; we use the
2139 // first one.
2140 if (networks.length > 0) {
2141 nai = getNetworkAgentInfoForNetwork(networks[0]);
2142 } else {
2143 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002144 }
2145 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002146 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002147 }
2148
2149 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002150 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002151 */
paulhu7aeba372020-12-30 00:42:19 +08002152 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2153 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002154 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002155 if (ignoreBlocked) {
2156 return false;
2157 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002158 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002159 final long ident = Binder.clearCallingIdentity();
2160 try {
2161 final boolean metered = nc == null ? true : nc.isMetered();
2162 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2163 } finally {
2164 Binder.restoreCallingIdentity(ident);
2165 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002166 }
2167
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002168 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002169 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2170 return;
2171 }
Hugo Benichi47011212017-03-30 10:46:05 +09002172 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002173 synchronized (mBlockedAppUids) {
2174 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002175 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002176 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002177 blocked = false;
2178 } else {
2179 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002180 }
2181 }
Hugo Benichi47011212017-03-30 10:46:05 +09002182 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2183 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2184 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002185 }
2186
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002187 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002188 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2189 return;
2190 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002191 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002192 final int requestId = nri.getActiveRequest() != null
2193 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002194 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002195 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002196 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002197 }
2198
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002199 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002200 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002201 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002202 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002203 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002204 @NonNull
2205 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2206 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002207 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2208 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2209 // but only exists if an app asks about them or requests them. Ensure the requesting app
2210 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002211 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002212 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2213 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2214 null /* extraInfo */);
2215 }
2216 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002217 return filtered;
2218 }
2219
2220 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2221 boolean ignoreBlocked) {
2222 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2223 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002224 }
2225
2226 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002227 * Return NetworkInfo for the active (i.e., connected) network interface.
2228 * It is assumed that at most one network is active at a time. If more
2229 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002230 * @return the info for the active network, or {@code null} if none is
2231 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002232 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002233 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002234 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002235 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002236 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002237 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002238 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2239 if (nai == null) return null;
2240 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2241 maybeLogBlockedNetworkInfo(networkInfo, uid);
2242 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002243 }
2244
Paul Jensen1f567382015-02-13 14:18:39 -05002245 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002246 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002247 public Network getActiveNetwork() {
2248 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002249 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002250 }
2251
2252 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002253 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002254 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002255 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002256 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002257 }
2258
Chalard Jean46bfbf02022-02-02 00:56:25 +09002259 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002260 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002261 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2262 if (vpnNai != null) {
2263 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2264 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2265 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002266 }
Paul Jensen1f567382015-02-13 14:18:39 -05002267 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002268
James Mattis2516da32021-01-31 17:06:19 -08002269 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002270 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2271 ignoreBlocked)) {
2272 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002273 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002274 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002275 }
2276
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002277 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002278 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002279 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002280 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002281 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2282 if (nai == null) return null;
2283 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002284 }
2285
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002286 /** Returns a NetworkInfo object for a network that doesn't exist. */
2287 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2288 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2289 getNetworkTypeName(networkType), "" /* subtypeName */);
2290 info.setIsAvailable(true);
2291 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2292 // background data is restricted.
2293 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2294 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2295 ? DetailedState.BLOCKED
2296 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002297 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2298 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002299 return info;
2300 }
2301
Lorenzo Colittia7574052021-01-19 01:33:05 +09002302 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002303 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2304 return null;
2305 }
2306 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002307 if (nai == null) {
2308 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002309 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002310 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2311 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002312 }
2313
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002314 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002315 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002316 public NetworkInfo getNetworkInfo(int networkType) {
2317 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002318 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002319 if (getVpnUnderlyingNetworks(uid) != null) {
2320 // A VPN is active, so we may need to return one of its underlying networks. This
2321 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002322 // getNetworkAgentInfoForUid.
2323 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2324 if (nai == null) return null;
2325 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2326 if (networkInfo.getType() == networkType) {
2327 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002328 }
2329 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002330 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002331 }
2332
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002333 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002334 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002335 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002336 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002337 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002338 if (nai == null) return null;
2339 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002340 }
2341
2342 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002343 public NetworkInfo[] getAllNetworkInfo() {
2344 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002345 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002346 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2347 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002348 NetworkInfo info = getNetworkInfo(networkType);
2349 if (info != null) {
2350 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002351 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002352 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002353 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002354 }
2355
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002356 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002357 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002358 public Network getNetworkForType(int networkType) {
2359 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002360 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2361 return null;
2362 }
2363 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2364 if (nai == null) {
2365 return null;
2366 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002367 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002368 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2369 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002370 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002371 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002372 }
2373
2374 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002375 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002376 public Network[] getAllNetworks() {
2377 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002378 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002379 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002380 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002381 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002382 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002383 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002384 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002385 }
2386
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002387 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002388 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002389 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002390 // The basic principle is: if an app's traffic could possibly go over a
2391 // network, without the app doing anything multinetwork-specific,
2392 // (hence, by "default"), then include that network's capabilities in
2393 // the array.
2394 //
2395 // In the normal case, app traffic only goes over the system's default
2396 // network connection, so that's the only network returned.
2397 //
2398 // With a VPN in force, some app traffic may go into the VPN, and thus
2399 // over whatever underlying networks the VPN specifies, while other app
2400 // traffic may go over the system default network (e.g.: a split-tunnel
2401 // VPN, or an app disallowed by the VPN), so the set of networks
2402 // returned includes the VPN's underlying networks and the system
2403 // default.
2404 enforceAccessPermission();
2405
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002406 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002407
James Mattis2516da32021-01-31 17:06:19 -08002408 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2409 if (!nri.isBeingSatisfied()) {
2410 continue;
2411 }
2412 final NetworkAgentInfo nai = nri.getSatisfier();
2413 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2414 if (null != nc
2415 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2416 && !result.containsKey(nai.network)) {
2417 result.put(
2418 nai.network,
2419 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002420 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002421 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2422 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002423 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002424 }
2425
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002426 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002427 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002428 if (null != networks) {
2429 for (final Network network : networks) {
2430 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2431 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002432 result.put(
2433 network,
2434 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002435 nc,
2436 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002437 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002438 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002439 }
2440 }
2441 }
2442
2443 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2444 out = result.values().toArray(out);
2445 return out;
2446 }
2447
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002448 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2449 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2450 // can call sampleConnectivityState and make the checks on it.
2451 @NonNull
2452 private StatsEvent sampleConnectivityStateToStatsEvent() {
2453 final ConnectivityStateSample sample = sampleConnectivityState();
2454 return ConnectivityStatsLog.buildStatsEvent(
2455 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2456 sample.getNetworkCountPerTransports().toByteArray(),
2457 sample.getConnectionDurationPerTransports().toByteArray(),
2458 sample.getNetworkRequestCount().toByteArray(),
2459 sample.getNetworks().toByteArray());
2460 }
2461
2462 /**
2463 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2464 *
2465 * This is used for metrics. These snapshots will be sampled and constitute a base for
2466 * statistics about connectivity state of devices.
2467 */
2468 @VisibleForTesting
2469 @NonNull
2470 public ConnectivityStateSample sampleConnectivityState() {
2471 ensureRunningOnConnectivityServiceThread();
2472 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2473 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2474 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2475 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2476 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2477 return builder.build();
2478 }
2479
2480 private static NetworkCountPerTransports sampleNetworkCount(
2481 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2482 final SparseIntArray countPerTransports = new SparseIntArray();
2483 for (final NetworkAgentInfo nai : nais) {
2484 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2485 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2486 }
2487 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2488 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2489 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2490 c.setTransportTypes(countPerTransports.keyAt(i));
2491 c.setNetworkCount(countPerTransports.valueAt(i));
2492 builder.addNetworkCountForTransports(c);
2493 }
2494 return builder.build();
2495 }
2496
2497 private static ConnectionDurationPerTransports sampleConnectionDuration(
2498 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2499 final ConnectionDurationPerTransports.Builder builder =
2500 ConnectionDurationPerTransports.newBuilder();
2501 for (final NetworkAgentInfo nai : nais) {
2502 final ConnectionDurationForTransports.Builder c =
2503 ConnectionDurationForTransports.newBuilder();
2504 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2505 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2506 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2507 // Add millisPerSecond/2 to round up or down to the nearest value
2508 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2509 builder.addConnectionDurationForTransports(c);
2510 }
2511 return builder.build();
2512 }
2513
2514 private static NetworkRequestCount sampleNetworkRequestCount(
2515 @NonNull final Collection<NetworkRequestInfo> nris) {
2516 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2517 final SparseIntArray countPerType = new SparseIntArray();
2518 for (final NetworkRequestInfo nri : nris) {
2519 final int type;
2520 if (Process.SYSTEM_UID == nri.mAsUid) {
2521 // The request is filed "as" the system, so it's the system on its own behalf.
2522 type = RequestType.RT_SYSTEM.getNumber();
2523 } else if (Process.SYSTEM_UID == nri.mUid) {
2524 // The request is filed by the system as some other app, so it's the system on
2525 // behalf of an app.
2526 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2527 } else {
2528 // Not the system, so it's an app requesting on its own behalf.
2529 type = RequestType.RT_APP.getNumber();
2530 }
2531 countPerType.put(type, countPerType.get(type, 0));
2532 }
2533 for (int i = countPerType.size() - 1; i >= 0; --i) {
2534 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2535 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2536 r.setRequestCount(countPerType.valueAt(i));
2537 builder.addRequestCountForType(r);
2538 }
2539 return builder.build();
2540 }
2541
2542 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2543 final NetworkList.Builder builder = NetworkList.newBuilder();
2544 for (final NetworkAgentInfo nai : nais) {
2545 final NetworkCapabilities nc = nai.networkCapabilities;
2546 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2547 d.setTransportTypes((int) nc.getTransportTypesInternal());
2548 final MeteredState meteredState;
2549 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2550 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2551 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2552 meteredState = MeteredState.METERED_NO;
2553 } else {
2554 meteredState = MeteredState.METERED_YES;
2555 }
2556 d.setMeteredState(meteredState);
2557 final ValidatedState validatedState;
2558 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2559 validatedState = ValidatedState.VS_PORTAL;
2560 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2561 validatedState = ValidatedState.VS_PARTIAL;
2562 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2563 validatedState = ValidatedState.VS_VALID;
2564 } else {
2565 validatedState = ValidatedState.VS_INVALID;
2566 }
2567 d.setValidatedState(validatedState);
2568 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2569 d.setCapabilities(nc.getCapabilitiesInternal());
2570 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2571 builder.addNetworkDescription(d);
2572 }
2573 return builder.build();
2574 }
2575
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002576 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002577 public boolean isNetworkSupported(int networkType) {
2578 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002579 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002580 }
2581
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002582 /**
2583 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002584 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002585 * @return the ip properties for the active network, or {@code null} if
2586 * none is active
2587 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002588 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002589 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002590 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002591 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002592 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2593 if (nai == null) return null;
2594 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002595 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002596 }
2597
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002598 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002599 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002600 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002601 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002602 final LinkProperties lp = getLinkProperties(nai);
2603 if (lp == null) return null;
2604 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002605 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002606 }
2607
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002608 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002609 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002610 public LinkProperties getLinkProperties(Network network) {
2611 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002612 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2613 if (lp == null) return null;
2614 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002615 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002616 }
2617
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002618 @Nullable
2619 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002620 if (nai == null) {
2621 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002622 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002623 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002624 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002625 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002626 }
2627
lucaslinc582d502022-01-27 09:07:00 +08002628 @Override
2629 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002630 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002631 @NonNull String packageName, @Nullable String callingAttributionTag) {
2632 Objects.requireNonNull(packageName);
2633 Objects.requireNonNull(lp);
2634 enforceNetworkStackOrSettingsPermission();
2635 if (!checkAccessPermission(-1 /* pid */, uid)) {
2636 return null;
2637 }
2638 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2639 }
2640
Qingxi Lib2748102020-01-08 12:51:49 -08002641 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2642 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2643 }
2644
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002645 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002646 if (nai == null) return null;
2647 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002648 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002649 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002650 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002651 }
2652
2653 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002654 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2655 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002656 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002657 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002658 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002659 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002660 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002661 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002662 }
2663
lucaslinc582d502022-01-27 09:07:00 +08002664 @Override
lucaslind2b06132022-03-02 10:56:57 +08002665 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2666 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2667 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002668 Objects.requireNonNull(nc);
2669 Objects.requireNonNull(packageName);
2670 enforceNetworkStackOrSettingsPermission();
2671 if (!checkAccessPermission(-1 /* pid */, uid)) {
2672 return null;
2673 }
2674 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2675 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2676 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2677 callingAttributionTag);
2678 }
2679
lucaslin69e1aa92022-03-22 18:15:09 +08002680 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2681 if (nc.getUnderlyingNetworks() != null
2682 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2683 nc.setUnderlyingNetworks(null);
2684 }
2685 }
2686
Chalard Jean53017782022-11-24 17:13:44 +09002687 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
2688 return Process.SYSTEM_UID == uid
Chalard Jean53017782022-11-24 17:13:44 +09002689 || checkAnyPermissionOf(mContext, pid, uid,
2690 android.Manifest.permission.NETWORK_FACTORY);
2691 }
2692
Qingxi Libb8da982020-01-17 17:54:27 -08002693 @VisibleForTesting
2694 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002695 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002696 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2697 // this would be expensive (one more permission check every time any NC callback is
2698 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2699 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2700 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002701 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002702 if (!checkSettingsPermission(callerPid, callerUid)) {
2703 newNc.setUids(null);
2704 newNc.setSSID(null);
2705 }
Etan Cohen107ae952018-12-30 17:59:59 -08002706 if (newNc.getNetworkSpecifier() != null) {
2707 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2708 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002709 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2710 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002711 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2712 newNc.setAdministratorUids(new int[0]);
2713 }
Chalard Jean53017782022-11-24 17:13:44 +09002714 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09002715 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002716 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002717 }
lucaslin69e1aa92022-03-22 18:15:09 +08002718 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002719
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002720 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002721 }
2722
Roshan Pius98f59ec2021-02-23 08:47:39 -08002723 /**
2724 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002725 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002726 * NetworkCapabilities.
2727 * Note: This wrapper does not support any sort of invalidation and thus must not be
2728 * persistent or long-lived. It may only be used for the time necessary to
2729 * compute the redactions required by one particular NetworkCallback or
2730 * synchronous call.
2731 */
2732 private class RedactionPermissionChecker {
2733 private final int mCallingPid;
2734 private final int mCallingUid;
2735 @NonNull private final String mCallingPackageName;
2736 @Nullable private final String mCallingAttributionTag;
2737
2738 private Boolean mHasLocationPermission = null;
2739 private Boolean mHasLocalMacAddressPermission = null;
2740 private Boolean mHasSettingsPermission = null;
2741
2742 RedactionPermissionChecker(int callingPid, int callingUid,
2743 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2744 mCallingPid = callingPid;
2745 mCallingUid = callingUid;
2746 mCallingPackageName = callingPackageName;
2747 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002748 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002749
2750 private boolean hasLocationPermissionInternal() {
2751 final long token = Binder.clearCallingIdentity();
2752 try {
2753 return mLocationPermissionChecker.checkLocationPermission(
2754 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2755 null /* message */);
2756 } finally {
2757 Binder.restoreCallingIdentity(token);
2758 }
2759 }
2760
2761 /**
2762 * Returns whether the app holds location permission or not (might return cached result
2763 * if the permission was already checked before).
2764 */
2765 public boolean hasLocationPermission() {
2766 if (mHasLocationPermission == null) {
2767 // If there is no cached result, perform the check now.
2768 mHasLocationPermission = hasLocationPermissionInternal();
2769 }
2770 return mHasLocationPermission;
2771 }
2772
2773 /**
2774 * Returns whether the app holds local mac address permission or not (might return cached
2775 * result if the permission was already checked before).
2776 */
2777 public boolean hasLocalMacAddressPermission() {
2778 if (mHasLocalMacAddressPermission == null) {
2779 // If there is no cached result, perform the check now.
2780 mHasLocalMacAddressPermission =
2781 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2782 }
2783 return mHasLocalMacAddressPermission;
2784 }
2785
2786 /**
2787 * Returns whether the app holds settings permission or not (might return cached
2788 * result if the permission was already checked before).
2789 */
2790 public boolean hasSettingsPermission() {
2791 if (mHasSettingsPermission == null) {
2792 // If there is no cached result, perform the check now.
2793 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2794 }
2795 return mHasSettingsPermission;
2796 }
2797 }
2798
2799 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2800 @NetworkCapabilities.NetCapability long redaction) {
2801 return (redactions & redaction) != 0;
2802 }
2803
2804 /**
2805 * Use the provided |applicableRedactions| to check the receiving app's
2806 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2807 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2808 * before being sent to the corresponding app.
2809 */
2810 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2811 @NetworkCapabilities.RedactionType long applicableRedactions,
2812 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2813 boolean includeLocationSensitiveInfo) {
2814 long redactions = applicableRedactions;
2815 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2816 if (includeLocationSensitiveInfo
2817 && redactionPermissionChecker.hasLocationPermission()) {
2818 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2819 }
2820 }
2821 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2822 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2823 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2824 }
2825 }
2826 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2827 if (redactionPermissionChecker.hasSettingsPermission()) {
2828 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2829 }
2830 }
2831 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002832 }
2833
Qingxi Lib2748102020-01-08 12:51:49 -08002834 @VisibleForTesting
2835 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002836 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002837 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002838 int callingPid, int callingUid, @NonNull String callingPkgName,
2839 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002840 if (nc == null) {
2841 return null;
2842 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002843 // Avoid doing location permission check if the transport info has no location sensitive
2844 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002845 final RedactionPermissionChecker redactionPermissionChecker =
2846 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2847 callingAttributionTag);
2848 final long redactions = retrieveRequiredRedactions(
2849 nc.getApplicableRedactions(), redactionPermissionChecker,
2850 includeLocationSensitiveInfo);
2851 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002852 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002853 // TODO : calling UID is redacted because apps should generally not know what UID is
2854 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002855 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002856 newNc.setOwnerUid(INVALID_UID);
2857 return newNc;
2858 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002859 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2860 if (nc.hasTransport(TRANSPORT_VPN)) {
2861 // Owner UIDs already checked above. No need to re-check.
2862 return newNc;
2863 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002864 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2865 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002866 // compatibility for older apps.
2867 if (!includeLocationSensitiveInfo
2868 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002869 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002870 newNc.setOwnerUid(INVALID_UID);
2871 return newNc;
2872 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002873 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002874 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002875 newNc.setOwnerUid(INVALID_UID);
2876 }
Qingxi Lib2748102020-01-08 12:51:49 -08002877 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002878 }
2879
lucaslinc582d502022-01-27 09:07:00 +08002880 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002881 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2882 LinkProperties lp, int callerPid, int callerUid) {
2883 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002884 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2885 // this would be expensive (one more permission check every time any LP callback is
2886 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2887 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2888 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002889
2890 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2891 final boolean needsSanitization =
2892 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2893 if (!needsSanitization) {
2894 return new LinkProperties(lp);
2895 }
2896
2897 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002898 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002899 }
2900
2901 final LinkProperties newLp = new LinkProperties(lp);
2902 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2903 // object gets parceled.
2904 newLp.setCaptivePortalApiUrl(null);
2905 newLp.setCaptivePortalData(null);
2906 return newLp;
2907 }
2908
Roshan Pius08c94fb2020-01-16 12:17:17 -08002909 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2910 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002911 // There is no need to track the effective UID of the request here. If the caller
2912 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002913 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002914 // Unprivileged apps can only pass in null or their own UID.
2915 if (nc.getUids() == null) {
2916 // If the caller passes in null, the callback will also match networks that do not
2917 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2918 // In this case, redact everything in the request immediately. This ensures that the
2919 // app is not able to get any redacted information by filing an unredacted request
2920 // and observing whether the request matches something.
2921 if (nc.getNetworkSpecifier() != null) {
2922 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2923 }
2924 } else {
2925 nc.setSingleUid(callerUid);
2926 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002927 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002928 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002929 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002930
2931 // Clear owner UID; this can never come from an app.
2932 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002933 }
2934
Chalard Jean38354d12018-03-20 19:13:57 +09002935 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002936 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002937 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2938 }
2939 }
2940
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002941 @Override
2942 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2943 enforceAccessPermission();
2944 final int callerUid = Binder.getCallingUid();
2945 final long token = Binder.clearCallingIdentity();
2946 try {
2947 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2948 } finally {
2949 Binder.restoreCallingIdentity(token);
2950 }
2951 }
2952
junyulaiebd15162021-03-03 12:09:05 +08002953 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002954 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002955 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002956 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002957 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002958
Serik Beketayev05130302021-01-15 16:47:25 -08002959 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002960 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002961 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2962 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002963 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002964 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002965 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002966 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2967 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002968 }
2969 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002970 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002971 }
2972
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002973 @Override
junyulaiebd15162021-03-03 12:09:05 +08002974 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002975 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002976 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002977 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002978
2979 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2980 for (Network network : getAllNetworks()) {
2981 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002982 final boolean includeNetwork = (nai != null) && nai.isCreated();
2983 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002984 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2985 // NetworkCapabilities, which may contain UIDs of apps to which the
2986 // network applies. Should the UIDs be cleared so as not to leak or
2987 // interfere ?
2988 result.add(nai.getNetworkStateSnapshot());
2989 }
2990 }
2991 return result;
2992 }
2993
2994 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002995 public boolean isActiveNetworkMetered() {
2996 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002997
Qingxi Lib2748102020-01-08 12:51:49 -08002998 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002999 if (caps != null) {
3000 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3001 } else {
3002 // Always return the most conservative value
3003 return true;
3004 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07003005 }
3006
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003007 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09003008 * Ensures that the system cannot call a particular method.
3009 */
3010 private boolean disallowedBecauseSystemCaller() {
3011 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07003012 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
3013 // for devices launched with Q and above. However, existing devices upgrading to Q and
3014 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003015 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07003016 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003017 log("This method exists only for app backwards compatibility"
3018 + " and must not be called by system services.");
3019 return true;
3020 }
3021 return false;
3022 }
3023
paulhub2c28682021-08-18 18:35:54 +08003024 private int getAppUid(final String app, final UserHandle user) {
3025 final PackageManager pm =
3026 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
3027 final long token = Binder.clearCallingIdentity();
3028 try {
3029 return pm.getPackageUid(app, 0 /* flags */);
3030 } catch (PackageManager.NameNotFoundException e) {
3031 return -1;
3032 } finally {
3033 Binder.restoreCallingIdentity(token);
3034 }
3035 }
3036
3037 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
3038 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
3039 if (getAppUid(packageName, user) != callingUid) {
3040 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
3041 }
3042 }
3043
Lorenzo Colitti23862912018-09-28 11:31:55 +09003044 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003045 * Ensure that a network route exists to deliver traffic to the specified
3046 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003047 * @param networkType the type of the network over which traffic to the
3048 * specified host is to be routed
3049 * @param hostAddress the IP address of the host to which the route is
3050 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003051 * @return {@code true} on success, {@code false} on failure
3052 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003053 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003054 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3055 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003056 if (disallowedBecauseSystemCaller()) {
3057 return false;
3058 }
paulhub2c28682021-08-18 18:35:54 +08003059 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003060 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003061 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003062 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003063 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003064
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003065 InetAddress addr;
3066 try {
3067 addr = InetAddress.getByAddress(hostAddress);
3068 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003069 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003070 return false;
3071 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003072
The Android Open Source Project28527d22009-03-03 19:31:44 -08003073 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003074 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003075 return false;
3076 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003077
3078 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3079 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003080 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003081 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3082 } else {
3083 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3084 }
3085 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003086 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003087
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003088 DetailedState netState;
3089 synchronized (nai) {
3090 netState = nai.networkInfo.getDetailedState();
3091 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003092
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003093 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003094 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003095 log("requestRouteToHostAddress on down network "
3096 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003097 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003098 }
3099 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003100 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003101
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003102 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003103 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003104 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003105 LinkProperties lp;
3106 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003107 synchronized (nai) {
3108 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003109 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003110 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003111 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003112 if (DBG) {
3113 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3114 }
Wink Saville32506bc2013-06-29 21:10:57 -07003115 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003116 } finally {
3117 Binder.restoreCallingIdentity(token);
3118 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003119 }
3120
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003121 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003122 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003123 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003124 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003125 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003126 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003127 if (bestRoute.getGateway().equals(addr)) {
3128 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003129 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003130 } else {
3131 // if we will connect to this through another route, add a direct route
3132 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003133 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003134 }
3135 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003136 if (DBG) log("Adding legacy route " + bestRoute +
3137 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003138
3139 final String dst = bestRoute.getDestinationLinkAddress().toString();
3140 final String nextHop = bestRoute.hasGateway()
3141 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003142 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003143 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3144 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003145 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003146 return false;
3147 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003148 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003149 }
3150
paulhu7c0a2e62021-01-08 00:51:49 +08003151 class DnsResolverUnsolicitedEventCallback extends
3152 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003153 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003154 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003155 try {
3156 mHandler.sendMessage(mHandler.obtainMessage(
3157 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003158 new PrivateDnsValidationUpdate(event.netId,
3159 InetAddresses.parseNumericAddress(event.ipAddress),
3160 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003161 } catch (IllegalArgumentException e) {
3162 loge("Error parsing ip address in validation event");
3163 }
3164 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003165
3166 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003167 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3168 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003169 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3170 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3171 // event callback for certain nai. e.g. cellular. Register here to pass to
3172 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003173 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003174 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3175 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003176 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003177 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003178 }
3179 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003180
3181 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003182 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3183 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3184 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003185 }
dalyk1720e542018-03-05 12:42:22 -05003186
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003187 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003188 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003189 return this.VERSION;
3190 }
3191
3192 @Override
3193 public String getInterfaceHash() {
3194 return this.HASH;
3195 }
paulhu7c0a2e62021-01-08 00:51:49 +08003196 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003197
3198 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003199 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3200 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003201
paulhu7c0a2e62021-01-08 00:51:49 +08003202 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003203 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003204 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003205 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003206 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003207 }
3208 }
3209
Sudheer Shanka9967d462021-03-18 19:09:25 +00003210 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003211 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003212 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003213 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3214 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003215 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003216 };
3217
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003218 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003219 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003220 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003221 }
3222
Mark Fasheh7c999d82023-05-04 20:23:11 +00003223 static final class UidFrozenStateChangedArgs {
3224 final int[] mUids;
3225 final int[] mFrozenStates;
3226
3227 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3228 mUids = uids;
3229 mFrozenStates = frozenStates;
3230 }
3231 }
3232
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003233 /**
3234 * Check if the cell network is idle.
3235 * @return true if the cell network state is idle
3236 * false if the cell network state is active or unknown
3237 */
3238 private boolean isCellNetworkIdle() {
3239 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3240 if (defaultNai == null
3241 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3242 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3243 // cell network is not the default network, cell network state is unknown.
3244 // TODO(b/279380356): Track cell network state when the cell is not the default network
3245 return false;
3246 }
3247
3248 return !mNetworkActivityTracker.isDefaultNetworkActive();
3249 }
3250
Mark Fasheh7c999d82023-05-04 20:23:11 +00003251 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003252 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003253
3254 for (int i = 0; i < uids.length; i++) {
3255 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003256 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003257 } else {
3258 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003259 }
3260 }
3261
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003262 if (ownerUids.isEmpty()) {
3263 return;
3264 }
3265
3266 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3267 // Delay closing sockets to avoid waking the cell modem up.
3268 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3269 // than waking cell modem up.
3270 mPendingFrozenUids.addAll(ownerUids);
3271 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003272 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003273 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003274 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003275 loge("Exception in socket destroy: " + e);
3276 }
3277 }
3278 }
3279
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003280 private void closePendingFrozenSockets() {
3281 ensureRunningOnConnectivityServiceThread();
3282
3283 try {
3284 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3285 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3286 loge("Failed to close pending frozen app sockets: " + e);
3287 }
3288 mPendingFrozenUids.clear();
3289 }
3290
3291 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3292 mNetworkActivityTracker.handleReportNetworkActivity(params);
3293
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003294 final boolean isCellNetworkActivity;
3295 if (mTrackMultiNetworkActivities) {
3296 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3297 // nai could be null if netd receives a netlink message and calls the network
3298 // activity change callback after the network is unregistered from ConnectivityService.
3299 isCellNetworkActivity = nai != null
3300 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3301 } else {
3302 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3303 }
3304
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003305 if (mDelayDestroyFrozenSockets
3306 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003307 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003308 && !mPendingFrozenUids.isEmpty()) {
3309 closePendingFrozenSockets();
3310 }
3311 }
3312
3313 /**
3314 * If the cellular network is no longer the default network, close pending frozen sockets.
3315 *
3316 * @param newNetwork new default network
3317 * @param oldNetwork old default network
3318 */
3319 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3320 NetworkAgentInfo oldNetwork) {
3321 final boolean isOldNetworkCellular = oldNetwork != null
3322 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3323 final boolean isNewNetworkCellular = newNetwork != null
3324 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3325
3326 if (isOldNetworkCellular
3327 && !isNewNetworkCellular
3328 && !mPendingFrozenUids.isEmpty()) {
3329 closePendingFrozenSockets();
3330 }
3331 }
3332
3333 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3334 pw.println("CloseFrozenAppSockets:");
3335 pw.increaseIndent();
3336 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3337 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3338 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3339 pw.decreaseIndent();
3340 }
3341
Junyu Lai155760b2023-10-05 14:51:00 +08003342 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3343 pw.println("Bpf Program Status:");
3344 pw.increaseIndent();
3345 try {
3346 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003347 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003348 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003349 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003350 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003351 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003352 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003353 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003354 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003355 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003356 } catch (IOException e) {
3357 pw.println(" IOException");
3358 }
3359 pw.decreaseIndent();
3360 }
3361
Mark Fasheh7c999d82023-05-04 20:23:11 +00003362 @VisibleForTesting
3363 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003364 @VisibleForTesting
3365 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3366 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003367
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003368 @VisibleForTesting
3369 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3370 "allow_sysui_connectivity_reports";
3371
Yuyang Huang41557552023-11-28 12:47:22 +09003372 public static final String LOG_BPF_RC = "log_bpf_rc_force_disable";
3373
Paul Jensen83f5d572014-08-29 09:54:01 -04003374 private void enforceInternetPermission() {
3375 mContext.enforceCallingOrSelfPermission(
3376 android.Manifest.permission.INTERNET,
3377 "ConnectivityService");
3378 }
3379
The Android Open Source Project28527d22009-03-03 19:31:44 -08003380 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003381 mContext.enforceCallingOrSelfPermission(
3382 android.Manifest.permission.ACCESS_NETWORK_STATE,
3383 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003384 }
3385
lucaslinc582d502022-01-27 09:07:00 +08003386 private boolean checkAccessPermission(int pid, int uid) {
3387 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3388 == PERMISSION_GRANTED;
3389 }
3390
paulhua6ee2122021-02-22 15:40:43 +08003391 /**
3392 * Performs a strict and comprehensive check of whether a calling package is allowed to
3393 * change the state of network, as the condition differs for pre-M, M+, and
3394 * privileged/preinstalled apps. The caller is expected to have either the
3395 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3396 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3397 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3398 * permission and cannot be revoked. See http://b/23597341
3399 *
3400 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3401 * of this app will be updated to the current time.
3402 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003403 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003404 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3405 == PackageManager.PERMISSION_GRANTED) {
3406 return;
3407 }
3408
3409 if (callingPkg == null) {
3410 throw new SecurityException("Calling package name is null.");
3411 }
3412
3413 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3414 final int uid = mDeps.getCallingUid();
3415 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3416 callingPkg, callingAttributionTag, null /* message */);
3417
3418 if (mode == AppOpsManager.MODE_ALLOWED) {
3419 return;
3420 }
3421
3422 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3423 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3424 return;
3425 }
3426
3427 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3428 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3429 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003430 }
3431
Charles He9369e612017-05-15 17:07:18 +01003432 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003433 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003434 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003435 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003436 }
3437
Quang Luong98858d62023-02-11 00:25:24 +00003438 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003439 enforceAnyPermissionOf(mContext,
3440 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003441 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003442 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3443 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3444 }
3445
paulhu8e96a752019-08-12 16:25:11 +08003446 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003447 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003448 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003449 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003450 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003451 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003452 }
3453
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003454 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003455 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003456 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003457 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003458 android.Manifest.permission.NETWORK_SETTINGS,
3459 android.Manifest.permission.NETWORK_FACTORY,
3460 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3461 }
3462
3463 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003464 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003465 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003466 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003467 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3468 android.Manifest.permission.NETWORK_FACTORY,
3469 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3470 }
3471
lucaslin69e1aa92022-03-22 18:15:09 +08003472 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3473 return PERMISSION_GRANTED == mContext.checkPermission(
3474 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3475 || PERMISSION_GRANTED == mContext.checkPermission(
3476 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3477 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003478 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003479 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003480 }
3481
Chalard Jean9a396cc2018-02-21 18:43:54 +09003482 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003483 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003484 android.Manifest.permission.NETWORK_SETTINGS,
3485 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003486 }
3487
3488 private boolean checkSettingsPermission(int pid, int uid) {
3489 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003490 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3491 || PERMISSION_GRANTED == mContext.checkPermission(
3492 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003493 }
3494
paulhu8e96a752019-08-12 16:25:11 +08003495 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003496 enforceNetworkStackPermissionOr(mContext,
3497 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003498 }
3499
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003500 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003501 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003502 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003503 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003504 }
3505
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003506 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003507 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003508 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3509 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003510 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003511 }
3512
James Mattis8378aec2021-01-26 14:05:36 -08003513 private void enforceOemNetworkPreferencesPermission() {
3514 mContext.enforceCallingOrSelfPermission(
3515 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3516 "ConnectivityService");
3517 }
3518
James Mattisfa270db2021-05-31 17:11:10 -07003519 private void enforceManageTestNetworksPermission() {
3520 mContext.enforceCallingOrSelfPermission(
3521 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3522 "ConnectivityService");
3523 }
3524
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003525 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003526 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003527 android.Manifest.permission.NETWORK_STACK,
3528 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003529 }
3530
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003531 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003532 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003533 android.Manifest.permission.NETWORK_STACK,
3534 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3535 }
3536
Chris Göllnercc962022023-12-26 09:55:32 +00003537 private boolean checkSystemBarServicePermission(int pid, int uid) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003538 return checkAnyPermissionOf(mContext, pid, uid,
3539 android.Manifest.permission.STATUS_BAR_SERVICE);
3540 }
3541
paulhu1a407652019-03-22 16:35:06 +08003542 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003543 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003544 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003545 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3546 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003547 }
3548
Paul Hu8fc2a552022-05-04 18:44:42 +08003549 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3550 boolean checkUidsAllowedList) {
3551 if (PermissionUtils.checkAnyPermissionOf(mContext,
3552 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3553 return true;
3554 }
3555
3556 // fallback to ConnectivityInternalPermission
3557 // TODO: Remove this fallback check after all apps have declared
3558 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3559 if (PermissionUtils.checkAnyPermissionOf(mContext,
3560 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3561 return true;
3562 }
3563
3564 // Check whether uid is in allowed on restricted networks list.
3565 if (checkUidsAllowedList
3566 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3567 return true;
3568 }
3569 return false;
3570 }
3571
3572 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3573 final int callingUid = mDeps.getCallingUid();
3574 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3575 throw new SecurityException("ConnectivityService: user " + callingUid
3576 + " has no permission to access restricted network.");
3577 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003578 }
3579
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003580 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003581 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003582 }
3583
Roshan Pius98f59ec2021-02-23 08:47:39 -08003584 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3585 return PERMISSION_GRANTED == mContext.checkPermission(
3586 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3587 }
3588
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003589 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003590 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003591 }
3592
3593 private void sendInetConditionBroadcast(NetworkInfo info) {
3594 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3595 }
3596
Wink Saville4f0de1e2011-08-04 15:01:58 -07003597 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003598 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003599 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003600 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003601 if (info.isFailover()) {
3602 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3603 info.setFailover(false);
3604 }
3605 if (info.getReason() != null) {
3606 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3607 }
3608 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003609 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3610 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003611 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003612 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003613 return intent;
3614 }
3615
3616 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3617 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3618 }
3619
Michael Groover73f69482023-01-27 11:01:25 -06003620 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3621 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003622 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3623 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003624 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003625 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003626 if (!mSystemReady
3627 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003628 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003629 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003630 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003631 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003632 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003633 }
3634
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003635 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003636 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003637 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003638 final NetworkInfo ni = intent.getParcelableExtra(
3639 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003640 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3641 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003642 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003643 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003644 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003645 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003646 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003647 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003648 } finally {
3649 Binder.restoreCallingIdentity(ident);
3650 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003651 }
3652 }
3653
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003654 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3655 NetworkInfo info) {
3656 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003657 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003658
3659 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3660 try {
3661 // This allows us to discard older broadcasts still waiting to be delivered
3662 // which have the same namespace and key.
3663 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3664 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3665 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003666 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003667 } catch (UnsupportedApiLevelException e) {
3668 Log.wtf(TAG, "Using unsupported API" + e);
3669 }
3670 }
3671
3672 @VisibleForTesting
3673 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3674 final StringBuilder sb = new StringBuilder();
3675 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3676 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3677 sb.append(info.getExtraInfo());
3678 return sb.toString();
3679 }
3680
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003681 /**
Aaron Huang96011892020-06-27 07:18:23 +08003682 * Called by SystemServer through ConnectivityManager when the system is ready.
3683 */
3684 @Override
3685 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003686 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003687 throw new SecurityException("Calling Uid is not system uid.");
3688 }
3689 systemReadyInternal();
3690 }
3691
3692 /**
3693 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003694 */
3695 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003696 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003697 // Load flags after PackageManager is ready to query module version
3698 mFlags.loadFlags(mDeps, mContext);
3699
Aaron Huang9a57acf2020-12-08 10:03:29 +08003700 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3701 // listening network request which is sent by MultipathPolicyTracker won't be added
3702 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3703 // be called after PermissionMonitor#startMonitoring().
3704 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3705 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3706 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003707 final ConditionVariable startMonitoringDone = new ConditionVariable();
3708 mHandler.post(() -> {
3709 mPermissionMonitor.startMonitoring();
3710 startMonitoringDone.open();
3711 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003712 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003713 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003714
Hugo Benichie5220992017-04-26 14:53:28 +09003715 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003716 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003717 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003718 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003719 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003720 }
3721 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003722
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003723 // Create network requests for always-on networks.
3724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003725
3726 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003727 // Note that updating can be skipped here if the list is empty only because no uid
3728 // rules are applied before system ready. Normally, the empty uid list means to clear
3729 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003730 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3731 updateMobileDataPreferredUids();
3732 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003733
3734 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003735 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003736 mBpfNetMaps.setPullAtomCallback(mContext);
3737 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003738 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3739 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003740 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3741 // have permission problem. While CV#block() is unbounded in time and can in principle block
3742 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3743 // could have blocked forever too.
3744 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003745 }
3746
The Android Open Source Project28527d22009-03-03 19:31:44 -08003747 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003748 * Start listening for default data network activity state changes.
3749 */
3750 @Override
3751 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003752 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003753 }
3754
3755 /**
3756 * Stop listening for default data network activity state changes.
3757 */
3758 @Override
3759 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003760 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003761 }
3762
3763 /**
3764 * Check whether the default network radio is currently active.
3765 */
3766 @Override
3767 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003768 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003769 }
3770
3771 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003772 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003773 * and set it on it's iface.
3774 */
Junyu Lai970963e2022-10-25 15:46:47 +08003775 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003776 final String iface = newLp.getInterfaceName();
3777 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003778 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003779 // Silently ignore unset MTU value.
3780 return;
3781 }
Hansen Kurli04252032022-12-07 11:21:49 +00003782 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3783 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3784 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003785 return;
3786 }
Hansen Kurli04252032022-12-07 11:21:49 +00003787 // Cannot set MTU without interface name
3788 if (TextUtils.isEmpty(iface)) {
3789 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003790 return;
3791 }
sy.yun4aa73922013-09-02 05:24:09 +09003792
Hansen Kurli04252032022-12-07 11:21:49 +00003793 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3794 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003795 return;
3796 }
3797
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003798 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003799 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003800 mNetd.interfaceSetMtu(iface, mtu);
3801 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003802 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003803 }
3804 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003805
Chenbo Feng15416292018-11-08 17:36:21 -08003806 @VisibleForTesting
3807 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003808
Junyu Lai970963e2022-10-25 15:46:47 +08003809 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003810 String[] values = null;
3811 if (tcpBufferSizes != null) {
3812 values = tcpBufferSizes.split(",");
3813 }
3814
3815 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003816 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003817 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3818 values = tcpBufferSizes.split(",");
3819 }
3820
3821 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3822
3823 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003824 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003825
Chenbo Feng15416292018-11-08 17:36:21 -08003826 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3827 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3828 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003829 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003830 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003831 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003832 }
3833 }
3834
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003835 @Override
3836 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003837 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003838 NETWORK_RESTORE_DELAY_PROP_NAME);
3839 if(restoreDefaultNetworkDelayStr != null &&
3840 restoreDefaultNetworkDelayStr.length() != 0) {
3841 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003842 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003843 } catch (NumberFormatException e) {
3844 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003845 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003846 // if the system property isn't set, use the value for the apn type
3847 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3848
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003849 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3850 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003851 }
3852 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003853 }
3854
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003855 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003856 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003857 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003858 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003859 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003860 // Start gathering diagnostic information.
3861 netDiags.add(new NetworkDiagnostics(
3862 nai.network,
3863 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003864 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003865 DIAG_TIME_MS));
3866 }
3867
3868 for (NetworkDiagnostics netDiag : netDiags) {
3869 pw.println();
3870 netDiag.waitForMeasurements();
3871 netDiag.dump(pw);
3872 }
3873 }
3874
The Android Open Source Project28527d22009-03-03 19:31:44 -08003875 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003876 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3877 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003878 if (!checkDumpPermission(mContext, TAG, writer)) return;
3879
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003880 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003881 }
3882
lucaslin99473f62020-12-10 15:10:54 +08003883 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3884 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3885 != PackageManager.PERMISSION_GRANTED) {
3886 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003887 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003888 + " due to missing android.permission.DUMP permission");
3889 return false;
3890 } else {
3891 return true;
3892 }
3893 }
3894
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003895 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003896 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003897
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003898 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003899 dumpNetworkDiagnostics(pw);
3900 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003901 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003902 dumpNetworks(pw);
3903 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003904 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003905 dumpNetworkRequests(pw);
3906 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003907 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3908 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3909 dumpTrafficController(pw, fd, verbose);
3910 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003911 }
Erik Kline9647f382015-06-05 17:47:34 +09003912
Junyu Lai0da479b2022-04-20 15:06:29 +08003913 pw.println("NetworkProviders for:");
3914 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003915 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003916 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003917 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003918 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003919 pw.println();
3920
Chalard Jean5b409c72021-02-04 13:12:59 +09003921 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003922 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003923 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003924 pw.println("none");
3925 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003926 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003927 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003928 pw.println();
3929
James Mattis8b298a02021-06-01 22:34:04 -07003930 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003931 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003932 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003933 pw.decreaseIndent();
3934 pw.println();
3935
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003936 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003937 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003938 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003939 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003940 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003941
junyulaif2c67e42018-08-07 19:50:45 +08003942 pw.println("Status for known UIDs:");
3943 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003944 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003945 for (int i = 0; i < size; i++) {
3946 // Don't crash if the array is modified while dumping in bugreports.
3947 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003948 final int uid = mUidBlockedReasons.keyAt(i);
3949 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3950 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003951 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003952 } catch (ArrayIndexOutOfBoundsException e) {
3953 pw.println(" ArrayIndexOutOfBoundsException");
3954 } catch (ConcurrentModificationException e) {
3955 pw.println(" ConcurrentModificationException");
3956 }
3957 }
3958 pw.println();
3959 pw.decreaseIndent();
3960
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003961 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003962 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003963 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003964 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003965 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003966
Junyu Lai0da479b2022-04-20 15:06:29 +08003967 pw.println("Network Offers:");
3968 pw.increaseIndent();
3969 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3970 pw.println(offerInfo.offer);
3971 }
3972 pw.decreaseIndent();
3973 pw.println();
3974
Robert Greenwalt94e22142014-07-30 16:31:24 -07003975 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003976
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003977 pw.println();
markchien5e866652019-09-30 14:40:57 +08003978 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003979
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003980 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003981 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003982
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003983 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003984 dumpCloseFrozenAppSockets(pw);
3985
3986 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003987 dumpBpfProgramStatus(pw);
3988
Chalard Jean53017782022-11-24 17:13:44 +09003989 if (null != mCarrierPrivilegeAuthenticator) {
3990 pw.println();
3991 mCarrierPrivilegeAuthenticator.dump(pw);
3992 }
3993
Junyu Lai155760b2023-10-05 14:51:00 +08003994 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003995
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003996 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003997 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003998 pw.println("mNetworkRequestInfoLogs (most recent first):");
3999 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004000 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09004001 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09004002
4003 pw.println();
4004 pw.println("mNetworkInfoBlockingLogs (most recent first):");
4005 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004006 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09004007 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09004008
4009 pw.println();
4010 pw.println("NetTransition WakeLock activity (most recent first):");
4011 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004012 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
4013 pw.println("total releases: " + mTotalWakelockReleases);
4014 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
4015 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
4016 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
4017 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4018 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
4019 }
James Mattiscb1e0362021-04-06 17:07:42 -07004020 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004021
4022 pw.println();
4023 pw.println("bandwidth update requests (by uid):");
4024 pw.increaseIndent();
4025 synchronized (mBandwidthRequests) {
4026 for (int i = 0; i < mBandwidthRequests.size(); i++) {
4027 pw.println("[" + mBandwidthRequests.keyAt(i)
4028 + "]: " + mBandwidthRequests.valueAt(i));
4029 }
4030 }
4031 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004032 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004033
James Mattiscb1e0362021-04-06 17:07:42 -07004034 pw.println();
4035 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4036 pw.increaseIndent();
4037 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004038 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004039 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004040
4041 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004042
4043 pw.println();
4044 pw.println("Permission Monitor:");
4045 pw.increaseIndent();
4046 mPermissionMonitor.dump(pw);
4047 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004048
4049 pw.println();
4050 pw.println("Legacy network activity:");
4051 pw.increaseIndent();
4052 mNetworkActivityTracker.dump(pw);
4053 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08004054 }
4055
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004056 private void dumpNetworks(IndentingPrintWriter pw) {
4057 for (NetworkAgentInfo nai : networksSortedById()) {
4058 pw.println(nai.toString());
4059 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004060 pw.println("Nat464Xlat:");
4061 pw.increaseIndent();
4062 nai.dumpNat464Xlat(pw);
4063 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004064 pw.println(String.format(
4065 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4066 nai.numForegroundNetworkRequests(),
4067 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4068 nai.numBackgroundNetworkRequests(),
4069 nai.numNetworkRequests()));
4070 pw.increaseIndent();
4071 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4072 pw.println(nai.requestAt(i).toString());
4073 }
4074 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004075 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004076 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004077 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004078 pw.decreaseIndent();
4079 pw.decreaseIndent();
4080 }
4081 }
4082
James Mattis8b298a02021-06-01 22:34:04 -07004083 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4084 if (!mProfileNetworkPreferences.isEmpty()) {
4085 pw.println("Profile preferences:");
4086 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004087 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004088 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004089 }
James Mattis8b298a02021-06-01 22:34:04 -07004090 if (!mOemNetworkPreferences.isEmpty()) {
4091 pw.println("OEM preferences:");
4092 pw.increaseIndent();
4093 pw.println(mOemNetworkPreferences);
4094 pw.decreaseIndent();
4095 }
4096 if (!mMobileDataPreferredUids.isEmpty()) {
4097 pw.println("Mobile data preferred UIDs:");
4098 pw.increaseIndent();
4099 pw.println(mMobileDataPreferredUids);
4100 pw.decreaseIndent();
4101 }
James Mattis45d81842021-01-10 14:24:24 -08004102
James Mattis8b298a02021-06-01 22:34:04 -07004103 pw.println("Default requests:");
4104 pw.increaseIndent();
4105 dumpPerAppDefaultRequests(pw);
4106 pw.decreaseIndent();
4107 }
4108
4109 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004110 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4111 if (mDefaultRequest == defaultRequest) {
4112 continue;
4113 }
4114
James Mattis8b298a02021-06-01 22:34:04 -07004115 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4116 final String networkOutput;
4117 if (null == satisfier) {
4118 networkOutput = "null";
4119 } else if (mNoServiceNetwork.equals(satisfier)) {
4120 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004121 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004122 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004123 }
James Mattis8b298a02021-06-01 22:34:04 -07004124 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4125 ? "" : " asUid: " + defaultRequest.mAsUid;
4126 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4127 + defaultRequest.mPid + asUidString + "]";
4128 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4129 + " Preference order: " + defaultRequest.mPreferenceOrder
4130 + " Tracked UIDs: " + defaultRequest.getUids();
4131 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004132 }
4133 }
4134
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004135 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004136 NetworkRequestInfo[] infos = null;
4137 while (infos == null) {
4138 try {
4139 infos = requestsSortedById();
4140 } catch (ConcurrentModificationException e) {
4141 // mNetworkRequests should only be accessed from handler thread, except dump().
4142 // As dump() is never called in normal usage, it would be needlessly expensive
4143 // to lock the collection only for its benefit. Instead, retry getting the
4144 // requests if ConcurrentModificationException is thrown during dump().
4145 }
4146 }
4147 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004148 pw.println(nri.toString());
4149 }
4150 }
4151
Ken Chene6d511f2022-01-25 11:10:42 +08004152 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4153 boolean verbose) {
4154 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004155 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004156 } catch (ServiceSpecificException e) {
4157 pw.println(e.getMessage());
4158 } catch (IOException e) {
4159 loge("Dump BPF maps failed, " + e);
4160 }
4161 }
4162
Chalard Jean524f0b12021-10-25 21:11:56 +09004163 private void dumpAllRequestInfoLogsToLogcat() {
4164 try (PrintWriter logPw = new PrintWriter(new Writer() {
4165 @Override
4166 public void write(final char[] cbuf, final int off, final int len) {
4167 // This method is called with 0-length and 1-length arrays for empty strings
4168 // or strings containing only the DEL character.
4169 if (len <= 1) return;
4170 Log.e(TAG, new String(cbuf, off, len));
4171 }
4172 @Override public void flush() {}
4173 @Override public void close() {}
4174 })) {
4175 mNetworkRequestInfoLogs.dump(logPw);
4176 }
4177 }
4178
Hugo Benichia480ba52018-09-03 08:19:02 +09004179 /**
4180 * Return an array of all current NetworkAgentInfos sorted by network id.
4181 */
4182 private NetworkAgentInfo[] networksSortedById() {
4183 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004184 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004185 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004186 return networks;
4187 }
4188
4189 /**
4190 * Return an array of all current NetworkRequest sorted by request id.
4191 */
James Mattis258ea3c2020-11-15 15:04:40 -08004192 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004193 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004194 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004195 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004196 // Sort the array based off the NRI containing the min requestId in its requests.
4197 Arrays.sort(requests,
4198 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4199 Comparator.comparingInt(req -> req.requestId)).requestId
4200 )
4201 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004202 return requests;
4203 }
4204
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004205 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004206 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004207 if (officialNai != null && officialNai.equals(nai)) return true;
4208 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004209 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004210 " - " + nai);
4211 }
4212 return false;
4213 }
4214
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004215 private boolean isDisconnectRequest(Message msg) {
4216 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4217 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4218 return info.getState() == NetworkInfo.State.DISCONNECTED;
4219 }
4220
Robert Greenwalt2034b912009-08-12 16:08:25 -07004221 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004222 private class NetworkStateTrackerHandler extends Handler {
4223 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004224 super(looper);
4225 }
4226
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004227 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004228 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4229 final NetworkAgentInfo nai = arg.first;
4230 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004231 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004232 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004233 }
4234 return;
4235 }
4236
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004237 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004238 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004239 return;
4240 }
4241
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004242 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004243 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004244 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4245 if (!nai.respectsNcStructuralConstraints(proposed)) {
4246 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4247 + nai.networkCapabilities + " -> " + proposed);
4248 disconnectAndDestroyNetwork(nai);
4249 return;
4250 }
4251 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004252 final NetworkCapabilities sanitized =
4253 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004254 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004255 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004256 break;
4257 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004258 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004259 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004260 processLinkPropertiesFromAgent(nai, newLp);
4261 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004262 break;
4263 }
4264 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004265 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004266 updateNetworkInfo(nai, info);
4267 break;
4268 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004269 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4270 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004271 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004272 break;
4273 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004274 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004275 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004276 break;
4277 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004278 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004279 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004280 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004281 // Note that if the NAI had been connected, this would affect the
4282 // score, and therefore would require re-mixing the score and performing
4283 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004284 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004285 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4286 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004287 // Mark the network as temporarily accepting partial connectivity so that it
4288 // will be validated (and possibly become default) even if it only provides
4289 // partial internet access. Note that if user connects to partial connectivity
4290 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4291 // out of wifi coverage) and if the same wifi is available again, the device
4292 // will auto connect to this wifi even though the wifi has "no internet".
4293 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004294 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004295 break;
4296 }
junyulai011b1f12019-01-03 18:50:15 +08004297 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004298 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004299 break;
4300 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004301 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004302 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004303 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004304
4305 if (isLegacyLockdownNai(nai)
4306 && (underlying == null || underlying.size() != 1)) {
4307 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4308 + " must have exactly one underlying network: " + underlying);
4309 }
4310
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004311 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4312 nai.declaredUnderlyingNetworks = (underlying != null)
4313 ? underlying.toArray(new Network[0]) : null;
4314
4315 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4316 if (DBG) {
4317 log(nai.toShortString() + " changed underlying networks to "
4318 + Arrays.toString(nai.declaredUnderlyingNetworks));
4319 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004320 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004321 notifyIfacesChangedForNetworkStats();
4322 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004323 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004324 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004325 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4326 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4327 nai.teardownDelayMs = msg.arg1;
4328 } else {
4329 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4330 }
Chalard Jean550b5212021-03-05 23:07:53 +09004331 break;
4332 }
4333 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4334 nai.setLingerDuration((int) arg.second);
4335 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004336 }
Tyler Wear72388212021-09-09 14:49:02 -07004337 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4338 DscpPolicy policy = (DscpPolicy) arg.second;
4339 if (mDscpPolicyTracker != null) {
4340 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4341 }
4342 break;
4343 }
4344 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4345 if (mDscpPolicyTracker != null) {
4346 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4347 }
4348 break;
4349 }
4350 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4351 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004352 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004353 }
4354 break;
4355 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004356 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004357 if (!nai.everConnected()) {
4358 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4359 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004360 teardownUnneededNetwork(nai);
4361 break;
4362 }
4363
4364 if (nai.isDestroyed()) {
4365 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4366 + ", ignoring");
4367 break;
4368 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004369
4370 final int timeoutMs = (int) arg.second;
4371 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4372 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4373 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4374 }
4375
4376 // Marking a network awaiting replacement is used to ensure that any requests
4377 // satisfied by the network do not switch to another network until a
4378 // replacement is available or the wait for a replacement times out.
4379 // If the network is inactive (i.e., nascent or lingering), then there are no
4380 // such requests, and there is no point keeping it. Just tear it down.
4381 // Note that setLingerDuration(0) cannot be used to do this because the network
4382 // could be nascent.
4383 nai.clearInactivityState();
4384 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4385 Log.d(TAG, nai.toShortString()
4386 + " marked awaiting replacement is unneeded, tearing down instead");
4387 teardownUnneededNetwork(nai);
4388 break;
4389 }
4390
4391 Log.d(TAG, "Marking " + nai.toShortString()
4392 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4393 destroyNativeNetwork(nai);
4394
4395 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4396 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4397 // consider the fact that the network could already have disconnected or been
4398 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4399 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4400 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4401 mKeepaliveTracker.handleStopAllKeepalives(nai,
4402 SocketKeepalive.ERROR_INVALID_NETWORK);
4403
4404 nai.updateScoreForNetworkAgentUpdate();
4405 // This rematch is almost certainly not going to result in any changes, because
4406 // the destroyed flag is only just above the "current satisfier wins"
4407 // tie-breaker. But technically anything that affects scoring should rematch.
4408 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004409 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004410 break;
4411 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004412 }
4413 }
4414
4415 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004416 final int netId = msg.arg2;
4417 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004418 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004419 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004420 switch (msg.what) {
4421 default:
4422 return false;
lucasline117e2e2019-10-22 18:27:33 +08004423 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004424 if (nai == null) {
4425 break;
4426 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004427 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4428 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004429 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004430 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004431 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004432 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004433 if (probePrivateDnsCompleted) {
4434 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4435 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004436 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004437 }
4438 // Only show the notification when the private DNS is broken and the
4439 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004440 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004441 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4442 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004443 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004444 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4445 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4446 // private DNS is broken, it means this network is being reevaluated.
4447 // Either probing private DNS is not necessary any more or it hasn't been
4448 // done yet. In either case, the networkCapabilities should be updated to
4449 // reflect the new status.
4450 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004451 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004452 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004453 }
4454 break;
4455 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004456 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004457 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4458
Erik Kline31b4a9e2018-01-11 21:07:29 +09004459 if (nai == null) break;
4460
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004461 handleNetworkTested(nai, results.mTestResult,
4462 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004463 break;
4464 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004465 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004466 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004467 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004468 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004469 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004470 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004471 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4472 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004473 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004474 if (nai == null) {
4475 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4476 break;
4477 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004478 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004479 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004480 (PendingIntent) msg.obj,
4481 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004482 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004483 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004484 break;
4485 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004486 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004487 if (nai == null) break;
4488
Erik Kline9a62f012018-03-21 07:18:33 -07004489 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004490 break;
4491 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004492 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004493 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004494 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004495 break;
4496 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004497 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004498 return true;
4499 }
4500
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004501 private void handleNetworkTested(
4502 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004503 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4504 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004505 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004506
4507 // If there is any kind of working networking, then the NAI has been evaluated
4508 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4509 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004510 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004511 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004512 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4513 // any callback that receives onAvailable for that rematch receives an extra caps
4514 // callback. To prevent that, update the score in the agent so the updates below won't
4515 // see an update to both caps and score at the same time.
4516 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004517 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4518
he_won.hwang881307a2022-03-15 21:23:52 +09004519 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4520 // Assume the validation failure is due to a temporary failure after roaming
4521 // and ignore it. NetworkMonitor will continue to retry validation. If it
4522 // continues to fail after the block timeout expires, the network will be
4523 // marked unvalidated. If it succeeds, then validation state will not change.
4524 return;
4525 }
4526
Chalard Jean254bd162022-08-25 13:04:51 +09004527 final boolean wasValidated = nai.isValidated();
4528 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004529 final boolean wasPortal = nai.captivePortalDetected();
4530 nai.setPartialConnectivity(partial);
4531 nai.setCaptivePortalDetected(portal);
4532 nai.updateScoreForNetworkAgentUpdate();
4533 final boolean partialConnectivityChanged = (wasPartial != partial);
4534 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004535
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004536 if (DBG) {
4537 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4538 ? " with redirect to " + redirectUrl
4539 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004540 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004541 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004542 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004543 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004544 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004545 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004546 if (valid) {
4547 handleFreshlyValidatedNetwork(nai);
4548 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4549 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004550 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004551 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004552 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004553 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004554 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004555 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004556 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004557 NotificationType.PRIVATE_DNS_BROKEN);
4558 // If network becomes valid, the hasShownBroken should be reset for
4559 // that network so that the notification will be fired when the private
4560 // DNS is broken again.
4561 nai.networkAgentConfig.hasShownBroken = false;
4562 }
4563 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004564 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004565 } else if (portalChanged) {
4566 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004567 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004568 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4569 nai.onPreventAutomaticReconnect();
4570 teardownUnneededNetwork(nai);
4571 return;
4572 } else {
4573 updateCapabilitiesForNetwork(nai);
4574 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004575 } else if (becameEvaluated) {
4576 // If valid or partial connectivity changed, updateCapabilities* has
4577 // done the rematch.
4578 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004579 }
4580 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004581
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004582 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004583 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004584 nai.onValidationStatusChanged(
4585 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4586 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004587
4588 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004589 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004590 // immediately. Re-notify partial connectivity silently if no internet
4591 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004592 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004593 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004594 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4595 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004596 }
4597
Chalard Jean254bd162022-08-25 13:04:51 +09004598 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004599 handleNetworkUnvalidated(nai);
4600 }
4601 }
4602
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004603 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4604 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4605 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4606 // Do not avoid captive portal when network is wear proxy.
4607 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4608 }
4609
Calvin Ondada1452016-10-11 15:10:46 -07004610 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004611 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4612 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004613 }
4614
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004615 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4616 switch (msg.what) {
4617 default:
4618 return false;
4619 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4620 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4621 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4622 handleLingerComplete(nai);
4623 }
4624 break;
4625 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004626 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4627 handleNetworkAgentRegistered(msg);
4628 break;
4629 }
4630 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4631 handleNetworkAgentDisconnected(msg);
4632 break;
4633 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004634 }
4635 return true;
4636 }
4637
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004638 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004639 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004640 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004641 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004642 maybeHandleNetworkAgentMessage(msg);
4643 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004644 }
4645 }
4646
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004647 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004648 private final int mNetId;
4649 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004650
4651 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004652 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004653 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004654 }
4655
4656 @Override
4657 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4658 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004659 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004660 }
4661
4662 @Override
4663 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004664 // Legacy version of notifyNetworkTestedWithExtras.
4665 // Would only be called if the system has a NetworkStack module older than the
4666 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004667 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004668 }
4669
4670 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004671 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004672 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4673 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004674 final Message msg = mTrackerHandler.obtainMessage(
4675 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004676 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004677 new NetworkTestedResults(
4678 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004679 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004680
4681 // Invoke ConnectivityReport generation for this Network test event.
4682 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4683 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004684
Cody Kestingf1120be2020-08-03 18:01:40 -07004685 // NetworkMonitor reports the network validation result as a bitmask while
4686 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4687 // logical value for ConnectivityDiagnostics.
4688 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4689 p.result);
4690
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004691 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004692 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004693 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4694 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4695
Aaron Huang959d3642021-01-21 15:47:41 +08004696 ConnectivityReportEvent reportEvent =
4697 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4698 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004699 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004700 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004701 }
4702
4703 @Override
4704 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4705 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4706 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004707 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004708 }
4709
4710 @Override
lucasline117e2e2019-10-22 18:27:33 +08004711 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4712 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4713 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004714 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004715 }
4716
4717 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004718 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4719 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4720 EVENT_CAPPORT_DATA_CHANGED,
4721 0, mNetId, data));
4722 }
4723
4724 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004725 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004726 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004727 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004728
4729 final PendingIntent pendingIntent;
4730 // Only the system server can register notifications with package "android"
4731 final long token = Binder.clearCallingIdentity();
4732 try {
paulhu7746e4e2020-06-09 19:07:03 +08004733 pendingIntent = PendingIntent.getBroadcast(
4734 mContext,
4735 0 /* requestCode */,
4736 intent,
4737 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004738 } finally {
4739 Binder.restoreCallingIdentity(token);
4740 }
4741 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4742 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004743 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004744 }
4745
4746 @Override
4747 public void hideProvisioningNotification() {
4748 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004749 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004750 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004751
4752 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004753 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004754 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004755 }
4756
4757 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004758 public int getInterfaceVersion() {
4759 return this.VERSION;
4760 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004761
4762 @Override
4763 public String getInterfaceHash() {
4764 return this.HASH;
4765 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004766 }
4767
Cody Kestingf1120be2020-08-03 18:01:40 -07004768 /**
4769 * Converts the given NetworkMonitor-specific validation result bitmask to a
4770 * ConnectivityDiagnostics-specific validation result int.
4771 */
4772 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4773 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4774 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4775 }
4776 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4777 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4778 }
4779 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4780 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4781 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4782 }
4783
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004784 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004785 log("Data stall detected with methods: " + p.detectionMethod);
4786
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004787 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004788 int detectionMethod = 0;
4789 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4790 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4791 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4792 }
4793 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4794 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4795 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4796 p.tcpMetricsCollectionPeriodMillis);
4797 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004798 }
4799
Cody Kestingf53a0752020-04-15 12:33:28 -07004800 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004801 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004802 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004803
4804 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4805 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4806 // the cost of going through two handlers.
4807 mConnectivityDiagnosticsHandler.sendMessage(msg);
4808 }
4809
Cody Kestingb37958e2020-05-15 10:36:01 -07004810 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4811 return (p.detectionMethod & detectionMethod) != 0;
4812 }
4813
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004814 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4815 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004816 }
4817
Erik Klinea73af002018-06-26 18:53:43 +09004818 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4819 if (nai == null) return;
4820 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4821 // in order to restart a validation pass from within netd.
4822 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00004823 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004824 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004825 }
4826 }
4827
Erik Kline31b4a9e2018-01-11 21:07:29 +09004828 private void handlePrivateDnsSettingsChanged() {
4829 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4830
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004831 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004832 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004833 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004834 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4835 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004836 }
4837 }
4838
Erik Kline9a62f012018-03-21 07:18:33 -07004839 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4840 // Private DNS only ever applies to networks that might provide
4841 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004842 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004843
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004844 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004845 // schedule DNS resolutions. If a DNS resolution is required the
4846 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004847 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004848
4849 // With Private DNS bypass support, we can proceed to update the
4850 // Private DNS config immediately, even if we're in strict mode
4851 // and have not yet resolved the provider name into a set of IPs.
4852 updatePrivateDns(nai, cfg);
4853 }
4854
4855 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4856 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004857 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004858 }
4859
dalyk1720e542018-03-05 12:42:22 -05004860 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4861 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4862 if (nai == null) {
4863 return;
4864 }
4865 mDnsManager.updatePrivateDnsValidation(update);
4866 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4867 }
4868
paulhu7c0a2e62021-01-08 00:51:49 +08004869 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004870 int prefixLength) {
4871 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4872 if (nai == null) return;
4873
paulhu7c0a2e62021-01-08 00:51:49 +08004874 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4875 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004876
4877 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004878 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004879 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004880 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004881 prefixLength);
4882 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004883 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004884 return;
4885 }
4886 }
4887
Lorenzo Colittid523d142020-04-01 20:16:30 +09004888 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004889 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4890 }
4891
Hai Shalome58bdc62021-01-11 18:45:34 -08004892 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004893 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004894 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004895 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4896 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4897 }
4898
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004899 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004900 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004901 * @param nai the agent info to update
4902 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004903 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004904 */
junyulai2b6f0c22021-02-03 20:15:30 +08004905 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4906 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4907 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004908 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004909 // one lingered request, set inactive.
4910 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004911 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004912 if (DBG) log("Unsetting inactive " + nai.toShortString());
4913 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004914 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004915 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004916 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004917 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4918 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004919 }
junyulai2b6f0c22021-02-03 20:15:30 +08004920 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004921 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004922 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004923 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004924 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004925 }
4926
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004927 private void handleNetworkAgentRegistered(Message msg) {
4928 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4929 if (!mNetworkAgentInfos.contains(nai)) {
4930 return;
4931 }
4932
4933 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4934 if (VDBG) log("NetworkAgent registered");
4935 } else {
4936 loge("Error connecting NetworkAgent");
4937 mNetworkAgentInfos.remove(nai);
4938 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004939 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004940 synchronized (mNetworkForNetId) {
4941 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004942 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004943 mNetIdManager.releaseNetId(nai.network.getNetId());
4944 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004945 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004946 }
4947 }
4948 }
Paul Jensend5f53392014-11-25 15:26:53 -05004949
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004950 @VisibleForTesting
4951 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004952 // The feature of creating the networks immediately was slated for U, but race conditions
4953 // detected late required this was flagged off.
4954 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4955 // in NetworkAgentTest.
4956 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004957 }
4958
4959 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4960 @NonNull NetworkInfo.State state) {
4961 if (nai.isCreated()) return false;
4962 if (state == NetworkInfo.State.CONNECTED) return true;
4963 if (state != NetworkInfo.State.CONNECTING) {
4964 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004965 if (shouldCreateNetworksImmediately()) {
4966 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4967 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004968 return false;
4969 }
4970 return nai.isVPN() || shouldCreateNetworksImmediately();
4971 }
4972
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004973 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004974 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004975 }
4976
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004977 @VisibleForTesting
4978 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004979 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004980 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004981
4982 // If the network never roamed, return false. The check below is not sufficient if time
4983 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4984 if (nai.lastRoamTime == 0) return false;
4985
he_won.hwang881307a2022-03-15 21:23:52 +09004986 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4987 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004988 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004989 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004990 final long currentTimeMs = SystemClock.elapsedRealtime();
4991 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004992 if (timeSinceLastRoam <= blockTimeOut) {
4993 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4994 return true;
4995 }
4996 }
4997 return false;
4998 }
4999
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005000 private void handleNetworkAgentDisconnected(Message msg) {
5001 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07005002 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005003 }
5004
Chalard Jeand9fffc32018-05-11 20:19:20 +09005005 // Destroys a network, remove references to it from the internal state managed by
5006 // ConnectivityService, free its interfaces and clean up.
5007 // Must be called on the Handler thread.
5008 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005009 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07005010
5011 if (!mNetworkAgentInfos.contains(nai)) return;
5012
Chalard Jeand9fffc32018-05-11 20:19:20 +09005013 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09005014 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005015 }
lucaslinb25c9a62019-02-12 15:30:13 +08005016 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005017 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005018 // A network agent has disconnected.
5019 // TODO - if we move the logic to the network agent (have them disconnect
5020 // because they lost all their requests or because their score isn't good)
5021 // then they would disconnect organically, report their new state and then
5022 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08005023 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005024 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
5025 null, null);
5026 }
Chalard Jean5b409c72021-02-04 13:12:59 +09005027 final boolean wasDefault = isDefaultNetwork(nai);
5028 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005029 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09005030 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005031 if (mTrackMultiNetworkActivities) {
5032 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
5033 // the network becomes no longer the default network.
5034 mNetworkActivityTracker.removeDataActivityTracking(nai);
5035 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005036 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005037 // If this was a local network forwarded to some upstream, or if some local network was
5038 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005039 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005040 // If this is a local network with an upstream selector, remove the associated network
5041 // request.
5042 if (nai.isLocalNetwork()) {
5043 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5044 if (null != selector) {
5045 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5046 }
5047 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005048 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5049 // by other networks that are already connected. Perhaps that can be done by
5050 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5051 // of rematchAllNetworksAndRequests
5052 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005053 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005054
5055 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005056 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5057 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005058 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005059 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005060 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005061 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005062 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005063 synchronized (mNetworkForNetId) {
5064 // Remove the NetworkAgent, but don't mark the netId as
5065 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005066 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005067 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005068 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005069 // Update allowed network lists in netd. This should be called after removing nai
5070 // from mNetworkAgentInfos.
5071 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005072 // Remove all previously satisfied requests.
5073 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005074 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005075 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005076 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005077 if (currentNetwork != null
5078 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005079 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005080 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5081 // rematch not to keep disconnected agents instead of setting it here ; this
5082 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005083 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005084 for (final NetworkOfferInfo noi : mNetworkOffers) {
5085 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005086 }
James Mattise3ef1912020-12-20 11:09:58 -08005087
Chalard Jean5b409c72021-02-04 13:12:59 +09005088 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005089 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005090 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005091 ensureNetworkTransitionWakelock(nai.toShortString());
5092 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005093 }
5094 }
junyulai2b6f0c22021-02-03 20:15:30 +08005095 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005096 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005097 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005098 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005099 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005100 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005101 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005102
Aaron Huang9fe47be2021-06-08 13:11:45 +08005103 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5104 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5105 // not called by the rematch in this case. This is because the code above unset
5106 // this network from the default request's satisfier, and that is what the rematch
5107 // is using as its source data to know what the old satisfier was. So as far as the
5108 // rematch above is concerned, the old default network was null.
5109 // Therefore if there is no new default, the default network was null and is still
5110 // null, thus there was no change so makeDefault() is not called. So if the old
5111 // network had a proxy and there is no new default, the proxy tracker should be told
5112 // that there is no longer a default proxy.
5113 // Strictly speaking this is not essential because having a proxy setting when
5114 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5115 mProxyTracker.setDefaultProxy(null);
5116 }
5117
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005118 // Immediate teardown.
5119 if (nai.teardownDelayMs == 0) {
5120 destroyNetwork(nai);
5121 return;
5122 }
5123
5124 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005125 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305126 try {
5127 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5128 } catch (RemoteException e) {
5129 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5130 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005131 }
5132 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5133 }
5134
5135 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005136 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005137 // Tell netd to clean up the configuration for this network
5138 // (routing rules, DNS, etc).
5139 // This may be slow as it requires a lot of netd shelling out to ip and
5140 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005141 // after we've rematched networks with requests (which might change the default
5142 // network or service a new request from an app), so network traffic isn't interrupted
5143 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005144 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005145 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005146 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005147 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5148 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5149 // false if the network was never created.
5150 // TODO: delete when S is no longer supported.
5151 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005152 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005153 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005154 }
5155
Chalard Jean1e4c2182023-10-06 18:45:53 +09005156 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005157 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005158 // Step 1 : maybe this network was the upstream for one or more local networks.
5159 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5160 if (!local.isLocalNetwork()) continue;
5161 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5162 if (null == selector) continue;
5163 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5164 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5165 // called after removing all associated NRIs from mNetworkRequests.
5166 if (null == nri) continue;
5167 final NetworkAgentInfo satisfier = nri.getSatisfier();
5168 if (disconnecting != satisfier) continue;
5169 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005170 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5171 // correctly contains null as an upstream.
5172 if (sendCallbacks) {
5173 nri.setSatisfier(null, null);
5174 notifyNetworkCallbacks(local,
5175 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5176 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005177 }
5178
5179 // Step 2 : maybe this is a local network that had an upstream.
5180 if (!disconnecting.isLocalNetwork()) return;
5181 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5182 if (null == selector) return;
5183 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5184 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5185 // is called after removing all associated NRIs from mNetworkRequests.
5186 if (null == nri) return;
5187 final NetworkAgentInfo satisfier = nri.getSatisfier();
5188 if (null == satisfier) return;
5189 removeLocalNetworkUpstream(disconnecting, satisfier);
5190 }
5191
5192 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5193 @NonNull final NetworkAgentInfo upstream) {
5194 try {
5195 mRoutingCoordinatorService.removeInterfaceForward(
5196 localAgent.linkProperties.getInterfaceName(),
5197 upstream.linkProperties.getInterfaceName());
5198 } catch (RemoteException e) {
5199 loge("Couldn't remove interface forward for "
5200 + localAgent.linkProperties.getInterfaceName() + " to "
5201 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5202 }
5203 }
5204
Ken Chen6df7a902021-04-09 15:08:42 +08005205 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005206 try {
5207 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005208 final NativeNetworkConfig config;
5209 if (nai.isVPN()) {
5210 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005211 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005212 return false;
5213 }
5214 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5215 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005216 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005217 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005218 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005219 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005220 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5221 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005222 getNetworkPermission(nai.networkCapabilities),
5223 false /* secure */,
5224 VpnManager.TYPE_VPN_NONE,
5225 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005226 }
Ken Chen6df7a902021-04-09 15:08:42 +08005227 mNetd.networkCreate(config);
5228 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005229 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5230 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005231 return true;
5232 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005233 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005234 return false;
5235 }
5236 }
5237
Ken Chen6df7a902021-04-09 15:08:42 +08005238 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005239 if (mDscpPolicyTracker != null) {
5240 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5241 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005242 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005243 // the interface is going to go away. Don't send the callbacks however ; if the network
5244 // was is being disconnected the callbacks have already been sent, and if it is being
5245 // destroyed pending replacement they will be sent when it is disconnected.
5246 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005247 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005248 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005249 } catch (RemoteException | ServiceSpecificException e) {
5250 loge("Exception destroying network(networkDestroy): " + e);
5251 }
5252 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005253 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005254 } catch (RemoteException | ServiceSpecificException e) {
5255 loge("Exception destroying network: " + e);
5256 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005257 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5258 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5259 // gets created, could add data to DnsManager data structures that will never get deleted.
5260 mDnsManager.removeNetwork(nai.network);
5261
5262 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005263 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005264 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5265 }
5266
Chalard Jean254bd162022-08-25 13:04:51 +09005267 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005268 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005269 }
5270
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005271 // If this method proves to be too slow then we can maintain a separate
5272 // pendingIntent => NetworkRequestInfo map.
5273 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5274 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005275 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5276 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5277 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005278 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005279 return entry.getValue();
5280 }
5281 }
5282 return null;
5283 }
5284
Chalard Jean524f0b12021-10-25 21:11:56 +09005285 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005286 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005287 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5288 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5289 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5290 // bug is fixed.
5291 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005292 throw new IllegalStateException("This NRI is already registered. New : " + nri
5293 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005294 }
5295 }
5296 }
5297 }
5298
Chalard Jeanac9ace02022-01-26 16:54:05 +09005299 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5300 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005301 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09005302 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09005303 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005304 }
5305 return false;
5306 }
5307
James Mattisf7027322020-12-13 16:28:14 -08005308 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005309 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005310 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5311 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5312 final NetworkRequestInfo existingRequest =
5313 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005314 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005315 if (DBG) {
5316 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5317 + nri.mRequests.get(0) + " because their intents matched.");
5318 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005319 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005320 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005321 }
Erik Kline05f2b402015-04-30 12:58:40 +09005322 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005323 }
5324
James Mattisf7027322020-12-13 16:28:14 -08005325 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005326 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005327 }
5328
James Mattis3ce3d3c2021-02-09 18:18:28 -08005329 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005330 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005331 for (final NetworkRequestInfo nri : nris) {
5332 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005333 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005334 for (final NetworkRequest req : nri.mRequests) {
5335 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005336 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005337 if (req.isListen()) {
5338 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5339 if (req.networkCapabilities.hasSignalStrength()
5340 && network.satisfiesImmutableCapabilitiesOf(req)) {
5341 updateSignalStrengthThresholds(network, "REGISTER", req);
5342 }
James Mattisf7027322020-12-13 16:28:14 -08005343 }
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005344 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5345 mNetworkRequestStateStatsMetrics.onNetworkRequestReceived(req);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005346 }
5347 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005348
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005349 // If this NRI has a satisfier already, it is replacing an older request that
5350 // has been removed. Track it.
5351 final NetworkRequest activeRequest = nri.getActiveRequest();
5352 if (null != activeRequest) {
5353 // If there is an active request, then for sure there is a satisfier.
5354 nri.getSatisfier().addRequest(activeRequest);
5355 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005356 }
James Mattisf7027322020-12-13 16:28:14 -08005357
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005358 if (mFlags.noRematchAllRequestsOnRegister()) {
5359 rematchNetworksAndRequests(nris);
5360 } else {
5361 rematchAllNetworksAndRequests();
5362 }
James Mattis45d81842021-01-10 14:24:24 -08005363
Chalard Jean0354d8c2021-01-12 10:58:56 +09005364 // Requests that have not been matched to a network will not have been sent to the
5365 // providers, because the old satisfier and the new satisfier are the same (null in this
5366 // case). Send these requests to the providers.
5367 for (final NetworkRequestInfo nri : nris) {
5368 for (final NetworkOfferInfo noi : mNetworkOffers) {
5369 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005370 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005371 }
5372 }
5373
James Mattisf7027322020-12-13 16:28:14 -08005374 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5375 final int callingUid) {
5376 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005377 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005378 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5379 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5380 handleReleaseNetworkRequest(
5381 nri.mRequests.get(0),
5382 callingUid,
5383 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005384 }
5385 }
5386
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005387 // Determines whether the network is the best (or could become the best, if it validated), for
5388 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5389 // on the value of reason:
5390 //
5391 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5392 // then it should be torn down.
5393 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5394 // then it should be lingered.
5395 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005396 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005397
Chalard Jean254bd162022-08-25 13:04:51 +09005398 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005399 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5400 return false;
5401 }
5402
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005403 final int numRequests;
5404 switch (reason) {
5405 case TEARDOWN:
5406 numRequests = nai.numRequestNetworkRequests();
5407 break;
5408 case LINGER:
5409 numRequests = nai.numForegroundNetworkRequests();
5410 break;
5411 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005412 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005413 return true;
5414 }
5415
Chalard Jean947acd42021-03-08 22:29:27 +09005416 if (numRequests > 0) return false;
5417
Paul Jensende49eb12015-06-25 15:30:08 -04005418 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005419 if (reason == UnneededFor.LINGER
5420 && !nri.isMultilayerRequest()
5421 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005422 // Background requests don't affect lingering.
5423 continue;
5424 }
5425
James Mattis3d229892020-11-16 16:46:28 -08005426 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005427 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005428 }
5429 }
Paul Jensende49eb12015-06-25 15:30:08 -04005430 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005431 }
5432
James Mattis3d229892020-11-16 16:46:28 -08005433 private boolean isNetworkPotentialSatisfier(
5434 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005435 // While destroyed network sometimes satisfy requests (including occasionally newly
5436 // satisfying requests), *potential* satisfiers are networks that might beat a current
5437 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5438 // because it's never a good idea to keep a destroyed network in case it validates.
5439 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5440 // candidate after it's been replaced by another unvalidated network.
5441 if (candidate.isDestroyed()) return false;
5442 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005443 // request, return immediately. For multilayer requests, check to see if any of the
5444 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005445 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5446 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005447 return false;
5448 }
5449 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005450 // This multilayer listen request is satisfied therefore no further requests need to be
5451 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005452 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005453 return false;
5454 }
James Mattis3d229892020-11-16 16:46:28 -08005455 // As non-multilayer listen requests have already returned, the below would only happen
5456 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005457 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005458 continue;
5459 }
Chalard Jean80685f42023-10-30 18:31:27 +09005460 // If there is hope for this network might validate and subsequently become the best
5461 // network for that request, then it is needed. Note that this network can't already
5462 // be the best for this request, or it would be the current satisfier, and therefore
5463 // there would be no need to call this method to find out if it is a *potential*
5464 // satisfier ("unneeded", the only caller, only calls this if this network currently
5465 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005466 if (candidate.satisfies(req)) {
5467 // As soon as a network is found that satisfies a request, return. Specifically for
5468 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5469 // is important so as to not evaluate lower priority requests further in
5470 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005471 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5472 ? nri.getSatisfier() : null;
5473 // Note that this catches two important cases:
5474 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5475 // is currently satisfying the request. This is desirable when
5476 // cellular ends up validating but WiFi does not.
5477 // 2. Unvalidated WiFi will not be reaped when validated cellular
5478 // is currently satisfying the request. This is desirable when
5479 // WiFi ends up validating and out scoring cellular.
5480 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005481 }
5482 }
5483
5484 return false;
5485 }
5486
Erik Kline0c04b742016-07-07 16:50:58 +09005487 private NetworkRequestInfo getNriForAppRequest(
5488 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005489 // Looking up the app passed param request in mRequests isn't possible since it may return
5490 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5491 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005492 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5493 // to avoid potential race conditions when validating a package->uid mapping when sending
5494 // the callback on the very low-chance that an application shuts down prior to the callback
5495 // being sent.
5496 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5497 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005498
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005499 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005500 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005501 log(String.format("UID %d attempted to %s for unowned request %s",
5502 callingUid, requestedOperation, nri));
5503 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005504 }
Erik Kline0c04b742016-07-07 16:50:58 +09005505 }
5506
5507 return nri;
5508 }
5509
James Mattisf7027322020-12-13 16:28:14 -08005510 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5511 final String callingMethod) {
5512 if (nri.isMultilayerRequest()) {
5513 throw new IllegalStateException(
5514 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005515 }
5516 }
5517
James Mattisf7027322020-12-13 16:28:14 -08005518 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005519 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005520 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5521 // single NetworkRequest and thus does not apply to multilayer requests.
5522 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5523 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005524 return;
5525 }
James Mattis2516da32021-01-31 17:06:19 -08005526 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005527 return;
5528 }
James Mattisf7027322020-12-13 16:28:14 -08005529 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5530 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005531 }
5532 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005533 callCallbackForRequest(
5534 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005535 }
5536
James Mattisf7027322020-12-13 16:28:14 -08005537 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5538 final int callingUid,
5539 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005540 final NetworkRequestInfo nri =
5541 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5542 if (nri == null) {
5543 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005544 }
James Mattisf7027322020-12-13 16:28:14 -08005545 if (VDBG || (DBG && request.isRequest())) {
5546 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005547 }
5548 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005549 if (callOnUnavailable) {
5550 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5551 }
Erik Kline155a59a2015-11-25 12:49:38 +09005552 }
Erik Kline0c04b742016-07-07 16:50:58 +09005553
James Mattisa076c532020-12-02 14:12:41 -08005554 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005555 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005556 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005557 if (null == mNetworkRequests.remove(req)) {
5558 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5559 continue;
5560 }
James Mattisa076c532020-12-02 14:12:41 -08005561 if (req.isListen()) {
5562 removeListenRequestFromNetworks(req);
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005563 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5564 mNetworkRequestStateStatsMetrics.onNetworkRequestRemoved(req);
James Mattisa076c532020-12-02 14:12:41 -08005565 }
5566 }
James Mattis8f036802021-06-20 16:26:01 -07005567 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005568 if (mDefaultNetworkRequests.remove(nri)) {
5569 // If this request was one of the defaults, then the UID rules need to be updated
5570 // WARNING : if the app(s) for which this network request is the default are doing
5571 // traffic, this will kill their connected sockets, even if an equivalent request
5572 // is going to be reinstated right away ; unconnected traffic will go on the default
5573 // until the new default is set, which will happen very soon.
5574 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5575 // remove ranges for those requests that won't have a replacement
5576 final NetworkAgentInfo satisfier = nri.getSatisfier();
5577 if (null != satisfier) {
5578 try {
paulhu0e79d952021-06-09 16:11:35 +08005579 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5580 satisfier.network.getNetId(),
5581 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005582 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005583 } catch (RemoteException e) {
5584 loge("Exception setting network preference default network", e);
5585 }
5586 }
5587 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005588
Junyu Lai00d92df2022-07-05 11:01:52 +08005589 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005590 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005591 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005592
5593 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005594 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005595 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005596 }
5597 }
5598
Chalard Jean0354d8c2021-01-12 10:58:56 +09005599 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5600 // needed for this offer.
5601 for (final NetworkOfferInfo noi : mNetworkOffers) {
5602 for (final NetworkRequest req : nri.mRequests) {
5603 if (req.isRequest() && noi.offer.neededFor(req)) {
5604 noi.offer.onNetworkUnneeded(req);
5605 }
5606 }
5607 }
James Mattisa076c532020-12-02 14:12:41 -08005608 }
5609
James Mattis3ce3d3c2021-02-09 18:18:28 -08005610 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5611 for (final NetworkRequestInfo nri : nris) {
5612 if (mDefaultRequest == nri) {
5613 // Make sure we never remove the default request.
5614 continue;
5615 }
5616 handleRemoveNetworkRequest(nri);
5617 }
5618 }
5619
James Mattisa076c532020-12-02 14:12:41 -08005620 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5621 // listens don't have a singular affected Network. Check all networks to see
5622 // if this listen request applies and remove it.
5623 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5624 nai.removeRequest(req.requestId);
5625 if (req.networkCapabilities.hasSignalStrength()
5626 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5627 updateSignalStrengthThresholds(nai, "RELEASE", req);
5628 }
5629 }
5630 }
5631
5632 /**
5633 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5634 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5635 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5636 */
5637 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5638 boolean wasKept = false;
5639 final NetworkAgentInfo nai = nri.getSatisfier();
5640 if (nai != null) {
5641 final int requestLegacyType = nri.getActiveRequest().legacyType;
5642 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5643 nai.removeRequest(nri.getActiveRequest().requestId);
5644 if (VDBG || DDBG) {
5645 log(" Removing from current network " + nai.toShortString()
5646 + ", leaving " + nai.numNetworkRequests() + " requests.");
5647 }
5648 // If there are still lingered requests on this network, don't tear it down,
5649 // but resume lingering instead.
5650 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005651 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005652 notifyNetworkLosing(nai, now);
5653 }
5654 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5655 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5656 teardownUnneededNetwork(nai);
5657 } else {
5658 wasKept = true;
5659 }
James Mattisa076c532020-12-02 14:12:41 -08005660 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5661 // Went from foreground to background.
5662 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005663 }
5664
Erik Kline0c04b742016-07-07 16:50:58 +09005665 // Maintain the illusion. When this request arrived, we might have pretended
5666 // that a network connected to serve it, even though the network was already
5667 // connected. Now that this request has gone away, we might have to pretend
5668 // that the network disconnected. LegacyTypeTracker will generate that
5669 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005670 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005671 boolean doRemove = true;
5672 if (wasKept) {
5673 // check if any of the remaining requests for this network are for the
5674 // same legacy type - if so, don't remove the nai
5675 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5676 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005677 if (otherRequest.legacyType == requestLegacyType
5678 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005679 if (DBG) log(" still have other legacy request - leaving");
5680 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005681 }
5682 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005683 }
5684
Erik Kline0c04b742016-07-07 16:50:58 +09005685 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005686 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005687 }
5688 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005689 }
5690 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005691
Junyu Lai00d92df2022-07-05 11:01:52 +08005692 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005693 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005694 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5695 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5696 }
5697
Lorenzo Colittid6459092016-07-04 12:55:44 +09005698 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005699 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005700 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005701 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005702 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005703 }
5704
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005705 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005706 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5707 enforceNetworkStackSettingsOrSetup();
5708 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5709 encodeBool(accept), encodeBool(always), network));
5710 }
5711
5712 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005713 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005714 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005715 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5716 }
5717
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005718 @Override
5719 public void setTestAllowBadWifiUntil(long timeMs) {
5720 enforceSettingsPermission();
5721 if (!Build.isDebuggable()) {
5722 throw new IllegalStateException("Does not support in non-debuggable build");
5723 }
5724
5725 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5726 throw new IllegalArgumentException("It should not exceed "
5727 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5728 }
5729
5730 mHandler.sendMessage(
5731 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5732 }
5733
chiachangwange0192a72023-02-06 13:25:01 +00005734 @Override
5735 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5736 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005737
5738 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5739 throw new IllegalArgumentException("Argument should not exceed "
5740 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5741 }
5742
5743 mHandler.sendMessage(
5744 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5745 }
5746
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005747 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5748 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5749 " accept=" + accept + " always=" + always);
5750
5751 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5752 if (nai == null) {
5753 // Nothing to do.
5754 return;
5755 }
5756
Chalard Jean254bd162022-08-25 13:04:51 +09005757 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005758 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005759 return;
5760 }
5761
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005762 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005763 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005764 }
5765
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005766 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5767 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005768 // If network becomes partial connectivity and user already accepted to use this
5769 // network, we should respect the user's option and don't need to popup the
5770 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005771 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005772 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005773 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005774 }
5775
5776 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005777 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005778 }
5779
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005780 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005781 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005782 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005783 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005784 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005785 }
5786
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005787 }
5788
lucaslin2240ef62019-03-12 13:08:03 +08005789 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5790 boolean always) {
5791 if (DBG) {
5792 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5793 + " always=" + always);
5794 }
5795
5796 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5797 if (nai == null) {
5798 // Nothing to do.
5799 return;
5800 }
5801
Chalard Jean254bd162022-08-25 13:04:51 +09005802 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005803 // The network validated while the dialog box was up. Take no action.
5804 return;
5805 }
5806
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005807 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5808 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005809 }
5810
5811 // TODO: Use the current design or save the user choice into IpMemoryStore.
5812 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005813 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005814 }
5815
5816 if (!accept) {
5817 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005818 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005819 // Tear down the network.
5820 teardownUnneededNetwork(nai);
5821 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005822 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5823 // result in a partial connectivity result which will be processed by
5824 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005825 //
5826 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5827 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005828 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005829 }
5830 }
5831
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005832 private void handleSetAvoidUnvalidated(Network network) {
5833 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005834 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005835 // Nothing to do. The network either disconnected or revalidated.
5836 return;
5837 }
Chalard Jean254bd162022-08-25 13:04:51 +09005838 if (0L == nai.getAvoidUnvalidated()) {
5839 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005840 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005841 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005842 }
5843 }
5844
Chalard Jean5fb43c72022-09-08 19:03:14 +09005845 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005846 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005847 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005848 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005849 }
5850
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005851 @Override
5852 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005853 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005854 mHandler.post(() -> {
5855 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5856 if (nai == null) return;
5857 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005858 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005859 });
5860 }
5861
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005862 /**
5863 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5864 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005865 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005866 * @param appExtras Bundle to use as intent extras for the captive portal application.
5867 * Must be treated as opaque to avoid preventing the captive portal app to
5868 * update its arguments.
5869 */
5870 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005871 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005872 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5873 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005874
5875 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5876 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005877 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5878 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005879 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5880
lucaslin75ff7022020-12-17 04:14:35 +08005881 final long token = Binder.clearCallingIdentity();
5882 try {
5883 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5884 } finally {
5885 Binder.restoreCallingIdentity(token);
5886 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005887 }
5888
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005889 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5890 private final Network mNetwork;
5891
5892 private CaptivePortalImpl(Network network) {
5893 mNetwork = network;
5894 }
5895
5896 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005897 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005898 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5899 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005900 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5901 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5902 // Since the network will be disconnected, skip notifying NetworkMonitor
5903 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005904 }
5905
Chiachang Wang938bfba2020-01-09 13:50:55 +08005906 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005907 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005908 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005909 }
5910
5911 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005912 public void appRequest(final int request) {
5913 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5914 if (nm == null) return;
5915
5916 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005917 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005918 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005919 }
5920 }
5921
5922 @Nullable
5923 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5924 // getNetworkAgentInfoForNetwork is thread-safe
5925 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5926 if (nai == null) return null;
5927
5928 // nai.networkMonitor() is thread-safe
5929 return nai.networkMonitor();
5930 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005931 }
5932
Hugo Benichic9048bc2016-09-14 23:23:08 +00005933 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005934 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005935 }
5936
Chalard Jean020b93a2022-09-01 13:20:14 +09005937 private boolean activelyPreferBadWifi() {
5938 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5939 }
5940
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005941 /**
5942 * Return whether the device should maintain continuous, working connectivity by switching away
5943 * from WiFi networks having no connectivity.
5944 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5945 */
5946 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005947 if (!checkNetworkStackPermission()) {
5948 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5949 }
5950 return avoidBadWifi();
5951 }
5952
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005953 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005954 ensureRunningOnConnectivityServiceThread();
5955 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005956 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005957 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005958 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005959 if (avoidBadWifi) {
5960 // If the device is now avoiding bad wifi, remove notifications that might have
5961 // been put up when the device didn't.
5962 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5963 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005964 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005965 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5966 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5967 for (final NetworkOfferInfo noi : offersToUpdate) {
5968 updateOfferScore(noi.offer);
5969 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005970 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005971 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005972 }
5973
Erik Kline95ecfee2016-10-02 18:02:14 +09005974 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005975 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005976 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005977 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005978 if (!configRestrict) {
5979 pw.println("Bad Wi-Fi avoidance: unrestricted");
5980 return;
5981 }
5982
5983 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5984 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005985 pw.println("Config restrict: " + configRestrict);
5986 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005987
Chalard Jeane0fdea32022-09-14 21:44:22 +09005988 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005989 String description;
5990 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005991 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005992 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005993 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005994 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005995 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005996 description = "avoid";
5997 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005998 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005999 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09006000 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00006001
6002 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
6003 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09006004 if (null == configValue) {
6005 description = "unset";
6006 } else if (configValue) {
6007 description = "force true";
6008 } else {
6009 description = "force false";
6010 }
6011 pw.println("Actively prefer bad wifi conf: " + description);
6012 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006013 pw.println("Network overrides:");
6014 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09006015 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09006016 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09006017 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006018 }
6019 }
6020 pw.decreaseIndent();
6021 pw.decreaseIndent();
6022 }
6023
paulhu7746e4e2020-06-09 19:07:03 +08006024 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
6025 // unify the method.
6026 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
6027 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
6028 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
6029 return settingsComponent != null
6030 ? settingsComponent.getPackageName() : "com.android.settings";
6031 }
6032
lucaslinb1e8e382019-01-24 15:55:30 +08006033 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006034 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006035 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006036 switch (type) {
6037 case NO_INTERNET:
6038 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006039 // High priority because it is only displayed for explicitly selected networks.
6040 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006041 break;
lucasline117e2e2019-10-22 18:27:33 +08006042 case PRIVATE_DNS_BROKEN:
6043 action = Settings.ACTION_WIRELESS_SETTINGS;
6044 // High priority because we should let user know why there is no internet.
6045 highPriority = true;
6046 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006047 case LOST_INTERNET:
6048 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006049 // High priority because it could help the user avoid unexpected data usage.
6050 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006051 break;
lucaslin2240ef62019-03-12 13:08:03 +08006052 case PARTIAL_CONNECTIVITY:
6053 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006054 // Don't bother the user with a high-priority notification if the network was not
6055 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006056 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006057 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006058 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006059 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006060 return;
6061 }
6062
6063 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006064 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006065 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006066 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006067 // Some OEMs have their own Settings package. Thus, need to get the current using
6068 // Settings package name instead of just use default name "com.android.settings".
6069 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6070 intent.setClassName(settingsPkgName,
6071 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006072 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006073
paulhu2af50222020-10-11 22:52:27 +08006074 PendingIntent pendingIntent = PendingIntent.getActivity(
6075 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006076 0 /* requestCode */,
6077 intent,
paulhu2af50222020-10-11 22:52:27 +08006078 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006079
Serik Beketayevec8ad212020-12-07 22:43:07 -08006080 mNotifier.showNotification(
6081 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006082 }
6083
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006084 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6085 // Don't prompt if the network is validated, and don't prompt on captive portals
6086 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006087 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006088 return false;
6089 }
6090
6091 // If a network has partial connectivity, always prompt unless the user has already accepted
6092 // partial connectivity and selected don't ask again. This ensures that if the device
6093 // automatically connects to a network that has partial Internet access, the user will
6094 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006095 // because we have prompted them.
6096 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006097 return true;
6098 }
6099
6100 // If a network has no Internet access, only prompt if the network was explicitly selected
6101 // and if the user has not already told us to use the network regardless of whether it
6102 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006103 if (nai.networkAgentConfig.explicitlySelected
6104 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006105 return true;
6106 }
6107
6108 return false;
6109 }
6110
Chalard Jean5fb43c72022-09-08 19:03:14 +09006111 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6112 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006113
Chalard Jean5fb43c72022-09-08 19:03:14 +09006114 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6115 if (null == nai) return;
6116
6117 if (nai.setEvaluated()) {
6118 // If setEvaluated() returned true, the network never had any form of connectivity.
6119 // This may have an impact on request matching if bad WiFi avoidance is off and the
6120 // network was found not to have Internet access.
6121 nai.updateScoreForNetworkAgentUpdate();
6122 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006123
6124 // Also, if this is WiFi and it should be preferred actively, now is the time to
6125 // prompt the user that they walked past and connected to a bad WiFi.
6126 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6127 && !avoidBadWifi()
6128 && activelyPreferBadWifi()) {
6129 // The notification will be removed if the network validates or disconnects.
6130 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6131 return;
6132 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006133 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006134
Chalard Jean5fb43c72022-09-08 19:03:14 +09006135 if (!shouldPromptUnvalidated(nai)) return;
6136
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006137 // Stop automatically reconnecting to this network in the future. Automatically connecting
6138 // to a network that provides no or limited connectivity is not useful, because the user
6139 // cannot use that network except through the notification shown by this method, and the
6140 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006141 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006142
Chalard Jean254bd162022-08-25 13:04:51 +09006143 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006144 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006145 } else {
6146 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6147 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006148 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006149
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006150 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6151 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006152 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006153
lucaslin2240ef62019-03-12 13:08:03 +08006154 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6155 return;
6156 }
6157
6158 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006159 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006160 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006161 }
6162
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006163 @Override
6164 public int getMultipathPreference(Network network) {
6165 enforceAccessPermission();
6166
6167 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006168 if (nai != null && nai.networkCapabilities
6169 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006170 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6171 }
6172
Aaron Huang9a57acf2020-12-08 10:03:29 +08006173 final NetworkPolicyManager netPolicyManager =
6174 mContext.getSystemService(NetworkPolicyManager.class);
6175
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006176 final long token = Binder.clearCallingIdentity();
6177 final int networkPreference;
6178 try {
6179 networkPreference = netPolicyManager.getMultipathPreference(network);
6180 } finally {
6181 Binder.restoreCallingIdentity(token);
6182 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006183 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006184 return networkPreference;
6185 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006186 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6187 }
6188
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006189 @Override
6190 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006191 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006192 }
6193
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006194 private class InternalHandler extends Handler {
6195 public InternalHandler(Looper looper) {
6196 super(looper);
6197 }
6198
6199 @Override
6200 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006201 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006202 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006203 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006204 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006205 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006206 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006207 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006208 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006209 break;
6210 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006211 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006212 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006213 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006214 break;
6215 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006216 case EVENT_REGISTER_NETWORK_PROVIDER: {
6217 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006218 break;
6219 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006220 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6221 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006222 break;
6223 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006224 case EVENT_REGISTER_NETWORK_OFFER: {
6225 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6226 break;
6227 }
6228 case EVENT_UNREGISTER_NETWORK_OFFER: {
6229 final NetworkOfferInfo offer =
6230 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6231 if (null != offer) {
6232 handleUnregisterNetworkOffer(offer);
6233 }
6234 break;
6235 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006236 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006237 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6238 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6239 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006240 break;
6241 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006242 case EVENT_REGISTER_NETWORK_REQUEST:
6243 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006244 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006245 break;
6246 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006247 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6248 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006249 handleRegisterNetworkRequestWithIntent(msg);
6250 break;
6251 }
Erik Kline155a59a2015-11-25 12:49:38 +09006252 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6253 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6254 handleTimedOutNetworkRequest(nri);
6255 break;
6256 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006257 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6258 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6259 break;
6260 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006261 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006262 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6263 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006264 break;
6265 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006266 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006267 Network network = (Network) msg.obj;
6268 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006269 break;
6270 }
lucaslin2240ef62019-03-12 13:08:03 +08006271 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6272 Network network = (Network) msg.obj;
6273 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6274 toBool(msg.arg2));
6275 break;
6276 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006277 case EVENT_SET_AVOID_UNVALIDATED: {
6278 handleSetAvoidUnvalidated((Network) msg.obj);
6279 break;
6280 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006281 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6282 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006283 break;
6284 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006285 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6286 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006287 break;
6288 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006289 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6290 // handler thread.
6291 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006292 mKeepaliveTracker.handleStartKeepalive(msg);
6293 break;
6294 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006295 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006296 final AutomaticOnOffKeepalive ki =
6297 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6298 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006299
chiachangwang676c84e2023-02-14 09:22:05 +00006300 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006301 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006302 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006303 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006304 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6305 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006306 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6307 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006308 }
6309 }
6310
6311 // If the network no longer exists, then the keepalive should have been
6312 // cleaned up already. There is no point trying to resume keepalives.
6313 if (!networkFound) return;
6314
chiachangwang676c84e2023-02-14 09:22:05 +00006315 if (underpinnedNetworkFound) {
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006316 final NetworkCapabilities underpinnedNc =
6317 getNetworkCapabilitiesInternal(underpinnedNetwork);
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006318 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006319 underpinnedNetwork.netId, underpinnedNc.getUids());
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006320 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006321 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006322 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006323 }
6324 break;
6325 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006326 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006327 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006328 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6329 (IBinder) msg.obj);
6330 if (ki == null) {
6331 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006332 return;
6333 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006334 final int reason = msg.arg2;
6335 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006336 break;
6337 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006338 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6339 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6340 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006341 break;
6342 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006343 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6344 handlePrivateDnsSettingsChanged();
6345 break;
dalyk1720e542018-03-05 12:42:22 -05006346 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6347 handlePrivateDnsValidationUpdate(
6348 (PrivateDnsValidationUpdate) msg.obj);
6349 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006350 case EVENT_UID_BLOCKED_REASON_CHANGED:
6351 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006352 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006353 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6354 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6355 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006356 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006357 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6358 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006359 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006360 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006361 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006362 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006363 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6364 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006365 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006366 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006367 }
lucaslin1193a5d2021-01-21 02:04:15 +08006368 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006369 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006370 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006371 break;
paulhu51f77dc2021-06-07 02:34:20 +00006372 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6373 handleMobileDataPreferredUidsChanged();
6374 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006375 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6376 final long timeMs = ((Long) msg.obj).longValue();
6377 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6378 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006379 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6380 handleIngressRateLimitChanged();
6381 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006382 case EVENT_USER_DOES_NOT_WANT:
6383 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6384 if (nai == null) break;
6385 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006386 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006387 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006388 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6389 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6390 break;
chiachangwange0192a72023-02-06 13:25:01 +00006391 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6392 final long time = ((Long) msg.obj).longValue();
6393 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6394 break;
6395 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006396 case EVENT_UID_FROZEN_STATE_CHANGED:
6397 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6398 handleFrozenUids(args.mUids, args.mFrozenStates);
6399 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006400 }
6401 }
6402 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006403
Lorenzo Colittid6459092016-07-04 12:55:44 +09006404 @Override
markchien5776f962019-12-16 20:15:20 +08006405 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006406 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006407 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006408 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6409 Context.TETHERING_SERVICE);
6410 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006411 }
6412
Lorenzo Colittid6459092016-07-04 12:55:44 +09006413 @Override
markchien5776f962019-12-16 20:15:20 +08006414 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006415 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006416 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006417 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6418 Context.TETHERING_SERVICE);
6419 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006420 }
6421
Lorenzo Colittid6459092016-07-04 12:55:44 +09006422 @Override
markchien5776f962019-12-16 20:15:20 +08006423 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006424 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006425 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006426 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6427 Context.TETHERING_SERVICE);
6428 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006429 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006430
markchien5776f962019-12-16 20:15:20 +08006431
Lorenzo Colittid6459092016-07-04 12:55:44 +09006432 @Override
markchien5776f962019-12-16 20:15:20 +08006433 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006434 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006435 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006436 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6437 Context.TETHERING_SERVICE);
6438
6439 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006440 }
6441
Lorenzo Colittid6459092016-07-04 12:55:44 +09006442 @Override
markchien5776f962019-12-16 20:15:20 +08006443 @Deprecated
6444 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006445 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006446 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6447 Context.TETHERING_SERVICE);
6448
6449 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006450 }
6451
Udam Saini8f7d6a72017-06-07 12:06:28 -07006452 @Override
markchien5776f962019-12-16 20:15:20 +08006453 @Deprecated
6454 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006455 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006456 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6457 Context.TETHERING_SERVICE);
6458 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006459 }
6460
Robert Greenwalte0b00512014-07-02 09:59:16 -07006461 // Called when we lose the default network and have no replacement yet.
6462 // This will automatically be cleared after X seconds or a new default network
6463 // becomes CONNECTED, whichever happens first. The timer is started by the
6464 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006465 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006466 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006467 if (mNetTransitionWakeLock.isHeld()) {
6468 return;
6469 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006470 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006471 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6472 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006473 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006474 mWakelockLogs.log("ACQUIRE for " + forWhom);
6475 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006476 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006477 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006478 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006479 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006480
Hugo Benichi471b62a2017-03-30 23:18:10 +09006481 // Called when we gain a new default network to release the network transition wakelock in a
6482 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6483 // message is cancelled.
6484 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006485 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006486 if (!mNetTransitionWakeLock.isHeld()) {
6487 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006488 }
6489 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006490 // Cancel self timeout on wakelock hold.
6491 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6492 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6493 mHandler.sendMessageDelayed(msg, 1000);
6494 }
6495
6496 // Called when either message of ensureNetworkTransitionWakelock or
6497 // scheduleReleaseNetworkTransitionWakelock is processed.
6498 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6499 String event = eventName(eventId);
6500 synchronized (this) {
6501 if (!mNetTransitionWakeLock.isHeld()) {
6502 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006503 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006504 return;
6505 }
6506 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006507 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6508 mTotalWakelockDurationMs += lockDuration;
6509 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6510 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006511 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006512 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006513 }
6514
Robert Greenwalt986c7412010-09-08 15:24:47 -07006515 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006516 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006517 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006518 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006519 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006520 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006521 }
6522
Lorenzo Colittid6459092016-07-04 12:55:44 +09006523 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006524 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006525 enforceAccessPermission();
6526 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006527 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006528 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006529
6530 final NetworkAgentInfo nai;
6531 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006532 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006533 } else {
6534 nai = getNetworkAgentInfoForNetwork(network);
6535 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006536
6537 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006538 mHandler.obtainMessage(
6539 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006540 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006541
Hugo Benichid6b510a2017-04-06 17:22:18 +09006542 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006543 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006544 if (nai == null
6545 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006546 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006547 return;
6548 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006549 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006550 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006551 mConnectivityDiagnosticsHandler.sendMessage(
6552 mConnectivityDiagnosticsHandler.obtainMessage(
6553 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6554 new ReportedNetworkConnectivityInfo(
6555 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006556 return;
6557 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006558 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006559 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006560 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006561 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006562 // Validating a network that has not yet connected could result in a call to
6563 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006564 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006565 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006566 }
paulhu7aeba372020-12-30 00:42:19 +08006567 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6568 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006569 return;
6570 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006571
6572 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6573 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6574 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6575 // completed.
6576 mConnectivityDiagnosticsHandler.sendMessage(
6577 mConnectivityDiagnosticsHandler.obtainMessage(
6578 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6579 new ReportedNetworkConnectivityInfo(
6580 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006581 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006582 }
6583
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006584 // TODO: call into netd.
6585 private boolean queryUserAccess(int uid, Network network) {
6586 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6587 if (nai == null) return false;
6588
6589 // Any UID can use its default network.
6590 if (nai == getDefaultNetworkForUid(uid)) return true;
6591
6592 // Privileged apps can use any network.
6593 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6594 return true;
6595 }
6596
6597 // An unprivileged UID can use a VPN iff the VPN applies to it.
6598 if (nai.isVPN()) {
6599 return nai.networkCapabilities.appliesToUid(uid);
6600 }
6601
6602 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6603 // sockets, i.e., if it is the owner.
6604 final NetworkAgentInfo vpn = getVpnForUid(uid);
6605 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6606 && uid != vpn.networkCapabilities.getOwnerUid()) {
6607 return false;
6608 }
6609
6610 // The UID's permission must be at least sufficient for the network. Since the restricted
6611 // permission was already checked above, that just leaves background networks.
6612 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6613 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6614 }
6615
6616 // Unrestricted network. Anyone gets to use it.
6617 return true;
6618 }
6619
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006620 /**
6621 * Returns information about the proxy a certain network is using. If given a null network, it
6622 * it will return the proxy for the bound network for the caller app or the default proxy if
6623 * none.
6624 *
6625 * @param network the network we want to get the proxy information for.
6626 * @return Proxy information if a network has a proxy configured, or otherwise null.
6627 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006628 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006629 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006630 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006631 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006632 if (network == null) {
6633 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006634 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006635 true);
6636 if (activeNetwork == null) {
6637 return null;
6638 }
6639 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006640 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006641 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6642 // caller may not have.
6643 return getLinkPropertiesProxyInfo(network);
6644 }
6645 // No proxy info available if the calling UID does not have network access.
6646 return null;
6647 }
6648
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006649
6650 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006651 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6652 if (nai == null) return null;
6653 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006654 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6655 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006656 }
6657 }
6658
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006659 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006660 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006661 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006662 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006663 }
6664
Chalard Jean777e2e52018-06-07 18:02:37 +09006665 @Override
6666 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006667 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006668 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006669 }
6670
Aaron Huang9fe47be2021-06-08 13:11:45 +08006671 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006672 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006673 final NetworkAgentInfo nai = getDefaultNetwork();
6674 // TODO : this method should check that net == nai.network, unfortunately at this point
6675 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6676 // is only ever installed on the default network so in practice this is okay.
6677 if (null == nai) return;
6678 // PAC proxies only work on the default network. Therefore, only the default network
6679 // should have its link properties fixed up for PAC proxies.
6680 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6681 if (nai.everConnected()) {
6682 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6683 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006684 }
6685
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006686 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6687 // when any network changes proxy.
6688 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6689 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006690 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6691 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006692 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6693
Chalard Jean7d97afc2018-06-07 17:41:29 +09006694 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006695 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006696 }
6697 }
6698
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006699 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006700 final private HashMap<Uri, Integer> mUriEventMap;
6701 final private Context mContext;
6702 final private Handler mHandler;
6703
6704 SettingsObserver(Context context, Handler handler) {
6705 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006706 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006707 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006708 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006709 }
6710
Erik Kline05f2b402015-04-30 12:58:40 +09006711 void observe(Uri uri, int what) {
6712 mUriEventMap.put(uri, what);
6713 final ContentResolver resolver = mContext.getContentResolver();
6714 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006715 }
6716
6717 @Override
6718 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006719 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006720 }
6721
6722 @Override
6723 public void onChange(boolean selfChange, Uri uri) {
6724 final Integer what = mUriEventMap.get(uri);
6725 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006726 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006727 } else {
6728 loge("No matching event to send for URI=" + uri);
6729 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006730 }
6731 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006732
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006733 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006734 Log.d(TAG, s);
6735 }
6736
6737 private static void logw(String s) {
6738 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006739 }
6740
Daniel Brightf9e945b2020-06-15 16:10:01 -07006741 private static void logwtf(String s) {
6742 Log.wtf(TAG, s);
6743 }
6744
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006745 private static void logwtf(String s, Throwable t) {
6746 Log.wtf(TAG, s, t);
6747 }
6748
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006749 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006750 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006751 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006752
Hugo Benichi39621362017-02-11 17:04:43 +09006753 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006754 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006755 }
6756
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006757 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006758 * Return the information of all ongoing VPNs.
6759 *
6760 * <p>This method is used to update NetworkStatsService.
6761 *
6762 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006763 */
junyulai2050bed2021-01-23 09:46:34 +08006764 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006765 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006766 if (mLockdownEnabled) {
6767 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006768 }
junyulai2050bed2021-01-23 09:46:34 +08006769 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006770 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006771 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006772 if (info != null) {
6773 infoList.add(info);
6774 }
6775 }
junyulai2050bed2021-01-23 09:46:34 +08006776 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006777 }
6778
6779 /**
6780 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006781 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006782 */
junyulai2050bed2021-01-23 09:46:34 +08006783 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006784 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006785 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6786 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006787 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6788 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6789 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006790 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6791 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006792 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006793 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006794 }
6795 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006796
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006797 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006798
6799 List<String> interfaces = new ArrayList<>();
6800 for (Network network : underlyingNetworks) {
6801 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6802 if (underlyingNai == null) continue;
6803 LinkProperties lp = underlyingNai.linkProperties;
6804 for (String iface : lp.getAllInterfaceNames()) {
6805 if (!TextUtils.isEmpty(iface)) {
6806 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006807 }
6808 }
Benedict Wong34857f82019-06-12 17:46:15 +00006809 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006810
6811 if (interfaces.isEmpty()) return null;
6812
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006813 // Must be non-null or NetworkStatsService will crash.
6814 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6815 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006816 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006817 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006818
junyulai2050bed2021-01-23 09:46:34 +08006819 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6820 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006821 }
6822
James Mattisd31bdfa2020-12-23 16:37:26 -08006823 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006824 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6825 Network[] underlyingNetworks) {
6826 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006827 if (underlyingNetworks == null && defaultNetwork != null) {
6828 // null underlying networks means to track the default.
6829 underlyingNetworks = new Network[] { defaultNetwork };
6830 }
6831 return underlyingNetworks;
6832 }
6833
6834 // Returns true iff |network| is an underlying network of |nai|.
6835 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6836 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6837 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006838 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006839 final Network[] underlying = underlyingNetworksOrDefault(
6840 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006841 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006842 }
6843
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006844 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006845 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006846 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006847 * When underlying networks change, such networks may have to update capabilities to reflect
6848 * things like the metered bit, their transports, and so on. The capabilities are calculated
6849 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006850 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006851 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006852 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006853 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006854 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006855 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006856 }
6857 }
6858 }
6859
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006860 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6861 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6862 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6863 // a VPN is not up.
6864 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6865 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6866 for (UidRange range : blockedUidRanges) {
6867 if (range.contains(uid)) return true;
6868 }
6869 return false;
6870 }
6871
6872 @Override
6873 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006874 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006875 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6876 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6877 }
6878
6879 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6880 if (DBG) {
6881 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6882 + Arrays.toString(ranges));
6883 }
6884 // Cannot use a Set since the list of UID ranges might contain duplicates.
6885 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6886 for (int i = 0; i < ranges.length; i++) {
6887 if (requireVpn) {
6888 newVpnBlockedUidRanges.add(ranges[i]);
6889 } else {
6890 newVpnBlockedUidRanges.remove(ranges[i]);
6891 }
6892 }
6893
6894 try {
6895 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6896 } catch (RemoteException | ServiceSpecificException e) {
6897 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6898 + Arrays.toString(ranges) + "): netd command failed: " + e);
6899 }
6900
Chalard Jeandf29a852023-05-29 17:02:43 +09006901 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006902 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6903 }
6904
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006905 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6906 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006907 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6908 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006909 }
6910
6911 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6912 }
6913
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006914 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006915 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006916 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006917 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006918 }
6919
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006920 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6921 return mLockdownEnabled
6922 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6923 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006924 }
6925
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006926 private NetworkAgentInfo getLegacyLockdownNai() {
6927 if (!mLockdownEnabled) {
6928 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006929 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006930 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006931 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6932 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006933
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006934 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006935 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6936 // a local variable. There is no need to make a copy because its contents cannot change.
6937 final Network[] underlying = nai.declaredUnderlyingNetworks;
6938 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006939 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006940 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006941
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006942 // The legacy lockdown VPN always uses the default network.
6943 // If the VPN's underlying network is no longer the current default network, it means that
6944 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006945 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6946 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006947 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006948 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006949 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006950 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006951
6952 return nai;
6953 };
6954
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006955 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6956 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6957 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006958 private DetailedState getLegacyLockdownState(DetailedState origState) {
6959 if (origState != DetailedState.CONNECTED) {
6960 return origState;
6961 }
6962 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6963 ? DetailedState.CONNECTING
6964 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006965 }
6966
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006967 private void filterForLegacyLockdown(NetworkInfo ni) {
6968 if (!mLockdownEnabled || !ni.isConnected()) return;
6969 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6970 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6971 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6972 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6973 // network, this time with a state of CONNECTED.
6974 //
6975 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6976 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6977 // is not too far off the truth, since an always-on VPN, when not connected, is always
6978 // trying to reconnect.
6979 if (getLegacyLockdownNai() == null) {
6980 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6981 }
6982 }
6983
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006984 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006985 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006986 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006987 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006988 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6989 return;
6990 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006991 final long ident = Binder.clearCallingIdentity();
6992 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006993 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006994 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006995 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006996 } finally {
6997 Binder.restoreCallingIdentity(ident);
6998 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006999 }
Wink Savillecb117d32013-08-29 14:57:08 -07007000
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007001 @Override
7002 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01007003 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007004 final long ident = Binder.clearCallingIdentity();
7005 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007006 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09007007 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007008 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
7009 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08007010 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007011 } finally {
7012 Binder.restoreCallingIdentity(ident);
7013 }
7014 }
7015
James Mattis02220e22021-03-13 19:27:21 -08007016 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08007017 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7018 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7019 }
Chalard Jeane0abd522023-01-23 16:47:43 +09007020 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007021 }
7022
James Mattis02220e22021-03-13 19:27:21 -08007023 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09007024 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007025 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08007026 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
7027 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09007028 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08007029 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7030 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7031 }
junyulaid91e7052020-08-28 13:44:33 +08007032 }
7033
James Mattis02220e22021-03-13 19:27:21 -08007034 private void onPackageChanged(@NonNull final String packageName) {
7035 // This is necessary in case a package is added or removed, but also when it's replaced to
7036 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
7037 // as one in the preferences, then it should follow the same routing as that other package,
7038 // which means updating the rules is never to be needed in this case (whether it joins or
7039 // leaves a UID with a preference).
7040 if (isMappedInOemNetworkPreference(packageName)) {
7041 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7042 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007043
7044 // Invalidates cache entry when the package is updated.
7045 synchronized (mSelfCertifiedCapabilityCache) {
7046 mSelfCertifiedCapabilityCache.remove(packageName);
7047 }
James Mattis02220e22021-03-13 19:27:21 -08007048 }
7049
7050 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007051 @Override
7052 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007053 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007054 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007055 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007056
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007057 // User should be filled for below intents, check the existence.
7058 if (user == null) {
7059 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7060 return;
7061 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007062
Lorenzo Colitticd675292021-02-04 17:32:07 +09007063 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007064 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007065 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007066 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007067 } else {
junyulaid91e7052020-08-28 13:44:33 +08007068 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007069 }
7070 }
7071 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007072
James Mattis02220e22021-03-13 19:27:21 -08007073 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7074 @Override
7075 public void onReceive(Context context, Intent intent) {
7076 ensureRunningOnConnectivityServiceThread();
7077 switch (intent.getAction()) {
7078 case Intent.ACTION_PACKAGE_ADDED:
7079 case Intent.ACTION_PACKAGE_REMOVED:
7080 case Intent.ACTION_PACKAGE_REPLACED:
7081 onPackageChanged(intent.getData().getSchemeSpecificPart());
7082 break;
7083 default:
7084 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7085 }
7086 }
7087 };
7088
Junyu Lai38c75032023-12-04 07:52:19 +00007089 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
7090 private final BroadcastReceiver mDataSaverReceiver = new BroadcastReceiver() {
7091 @Override
7092 public void onReceive(Context context, Intent intent) {
7093 if (mDeps.isAtLeastV()) {
7094 throw new IllegalStateException(
7095 "data saver status should be updated from platform");
7096 }
7097 ensureRunningOnConnectivityServiceThread();
7098 switch (intent.getAction()) {
7099 case ACTION_RESTRICT_BACKGROUND_CHANGED:
7100 // If the uid is present in the deny list, the API will consistently
7101 // return ENABLED. To retrieve the global switch status, the system
7102 // uid is chosen because it will never be included in the deny list.
7103 final int dataSaverForSystemUid =
7104 mPolicyManager.getRestrictBackgroundStatus(Process.SYSTEM_UID);
7105 final boolean isDataSaverEnabled = (dataSaverForSystemUid
7106 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
7107 mBpfNetMaps.setDataSaverEnabled(isDataSaverEnabled);
7108 break;
7109 default:
7110 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7111 }
7112 }
7113 };
7114
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007115 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007116 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007117
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007118 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007119 public final String name;
7120 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007121 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007122 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007123
lifraf3a3492021-03-10 13:58:14 +08007124 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7125 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007126 this.name = name;
7127 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007128 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007129 mDeathRecipient = deathRecipient;
7130
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007131 if (mDeathRecipient == null) {
7132 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007133 }
7134 }
7135
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007136 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007137 try {
7138 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7139 } catch (RemoteException e) {
7140 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007141 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007142 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007143 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007144
James Mattis4fce5d12020-11-12 15:53:42 -08007145 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7146 for (int i = 0; i < requests.size(); i++) {
7147 ensureNetworkRequestHasType(requests.get(i));
7148 }
7149 }
7150
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007151 private void ensureNetworkRequestHasType(NetworkRequest request) {
7152 if (request.type == NetworkRequest.Type.NONE) {
7153 throw new IllegalArgumentException(
7154 "All NetworkRequests in ConnectivityService must have a type");
7155 }
7156 }
7157
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007158 /**
7159 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007160 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007161 */
James Mattis258ea3c2020-11-15 15:04:40 -08007162 @VisibleForTesting
7163 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007164 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7165 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007166 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007167
James Mattisa076c532020-12-02 14:12:41 -08007168 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7169 void setSatisfier(
7170 @Nullable final NetworkAgentInfo satisfier,
7171 @Nullable final NetworkRequest activeRequest) {
7172 mSatisfier = satisfier;
7173 mActiveRequest = activeRequest;
7174 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007175
James Mattisd31bdfa2020-12-23 16:37:26 -08007176 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007177 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007178 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007179 private NetworkAgentInfo mSatisfier;
7180 NetworkAgentInfo getSatisfier() {
7181 return mSatisfier;
7182 }
7183
7184 // The request in mRequests assigned to a network agent. This is null if none of the
7185 // requests in mRequests can be satisfied. This member has the constraint of only being
7186 // accessible on the handler thread.
7187 @Nullable
7188 private NetworkRequest mActiveRequest;
7189 NetworkRequest getActiveRequest() {
7190 return mActiveRequest;
7191 }
7192
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007193 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007194 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007195 @Nullable
7196 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007197
7198 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007199 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007200 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007201 final int mPid;
7202 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007203 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007204 @Nullable
7205 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007206
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007207 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007208 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007209
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007210 // Effective UID of this request. This is different from mUid when a privileged process
7211 // files a request on behalf of another UID. This UID is used to determine blocked status,
7212 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7213 // maximum limit of registered callbacks per UID.
7214 final int mAsUid;
7215
paulhu48291862021-07-14 14:53:57 +08007216 // Preference order of this request.
7217 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007218
James Mattis3ce3d3c2021-02-09 18:18:28 -08007219 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7220 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7221 // maintained for keying off of. This is only a concern when the original nri
7222 // mNetworkRequests changes which happens currently for apps that register callbacks to
7223 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7224 // that match the per-app default nri that currently tracks the calling app's uid so that
7225 // callbacks are fired at the appropriate time. When the callbacks fire,
7226 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7227 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7228 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7229 @NonNull
7230 private final NetworkRequest mNetworkRequestForCallback;
7231 NetworkRequest getNetworkRequestForCallback() {
7232 return mNetworkRequestForCallback;
7233 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007234
James Mattisd31bdfa2020-12-23 16:37:26 -08007235 /**
7236 * Get the list of UIDs this nri applies to.
7237 */
7238 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007239 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007240 // networkCapabilities.getUids() returns a defensive copy.
7241 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007242 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7243 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007244 }
7245
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007246 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7247 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007248 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007249 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007250 }
7251
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007252 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007253 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007254 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007255 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007256 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007257 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007258 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007259 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007260 mBinder = null;
7261 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007262 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007263 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007264 mPerUidCounter = getRequestCounter(this);
7265 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007266 /**
7267 * Location sensitive data not included in pending intent. Only included in
7268 * {@link NetworkCallback}.
7269 */
7270 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007271 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007272 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007273 }
7274
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007275 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007276 @Nullable final IBinder binder,
7277 @NetworkCallback.Flag int callbackFlags,
7278 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007279 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7280 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007281 }
7282
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007283 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007284 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007285 @Nullable final IBinder binder,
7286 @NetworkCallback.Flag int callbackFlags,
7287 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007288 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007289 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007290 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007291 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007292 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007293 mBinder = binder;
7294 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007295 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007296 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007297 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007298 mPerUidCounter = getRequestCounter(this);
7299 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007300 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007301 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007302 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007303 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007304 }
7305
James Mattis3ce3d3c2021-02-09 18:18:28 -08007306 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7307 @NonNull final List<NetworkRequest> r) {
7308 super();
7309 ensureAllNetworkRequestsHaveType(r);
7310 mRequests = initializeRequests(r);
7311 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007312 final NetworkAgentInfo satisfier = nri.getSatisfier();
7313 if (null != satisfier) {
7314 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7315 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007316 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007317 // As this code creates a new NRI with a new set of requests, figure out which of
7318 // the list of requests should be the active request. It is always the first
7319 // request of the list that can be satisfied by the satisfier since the order of
7320 // requests is a priority order.
7321 // Note even in the presence of a satisfier there may not be an active request,
7322 // when the satisfier is the no-service network.
7323 NetworkRequest activeRequest = null;
7324 for (final NetworkRequest candidate : r) {
7325 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7326 activeRequest = candidate;
7327 break;
7328 }
7329 }
7330 setSatisfier(satisfier, activeRequest);
7331 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007332 mMessenger = nri.mMessenger;
7333 mBinder = nri.mBinder;
7334 mPid = nri.mPid;
7335 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007336 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007337 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007338 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007339 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007340 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007341 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007342 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007343 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007344 }
7345
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007346 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007347 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007348 }
7349
paulhue9913722021-05-26 15:19:20 +08007350 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007351 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007352 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007353 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007354 }
7355
James Mattis2516da32021-01-31 17:06:19 -08007356 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7357 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7358 // false.
7359 boolean isBeingSatisfied() {
7360 return (null != mSatisfier && null != mActiveRequest);
7361 }
7362
James Mattis3d229892020-11-16 16:46:28 -08007363 boolean isMultilayerRequest() {
7364 return mRequests.size() > 1;
7365 }
7366
James Mattis45d81842021-01-10 14:24:24 -08007367 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7368 // Creating a defensive copy to prevent the sender from modifying the list being
7369 // reflected in the return value of this method.
7370 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007371 return Collections.unmodifiableList(tempRequests);
7372 }
7373
James Mattisb1392002021-03-31 13:57:52 -07007374 void linkDeathRecipient() {
7375 if (null != mBinder) {
7376 try {
7377 mBinder.linkToDeath(this, 0);
7378 } catch (RemoteException e) {
7379 binderDied();
7380 }
7381 }
7382 }
7383
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007384 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007385 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007386 try {
7387 mBinder.unlinkToDeath(this, 0);
7388 } catch (NoSuchElementException e) {
7389 // Temporary workaround for b/194394697 pending analysis of additional logs
7390 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7391 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007392 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007393 }
7394
paulhu48291862021-07-14 14:53:57 +08007395 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7396 // Compare two preference orders.
7397 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007398 }
7399
paulhu48291862021-07-14 14:53:57 +08007400 int getPreferenceOrderForNetd() {
7401 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7402 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7403 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007404 }
paulhu48291862021-07-14 14:53:57 +08007405 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007406 }
7407
James Mattis4fce5d12020-11-12 15:53:42 -08007408 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007409 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007410 // As an immutable collection, mRequests cannot change by the time the
7411 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7412 // is acceptable. Use handleReleaseNetworkRequest and not directly
7413 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7414 // the app already unregistered the request.
7415 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7416 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007417 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007418
James Mattis4fce5d12020-11-12 15:53:42 -08007419 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007420 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007421 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7422 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007423 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007424 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007425 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007426 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007427 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007428 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007429 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007430 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007431 }
7432
Junyu Lai00d92df2022-07-05 11:01:52 +08007433 // Keep backward compatibility since the ServiceSpecificException is used by
7434 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7435 public static class RequestInfoPerUidCounter extends PerUidCounter {
7436 RequestInfoPerUidCounter(int maxCountPerUid) {
7437 super(maxCountPerUid);
7438 }
7439
7440 @Override
7441 public synchronized void incrementCountOrThrow(int uid) {
7442 try {
7443 super.incrementCountOrThrow(uid);
7444 } catch (IllegalStateException e) {
7445 throw new ServiceSpecificException(
7446 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7447 "Uid " + uid + " exceeded its allotted requests limit");
7448 }
7449 }
7450
7451 @Override
7452 public synchronized void decrementCountOrThrow(int uid) {
7453 throw new UnsupportedOperationException("Use decrementCount instead.");
7454 }
7455
7456 public synchronized void decrementCount(int uid) {
7457 try {
7458 super.decrementCountOrThrow(uid);
7459 } catch (IllegalStateException e) {
7460 logwtf("Exception when decrement per uid request count: ", e);
7461 }
7462 }
7463 }
7464
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007465 // This checks that the passed capabilities either do not request a
7466 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007467 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007468 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007469 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007470 throw new SecurityException("Insufficient permissions to request a specific SSID");
7471 }
paulhu1a407652019-03-22 16:35:06 +08007472
7473 if (nc.hasSignalStrength()
7474 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7475 throw new SecurityException(
7476 "Insufficient permissions to request a specific signal strength");
7477 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007478 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007479
junyulai2217bec2021-04-14 23:33:31 +08007480 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007481 enforceNetworkFactoryPermission();
7482 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007483 }
7484
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007485 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007486 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007487 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007488 // mNetworkRequests may contain the same value multiple times in case of
7489 // multilayer requests. It won't matter in this case because the thresholds
7490 // will then be the same and be deduplicated as they enter the `thresholds` set.
7491 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007492 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7493 for (final NetworkRequest req : nri.mRequests) {
7494 if (req.networkCapabilities.hasSignalStrength()
7495 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7496 thresholds.add(req.networkCapabilities.getSignalStrength());
7497 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007498 }
7499 }
7500 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007501 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007502 }
7503
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007504 private void updateSignalStrengthThresholds(
7505 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007506 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007507
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007508 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007509 String detail;
7510 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7511 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7512 } else {
7513 detail = reason;
7514 }
7515 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007516 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007517 }
7518
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007519 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007520 }
7521
Chalard Jeandd421992021-12-16 23:16:02 +09007522 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007523 if (nc == null) {
7524 return;
7525 }
7526 NetworkSpecifier ns = nc.getNetworkSpecifier();
7527 if (ns == null) {
7528 return;
7529 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007530 if (ns instanceof MatchAllNetworkSpecifier) {
7531 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7532 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007533 }
7534
Chalard Jeandd421992021-12-16 23:16:02 +09007535 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007536 ensureValidNetworkSpecifier(nc);
7537 if (nc.isPrivateDnsBroken()) {
7538 throw new IllegalArgumentException("Can't request broken private DNS");
7539 }
Chalard Jeande665262022-02-25 16:12:12 +09007540 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007541 throw new IllegalArgumentException("Can't request access UIDs");
7542 }
lucasline117e2e2019-10-22 18:27:33 +08007543 }
7544
Chalard Jeandd421992021-12-16 23:16:02 +09007545 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7546 ensureListenableCapabilities(nc);
7547 final String badCapability = nc.describeFirstNonRequestableCapability();
7548 if (badCapability != null) {
7549 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7550 }
7551 }
7552
Chiachang Wang3bc52762021-11-25 14:17:57 +08007553 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7554 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007555 private boolean isTargetSdkAtleast(int version, int callingUid,
7556 @NonNull String callingPackageName) {
7557 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007558 final PackageManager pm =
7559 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007560 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007561 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007562 if (callingVersion < version) return false;
7563 } catch (PackageManager.NameNotFoundException e) { }
7564 return true;
7565 }
7566
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007567 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007568 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007569 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007570 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007571 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007572 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007573 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7574 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007575 throw new SecurityException("Insufficient permissions to specify legacy type");
7576 }
markchienfac84a22020-03-18 21:16:15 +08007577 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007578 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007579 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007580 // Privileged callers can track the default network of another UID by passing in a UID.
7581 if (asUid != Process.INVALID_UID) {
7582 enforceSettingsPermission();
7583 } else {
7584 asUid = callingUid;
7585 }
junyulaiad010792021-01-11 16:53:38 +08007586 final NetworkRequest.Type reqType;
7587 try {
7588 reqType = NetworkRequest.Type.values()[reqTypeInt];
7589 } catch (ArrayIndexOutOfBoundsException e) {
7590 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7591 }
7592 switch (reqType) {
7593 case TRACK_DEFAULT:
7594 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007595 // is unused and will be replaced by ones appropriate for the UID (usually, the
7596 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007597 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007598 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007599 enforceAccessPermission();
7600 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007601 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007602 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007603 networkCapabilities = new NetworkCapabilities(defaultNc);
7604 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007605 case BACKGROUND_REQUEST:
7606 enforceNetworkStackOrSettingsPermission();
7607 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007608 case REQUEST:
7609 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7610 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007611 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007612 // TODO: this is incorrect. We mark the request as metered or not depending on
7613 // the state of the app when the request is filed, but we never change the
7614 // request if the app changes network state. http://b/29964605
7615 enforceMeteredApnPolicy(networkCapabilities);
7616 break;
junyulai1b1c8742021-03-12 20:05:08 +08007617 case LISTEN_FOR_BEST:
7618 enforceAccessPermission();
7619 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7620 break;
junyulaiad010792021-01-11 16:53:38 +08007621 default:
7622 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007623 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007624 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007625 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007626 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007627
junyulai1b1c8742021-03-12 20:05:08 +08007628 // Enforce FOREGROUND if the caller does not have permission to use background network.
7629 if (reqType == LISTEN_FOR_BEST) {
7630 restrictBackgroundRequestForCaller(networkCapabilities);
7631 }
7632
7633 // Set the UID range for this request to the single UID of the requester, unless the
7634 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007635 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7636 // are no visible methods to set the UIDs, an app could use reflection to try and get
7637 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007638 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007639 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7640 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007641
Etan Cohen85000162017-02-05 10:42:27 -08007642 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007643 throw new IllegalArgumentException("Bad timeout specified");
7644 }
Etan Cohen9786d922015-11-18 10:56:15 -08007645
James Mattis3ce3d3c2021-02-09 18:18:28 -08007646 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007647 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007648 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007649 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007650 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007651 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007652
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007653 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7654 // copied from the default request above. (This is necessary to ensure, for example, that
7655 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7656 // changes don't alter request matching.
7657 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7658 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007659 throw new IllegalStateException(
7660 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007661 + networkCapabilities + " vs. " + defaultNc);
7662 }
7663
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007664 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007665 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007666 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007667 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007668 }
7669 return networkRequest;
7670 }
7671
James Mattis3ce3d3c2021-02-09 18:18:28 -08007672 /**
7673 * Return the nri to be used when registering a network request. Specifically, this is used with
7674 * requests registered to track the default request. If there is currently a per-app default
7675 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7676 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007677 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7678 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007679 * @param nr the network request for the nri.
7680 * @param msgr the messenger for the nri.
7681 * @param binder the binder for the nri.
7682 * @param callingAttributionTag the calling attribution tag for the nri.
7683 * @return the nri to register.
7684 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007685 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007686 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007687 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007688 @Nullable String callingAttributionTag) {
7689 final List<NetworkRequest> requests;
7690 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7691 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007692 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007693 } else {
7694 requests = Collections.singletonList(nr);
7695 }
Roshan Pius951c0032020-12-22 15:10:42 -08007696 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007697 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007698 }
7699
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007700 private boolean shouldCheckCapabilitiesDeclaration(
7701 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7702 @NonNull final String callingPackageName) {
7703 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7704 // Only run the check if the change is enabled.
7705 if (!mDeps.isChangeEnabled(
7706 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7707 callingPackageName, user)) {
7708 return false;
7709 }
7710
7711 return networkCapabilities.hasCapability(
7712 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7713 || networkCapabilities.hasCapability(
7714 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7715 }
7716
7717 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007718 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007719 // This check is added to fix the linter error for "current min is 30", which is not going
7720 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007721 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007722 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7723 return;
7724 }
7725 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007726 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007727 try {
7728 synchronized (mSelfCertifiedCapabilityCache) {
7729 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7730 callerPackageName);
7731 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007732 final PackageManager packageManager =
7733 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
7734 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007735 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7736 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7737 callerPackageName
7738 );
7739 final XmlResourceParser parser = packageManager
7740 .getResourcesForApplication(callerPackageName)
7741 .getXml(networkSliceProperty.getResourceId());
7742 applicationNetworkCapabilities =
7743 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7744 mSelfCertifiedCapabilityCache.put(callerPackageName,
7745 applicationNetworkCapabilities);
7746 }
7747
7748 }
7749 } catch (PackageManager.NameNotFoundException ne) {
7750 throw new SecurityException(
7751 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7752 + " property");
7753 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7754 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007755 } finally {
7756 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007757 }
7758
7759 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7760 networkCapabilities);
7761 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007762 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007763 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007764 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7765 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007766 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
7767 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007768 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007769 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007770 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7771 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7772 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7773 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007774 }
junyulai96bd9fe2022-03-08 17:36:42 +08007775 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007776 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007777 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007778 }
7779 }
7780
fenglu3f357402015-03-20 11:29:56 -07007781 @Override
fenglub00f4882015-04-21 17:12:05 -07007782 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007783 enforceAccessPermission();
7784 NetworkAgentInfo nai = null;
7785 if (network == null) {
7786 return false;
7787 }
7788 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007789 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007790 }
7791 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007792 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007793 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007794 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007795 Integer uidReqs = mBandwidthRequests.get(uid);
7796 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007797 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007798 }
7799 mBandwidthRequests.put(uid, ++uidReqs);
7800 }
fenglu3f357402015-03-20 11:29:56 -07007801 return true;
7802 }
7803 return false;
7804 }
7805
Felipe Leme0a5ae422016-06-20 16:36:29 -07007806 private boolean isSystem(int uid) {
7807 return uid < Process.FIRST_APPLICATION_UID;
7808 }
fenglu3f357402015-03-20 11:29:56 -07007809
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007810 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007811 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007812 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007813 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007814 return;
7815 }
Hugo Benichi39621362017-02-11 17:04:43 +09007816 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7817 // Policy already enforced.
7818 return;
7819 }
paulhuaf50d7d2020-12-24 19:47:34 +08007820 final long ident = Binder.clearCallingIdentity();
7821 try {
7822 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7823 // If UID is restricted, don't allow them to bring up metered APNs.
7824 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7825 }
7826 } finally {
7827 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007828 }
7829 }
7830
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007831 @Override
7832 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007833 PendingIntent operation, @NonNull String callingPackageName,
7834 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007835 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007836 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007837 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007838 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007839 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007840 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007841 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007842 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007843 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007844 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7845 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007846
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007847 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007848 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007849 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7850 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007851 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007852 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7853 nri));
7854 return networkRequest;
7855 }
7856
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007857 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7858 mHandler.sendMessageDelayed(
7859 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007860 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007861 }
7862
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007863 @Override
7864 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007865 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007866 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007867 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007868 }
7869
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007870 // In order to implement the compatibility measure for pre-M apps that call
7871 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7872 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7873 // This ensures it has permission to do so.
7874 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7875 if (nc == null) {
7876 return false;
7877 }
7878 int[] transportTypes = nc.getTransportTypes();
7879 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7880 return false;
7881 }
7882 try {
7883 mContext.enforceCallingOrSelfPermission(
7884 android.Manifest.permission.ACCESS_WIFI_STATE,
7885 "ConnectivityService");
7886 } catch (SecurityException e) {
7887 return false;
7888 }
7889 return true;
7890 }
7891
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007892 @Override
7893 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007894 Messenger messenger, IBinder binder,
7895 @NetworkCallback.Flag int callbackFlags,
7896 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007897 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007898 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7899 enforceAccessPermission();
7900 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007901
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007902 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007903 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007904 Binder.getCallingPid(), callingUid, callingPackageName);
7905 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007906 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7907 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7908 // onLost and onAvailable callbacks when networks move in and out of the background.
7909 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7910 // can't request networks.
7911 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007912 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007913
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007914 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007915 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007916 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007917 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007918 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007919 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007920
7921 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7922 return networkRequest;
7923 }
7924
7925 @Override
7926 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007927 PendingIntent operation, @NonNull String callingPackageName,
7928 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007929 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007930 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007931 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7932 enforceAccessPermission();
7933 }
Chalard Jeandd421992021-12-16 23:16:02 +09007934 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007935 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007936 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007937 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007938 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007939
7940 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007941 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007942 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7943 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007944 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007945
WeiZhang1cc3f172021-06-03 19:02:04 -05007946 mHandler.sendMessage(mHandler.obtainMessage(
7947 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007948 }
7949
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007950 /** Returns the next Network provider ID. */
7951 public final int nextNetworkProviderId() {
7952 return mNextNetworkProviderId.getAndIncrement();
7953 }
7954
Erik Kline0c04b742016-07-07 16:50:58 +09007955 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007956 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007957 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007958 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007959 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007960 }
7961
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007962 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7963 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007964 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7965 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7966 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007967 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007968 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007969 return;
7970 }
7971
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007972 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7973 mNetworkProviderInfos.put(npi.messenger, npi);
7974 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007975 }
7976
7977 @Override
7978 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007979 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007980 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007981 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007982 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007983 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7984 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007985 }
7986
7987 @Override
7988 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007989 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007990 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007991 }
7992
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007993 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007994 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007995 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7996 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007997 Objects.requireNonNull(score);
7998 Objects.requireNonNull(caps);
7999 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008000 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008001 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09008002 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
8003 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008004 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
8005 }
8006
Chalard Jeanbb902a52021-08-18 01:35:19 +09008007 private void updateOfferScore(final NetworkOffer offer) {
8008 final boolean yieldToBadWiFi =
8009 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
8010 final NetworkOffer newOffer = new NetworkOffer(
8011 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
8012 offer.caps, offer.callback, offer.providerId);
8013 if (offer.equals(newOffer)) return;
8014 handleRegisterNetworkOffer(newOffer);
8015 }
8016
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008017 @Override
8018 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08008019 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008020 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
8021 }
8022
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008023 private void handleUnregisterNetworkProvider(Messenger messenger) {
8024 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
8025 if (npi == null) {
8026 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008027 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008028 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008029 // Unregister all the offers from this provider
8030 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
8031 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09008032 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008033 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
8034 toRemove.add(noi);
8035 }
8036 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09008037 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008038 handleUnregisterNetworkOffer(noi);
8039 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008040 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07008041 }
8042
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008043 @Override
James Mattisf7027322020-12-13 16:28:14 -08008044 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008045 if (request.hasTransport(TRANSPORT_TEST)) {
8046 enforceNetworkFactoryOrTestNetworksPermission();
8047 } else {
8048 enforceNetworkFactoryPermission();
8049 }
James Mattisf7027322020-12-13 16:28:14 -08008050 final NetworkRequestInfo nri = mNetworkRequests.get(request);
8051 if (nri != null) {
8052 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
8053 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
8054 mHandler.post(() -> handleReleaseNetworkRequest(
8055 nri.mRequests.get(0), mDeps.getCallingUid(), true));
8056 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008057 }
8058
Paul Jensen1f567382015-02-13 14:18:39 -05008059 // NOTE: Accessed on multiple threads, must be synchronized on itself.
8060 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008061 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05008062 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008063 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05008064 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008065 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008066
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008067 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05008068 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008069 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008070
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008071 // UID ranges for users that are currently blocked by VPNs.
8072 // This array is accessed and iterated on multiple threads without holding locks, so its
8073 // contents must never be mutated. When the ranges change, the array is replaced with a new one
8074 // (on the handler thread).
8075 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
8076
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008077 // Must only be accessed on the handler thread
8078 @NonNull
8079 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8080
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008081 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008082 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008083
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008084 // Current OEM network preferences. This object must only be written to on the handler thread.
8085 // Since it is immutable and always non-null, other threads may read it if they only care
8086 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008087 @NonNull
8088 private OemNetworkPreferences mOemNetworkPreferences =
8089 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008090 // Current per-profile network preferences. This object follows the same threading rules as
8091 // the OEM network preferences above.
8092 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008093 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8094 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008095
lucaslin3ba7cc22022-12-19 02:35:33 +00008096 // Current VPN network preferences. This object follows the same threading rules as the OEM
8097 // network preferences above.
8098 @NonNull
8099 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8100 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8101
paulhu51f77dc2021-06-07 02:34:20 +00008102 // A set of UIDs that should use mobile data preferentially if available. This object follows
8103 // the same threading rules as the OEM network preferences above.
8104 @NonNull
8105 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8106
James Mattiscb1e0362021-04-06 17:07:42 -07008107 // OemNetworkPreferences activity String log entries.
8108 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8109 @NonNull
8110 private final LocalLog mOemNetworkPreferencesLogs =
8111 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8112
James Mattis02220e22021-03-13 19:27:21 -08008113 /**
8114 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8115 * @param packageName the package name to check existence of a mapping for.
8116 * @return true if a mapping exists, false otherwise
8117 */
8118 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8119 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8120 }
8121
James Mattise3ef1912020-12-20 11:09:58 -08008122 // The always-on request for an Internet-capable network that apps without a specific default
8123 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008124 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008125 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008126 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008127 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008128 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008129 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008130 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008131
James Mattisd31bdfa2020-12-23 16:37:26 -08008132 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8133 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8134 }
8135
8136 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008137 * Return the default network request currently tracking the given uid.
8138 * @param uid the uid to check.
8139 * @return the NetworkRequestInfo tracking the given uid.
8140 */
8141 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008142 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008143 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008144 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008145 // Checking the first request is sufficient as only multilayer requests will have more
8146 // than one request and for multilayer, all requests will track the same uids.
8147 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008148 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008149 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008150 highestPriorityNri = nri;
8151 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008152 }
8153 }
paulhuaa0743d2021-05-26 21:56:03 +08008154 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008155 }
8156
8157 /**
8158 * Get a copy of the network requests of the default request that is currently tracking the
8159 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008160 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8161 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008162 * @param requestorUid the uid to check the default for.
8163 * @param requestorPackageName the requestor's package name.
8164 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8165 */
8166 @NonNull
8167 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008168 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008169 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008170 getDefaultRequestTrackingUid(asUid).mRequests,
8171 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008172 }
8173
8174 /**
8175 * Copy the given nri's NetworkRequest collection.
8176 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008177 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8178 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008179 * @param requestorUid the uid to set on the copied collection.
8180 * @param requestorPackageName the package name to set on the copied collection.
8181 * @return the copied NetworkRequest collection.
8182 */
8183 @NonNull
8184 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008185 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8186 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008187 final List<NetworkRequest> requests = new ArrayList<>();
8188 for (final NetworkRequest nr : requestsToCopy) {
8189 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008190 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008191 nr.legacyType, nextNetworkRequestId(), nr.type));
8192 }
8193 return requests;
8194 }
8195
8196 @NonNull
8197 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008198 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8199 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008200 // These capabilities are for a TRACK_DEFAULT callback, so:
8201 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8202 // mDefaultRequest and a per-UID default request.
8203 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008204 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008205 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008206 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8207 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008208 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008209 restrictRequestUidsForCallerAndSetRequestorInfo(
8210 netCap, requestorUid, requestorPackageName);
8211 return netCap;
8212 }
8213
8214 /**
8215 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8216 * @param nr the network request to check for equality against.
8217 * @return the nri if one exists, null otherwise.
8218 */
8219 @Nullable
8220 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8221 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8222 if (nri.getNetworkRequestForCallback().equals(nr)) {
8223 return nri;
8224 }
8225 }
8226 return null;
8227 }
8228
8229 /**
8230 * Check if an nri is currently being managed by per-app default networking.
8231 * @param nri the nri to check.
8232 * @return true if this nri is currently being managed by per-app default networking.
8233 */
8234 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8235 // nri.mRequests.get(0) is only different from the original request filed in
8236 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8237 // functionality therefore if these two don't match, it means this particular nri is
8238 // currently being managed by a per-app default.
8239 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8240 }
8241
8242 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008243 * Determine if an nri is a managed default request that disallows default networking.
8244 * @param nri the request to evaluate
8245 * @return true if device-default networking is disallowed
8246 */
8247 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8248 // Check if this nri is a managed default that supports the default network at its
8249 // lowest priority request.
8250 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8251 final NetworkCapabilities lowestPriorityNetCap =
8252 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8253 return isPerAppDefaultRequest(nri)
8254 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8255 lowestPriorityNetCap));
8256 }
8257
Erik Kline05f2b402015-04-30 12:58:40 +09008258 // Request used to optionally keep mobile data active even when higher
8259 // priority networks like Wi-Fi are active.
8260 private final NetworkRequest mDefaultMobileDataRequest;
8261
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008262 // Request used to optionally keep wifi data active even when higher
8263 // priority networks like ethernet are active.
8264 private final NetworkRequest mDefaultWifiRequest;
8265
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008266 // Request used to optionally keep vehicle internal network always active
8267 private final NetworkRequest mDefaultVehicleRequest;
8268
James Mattisd31bdfa2020-12-23 16:37:26 -08008269 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8270 // network with no service. This NAI should never be matched against, nor should any public API
8271 // ever return the associated network. For this reason, this NAI is not in the list of available
8272 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8273 // default requests that don't support using the device default network which will ultimately
8274 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8275 @VisibleForTesting
8276 final NetworkAgentInfo mNoServiceNetwork;
8277
Chalard Jean5b409c72021-02-04 13:12:59 +09008278 // The NetworkAgentInfo currently satisfying the default request, if any.
8279 private NetworkAgentInfo getDefaultNetwork() {
8280 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008281 }
8282
James Mattis2516da32021-01-31 17:06:19 -08008283 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008284 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008285 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8286 // Currently, all network requests will have the same uids therefore checking the first
8287 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008288 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008289 if (null == uids) {
8290 continue;
8291 }
8292 for (final UidRange range : uids) {
8293 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008294 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008295 highestPriorityNri = nri;
8296 }
James Mattis2516da32021-01-31 17:06:19 -08008297 }
8298 }
8299 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008300 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008301 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008302 }
8303
Varun Ananddf569952019-02-06 10:13:38 -08008304 @Nullable
8305 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8306 return nai != null ? nai.network : null;
8307 }
8308
8309 private void ensureRunningOnConnectivityServiceThread() {
8310 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8311 throw new IllegalStateException(
8312 "Not running on ConnectivityService thread: "
8313 + Thread.currentThread().getName());
8314 }
8315 }
8316
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008317 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008318 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8319 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008320 }
8321
Chalard Jean29d06db2018-05-02 21:14:54 +09008322 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008323 * Returns whether local agents are supported on this device.
8324 *
8325 * Local agents are supported from U on TVs, and from V on all devices.
8326 */
8327 @VisibleForTesting
8328 public boolean areLocalAgentsSupported() {
8329 final PackageManager pm = mContext.getPackageManager();
8330 // Local agents are supported starting on U on TVs and on V on everything else.
8331 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8332 }
8333
8334 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008335 * Register a new agent with ConnectivityService to handle a network.
8336 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008337 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008338 * @param networkInfo the initial info associated with this network. It can be updated later :
8339 * see {@link #updateNetworkInfo}.
8340 * @param linkProperties the initial link properties of this network. They can be updated
8341 * later : see {@link #updateLinkProperties}.
8342 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008343 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008344 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008345 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008346 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008347 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008348 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008349 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008350 public Network registerNetworkAgent(INetworkAgent na,
8351 NetworkInfo networkInfo,
8352 LinkProperties linkProperties,
8353 NetworkCapabilities networkCapabilities,
8354 @NonNull NetworkScore initialScore,
8355 @Nullable LocalNetworkConfig localNetworkConfig,
8356 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008357 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008358 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8359 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8360 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008361 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008362 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008363 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008364 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008365 } else {
8366 enforceNetworkFactoryPermission();
8367 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008368 final boolean hasLocalCap =
8369 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8370 if (hasLocalCap && !areLocalAgentsSupported()) {
8371 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8372 throw new IllegalArgumentException("Local agents are not supported in this version");
8373 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008374 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8375 if (hasLocalCap != hasLocalNetworkConfig) {
8376 throw new IllegalArgumentException(null != localNetworkConfig
8377 ? "Only local network agents can have a LocalNetworkConfig"
8378 : "Local network agents must have a LocalNetworkConfig"
8379 );
8380 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008381
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008382 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008383 final long token = Binder.clearCallingIdentity();
8384 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008385 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008386 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8387 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008388 } finally {
8389 Binder.restoreCallingIdentity(token);
8390 }
8391 }
8392
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008393 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008394 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008395 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8396 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008397 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008398
Chalard Jeandbc46952022-02-02 00:14:18 +09008399 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8400 // and mutate them at any time.
8401 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8402 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8403 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008404 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008405
Chalard Jean366c5252022-01-25 18:27:53 +09008406 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008407 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008408 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8409 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008410 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008411 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008412 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8413 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8414 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008415
Chalard Jeandbc46952022-02-02 00:14:18 +09008416 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008417 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008418 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008419 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008420 mDeps.getNetworkStack().makeNetworkMonitor(
8421 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008422 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8423 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008424 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008425 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008426 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008427 }
8428
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008429 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008430 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008431 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008432 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008433 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008434 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8435 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8436 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008437
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008438 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008439
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008440 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008441 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008442 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008443 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008444
8445 try {
8446 networkMonitor.start();
8447 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008448 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008449 }
Chalard Jean366c5252022-01-25 18:27:53 +09008450
Chalard Jean1e4c2182023-10-06 18:45:53 +09008451 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008452 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008453 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008454 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008455 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008456 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008457 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008458 }
8459
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008460 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8461 @NonNull public final NetworkOffer offer;
8462
8463 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8464 this.offer = offer;
8465 }
8466
8467 @Override
8468 public void binderDied() {
8469 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8470 }
8471 }
8472
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008473 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8474 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8475 if (npi.providerId == providerId) return true;
8476 }
8477 return false;
8478 }
8479
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008480 /**
8481 * Register or update a network offer.
8482 * @param newOffer The new offer. If the callback member is the same as an existing
8483 * offer, it is an update of that offer.
8484 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008485 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008486 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8487 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008488 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008489 // This may actually happen if a provider updates its score or registers and then
8490 // immediately unregisters. The offer would still be in the handler queue, but the
8491 // provider would have been removed.
8492 if (DBG) log("Received offer from an unregistered provider");
8493 return;
8494 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008495 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8496 if (null != existingOffer) {
8497 handleUnregisterNetworkOffer(existingOffer);
8498 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008499 if (DBG) {
8500 // handleUnregisterNetworkOffer has already logged the old offer
8501 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8502 }
8503 } else {
8504 if (DBG) {
8505 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8506 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008507 }
8508 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8509 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008510 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008511 } catch (RemoteException e) {
8512 noi.binderDied();
8513 return;
8514 }
8515 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008516 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008517 }
8518
8519 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8520 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008521 if (DBG) {
8522 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8523 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008524
8525 // If the provider removes the offer and dies immediately afterwards this
8526 // function may be called twice in a row, but the array will no longer contain
8527 // the offer.
8528 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008529 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008530 }
8531
8532 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8533 @NonNull final INetworkOfferCallback callback) {
8534 ensureRunningOnConnectivityServiceThread();
8535 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008536 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008537 }
8538 return null;
8539 }
8540
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008541 /**
8542 * Called when receiving LinkProperties directly from a NetworkAgent.
8543 * Stores into |nai| any data coming from the agent that might also be written to the network's
8544 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8545 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008546 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008547 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008548 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8549 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008550 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008551 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008552 }
8553
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008554 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008555 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008556 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008557
Lorenzo Colittid523d142020-04-01 20:16:30 +09008558 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8559 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8560 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008561 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008562
Suprabh Shukla1e312032023-01-24 03:36:37 -08008563 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008564
8565 // update filtering rules, need to happen after the interface update so netd knows about the
8566 // new interface (the interface name -> index map becomes initialized)
8567 updateVpnFiltering(newLp, oldLp, networkAgent);
8568
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008569 updateMtu(newLp, oldLp);
8570 // TODO - figure out what to do for clat
8571// for (LinkProperties lp : newLp.getStackedLinks()) {
8572// updateMtu(lp, null);
8573// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008574 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008575 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008576 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8577 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008578
Erik Klineb9888902016-04-05 13:30:49 +09008579 updateRoutes(newLp, oldLp, netId);
8580 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008581 // Make sure LinkProperties represents the latest private DNS status.
8582 // This does not need to be done before updateDnses because the
8583 // LinkProperties are not the source of the private DNS configuration.
8584 // updateDnses will fetch the private DNS configuration from DnsManager.
8585 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008586
Chalard Jean5b409c72021-02-04 13:12:59 +09008587 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008588 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008589 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008590 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008591 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008592
8593 updateWakeOnLan(newLp);
8594
Hai Shalome58bdc62021-01-11 18:45:34 -08008595 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8596 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8597 // does, it needs to be merged here.
8598 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8599 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008600
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008601 // TODO - move this check to cover the whole function
8602 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008603 synchronized (networkAgent) {
8604 networkAgent.linkProperties = newLp;
8605 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008606 // Start or stop DNS64 detection and 464xlat according to network state.
8607 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008608 // Notify NSS when relevant events happened. Currently, NSS only cares about
8609 // interface changed to update clat interfaces accounting.
8610 final boolean interfacesChanged = oldLp == null
8611 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8612 if (interfacesChanged) {
8613 notifyIfacesChangedForNetworkStats();
8614 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008615 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8616 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008617 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008618 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008619
8620 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008621 }
8622
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008623 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8624 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8625 }
8626
Hai Shalome58bdc62021-01-11 18:45:34 -08008627 /**
8628 * @param naData captive portal data from NetworkAgent
8629 * @param apiData captive portal data from capport API
8630 */
8631 @Nullable
8632 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8633 CaptivePortalData apiData) {
8634 if (naData == null || apiData == null) {
8635 return naData == null ? apiData : naData;
8636 }
8637 final CaptivePortalData.Builder captivePortalBuilder =
8638 new CaptivePortalData.Builder(naData);
8639
8640 if (apiData.isCaptive()) {
8641 captivePortalBuilder.setCaptive(true);
8642 }
8643 if (apiData.isSessionExtendable()) {
8644 captivePortalBuilder.setSessionExtendable(true);
8645 }
8646 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8647 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8648 // otherwise data would be inconsistent. Prefer the capport API info if present,
8649 // as it can generally be refreshed more often.
8650 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8651 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8652 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8653 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8654 // No source has time / bytes remaining information: surface the newest refresh time
8655 // for other fields
8656 captivePortalBuilder.setRefreshTime(
8657 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8658 }
8659
Hai Shalom7c6ab402021-02-04 19:34:06 -08008660 // Prioritize the user portal URL from the network agent if the source is authenticated.
8661 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8662 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8663 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8664 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008665 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008666 // Prioritize the venue information URL from the network agent if the source is
8667 // authenticated.
8668 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8669 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8670 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8671 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008672 }
8673 return captivePortalBuilder.build();
8674 }
8675
Suprabh Shukla53e16392023-04-26 18:47:36 -07008676 @VisibleForTesting
8677 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008678 // This needs to be kept in sync and backwards compatible with the decoding logic in
8679 // NetdEventListenerService, which is non-mainline code.
8680 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8681 }
8682
Suprabh Shukla75642282023-04-25 23:15:43 -07008683 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8684 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8685 return true;
8686 }
8687 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8688 return true;
8689 }
8690 return false;
8691 }
8692
Suprabh Shukla1e312032023-01-24 03:36:37 -08008693 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008694 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008695 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008696 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008697 return;
8698 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008699
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008700 // Mask/mark of zero will not detect anything interesting.
8701 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008702 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008703 return;
8704 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008705
Suprabh Shukla1e312032023-01-24 03:36:37 -08008706 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008707 try {
8708 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008709 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008710 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008711 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008712 }
8713 } catch (Exception e) {
8714 loge("Exception modifying wakeup packet monitoring: " + e);
8715 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008716 }
8717
Junyu Lai970963e2022-10-25 15:46:47 +08008718 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008719 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008720 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008721 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008722 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008723 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008724 for (final String iface : interfaceDiff.added) {
8725 try {
8726 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008727 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008728 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008729 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008730 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008731 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008732 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008733 }
Paul Jensenbff73492014-04-28 10:33:11 -04008734 }
8735 }
Chalard Jean9589e722019-11-19 19:03:53 +09008736 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008737 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008738 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008739 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008740 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008741 } catch (Exception e) {
8742 loge("Exception removing interface: " + e);
8743 }
8744 }
8745 }
8746
Paul Jensene0fd4a82014-08-06 15:51:33 -04008747 /**
8748 * Have netd update routes from oldLp to newLp.
8749 * @return true if routes changed between oldLp and newLp
8750 */
Junyu Lai970963e2022-10-25 15:46:47 +08008751 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8752 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008753 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008754 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8755 new CompareOrUpdateResult<>(
8756 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008757 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008758 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008759
8760 // add routes before removing old in case it helps with continuous connectivity
8761
Chalard Jean9dd11612018-06-04 16:52:49 +09008762 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008763 for (RouteInfo route : routeDiff.added) {
8764 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008765 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008766 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008767 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008768 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008769 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008770 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008771 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008772 }
8773 }
8774 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008775 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008776 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008777 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008778 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008779 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008780 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008781 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008782 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008783 }
8784 }
8785
8786 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008787 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008788 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008789 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008790 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008791 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008792 }
8793 }
Tyler Weare4314862019-12-05 14:55:30 -08008794
8795 for (RouteInfo route : routeDiff.updated) {
8796 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8797 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008798 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008799 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008800 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008801 }
8802 }
8803 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8804 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008805 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008806
Junyu Lai970963e2022-10-25 15:46:47 +08008807 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8808 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008809 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8810 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008811 }
Erik Klineb9888902016-04-05 13:30:49 +09008812
Erik Kline31b4a9e2018-01-11 21:07:29 +09008813 if (DBG) {
8814 final Collection<InetAddress> dnses = newLp.getDnsServers();
8815 log("Setting DNS servers for network " + netId + " to " + dnses);
8816 }
Erik Klineb9888902016-04-05 13:30:49 +09008817 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008818 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008819 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008820 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008821 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008822 }
Erik Kline54e35c02017-04-07 15:29:29 +09008823 }
8824
Junyu Lai970963e2022-10-25 15:46:47 +08008825 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8826 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008827 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8828 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008829 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8830 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008831
8832 if (!wasFiltering && !needsFiltering) {
8833 // Nothing to do.
8834 return;
8835 }
8836
8837 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8838 // Nothing changed.
8839 return;
8840 }
8841
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008842 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008843 if (ranges == null || ranges.isEmpty()) {
8844 return;
8845 }
8846
Qingxi Libb8da982020-01-17 17:54:27 -08008847 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008848 // TODO: this create a window of opportunity for apps to receive traffic between the time
8849 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008850 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008851 // old rules are being removed.
8852 if (wasFiltering) {
8853 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8854 }
8855 if (needsFiltering) {
8856 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8857 }
8858 }
8859
Valentin Iftime9fa35092019-09-24 13:32:13 +02008860 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008861 if (mWolSupportedInterfaces == null) {
8862 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008863 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008864 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008865 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8866 }
8867
Luke Huangb913c812018-08-24 20:33:16 +08008868 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008869 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008870 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008871 }
8872 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008873 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008874 }
Luke Huangb913c812018-08-24 20:33:16 +08008875 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008876 }
8877
Chalard Jean62edfd82019-12-02 18:39:29 +09008878 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8879 @NonNull final NetworkCapabilities newNc) {
8880 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8881 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008882 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008883 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008884 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008885 } catch (RemoteException | ServiceSpecificException e) {
8886 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008887 }
8888 }
8889 }
8890
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008891 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008892 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008893 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008894 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008895 underlyingNetworks = underlyingNetworksOrDefault(
8896 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008897 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008898 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8899 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008900 // metered if any underlying is metered, or originally declared metered by the agent.
8901 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008902 boolean roaming = false; // roaming if any underlying is roaming
8903 boolean congested = false; // congested if any underlying is congested
8904 boolean suspended = true; // suspended if all underlying are suspended
8905
8906 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008907 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008908 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008909 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008910 for (Network underlyingNetwork : underlyingNetworks) {
8911 final NetworkAgentInfo underlying =
8912 getNetworkAgentInfoForNetwork(underlyingNetwork);
8913 if (underlying == null) continue;
8914
8915 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8916 hadUnderlyingNetworks = true;
8917 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008918 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008919 }
8920
8921 // Merge capabilities of this underlying network. For bandwidth, assume the
8922 // worst case.
8923 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8924 underlyingCaps.getLinkDownstreamBandwidthKbps());
8925 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8926 underlyingCaps.getLinkUpstreamBandwidthKbps());
8927 // If this underlying network is metered, the VPN is metered (it may cost money
8928 // to send packets on this network).
8929 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8930 // If this underlying network is roaming, the VPN is roaming (the billing structure
8931 // is different than the usual, local one).
8932 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8933 // If this underlying network is congested, the VPN is congested (the current
8934 // condition of the network affects the performance of this network).
8935 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8936 // If this network is not suspended, the VPN is not suspended (the VPN
8937 // is able to transfer some data).
8938 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008939 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008940 }
8941 }
8942 if (!hadUnderlyingNetworks) {
8943 // No idea what the underlying networks are; assume reasonable defaults
8944 metered = true;
8945 roaming = false;
8946 congested = false;
8947 suspended = false;
8948 }
8949
Chalard Jean1d420b32022-10-12 16:39:37 +09008950 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008951 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8952 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8953 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8954 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8955 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8956 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008957 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008958 }
8959
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008960 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008961 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8962 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8963 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008964 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008965 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008966 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008967 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008968 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8969 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008970 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008971 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008972 if (nai.everConnected()
8973 && !nai.isVPN()
8974 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008975 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008976 // does not cause any request (that is not a listen) currently matching that agent to
8977 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008978 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008979 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008980 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008981 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008982 }
8983
Paul Jensen53f08952015-06-16 14:27:36 -04008984 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008985 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008986 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008987 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008988 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008989 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008990 }
Chalard Jean254bd162022-08-25 13:04:51 +09008991 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008992 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008993 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008994 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008995 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008996 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008997 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008998 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008999 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009000 }
Chalard Jean254bd162022-08-25 13:04:51 +09009001 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08009002 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9003 } else {
9004 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9005 }
lucasline117e2e2019-10-22 18:27:33 +08009006 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009007
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009008 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09009009 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
9010 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009011 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09009012 }
9013
Lorenzo Colittibd079452021-07-02 11:47:57 +09009014 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09009015 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09009016 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009017 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009018 }
9019
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009020 return newNc;
9021 }
9022
Lorenzo Colitti44840702021-01-11 22:27:57 +09009023 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
9024 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
9025 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9026 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9027 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9028 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9029 if (prevSuspended != suspended) {
9030 // TODO (b/73132094) : remove this call once the few users of onSuspended and
9031 // onResumed have been removed.
9032 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
9033 : ConnectivityManager.CALLBACK_RESUMED);
9034 }
9035 if (prevSuspended != suspended || prevRoaming != roaming) {
9036 // updateNetworkInfo will mix in the suspended info from the capabilities and
9037 // take appropriate action for the network having possibly changed state.
9038 updateNetworkInfo(nai, nai.networkInfo);
9039 }
9040 }
9041
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009042 /**
9043 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
9044 *
9045 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
9046 * capabilities we manage and store in {@code nai}, such as validated status and captive
9047 * portal status)
9048 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
9049 * potentially triggers rematches.
9050 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
9051 * change.)
9052 *
9053 * @param oldScore score of the network before any of the changes that prompted us
9054 * to call this function.
9055 * @param nai the network having its capabilities updated.
9056 * @param nc the new network capabilities.
9057 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009058 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09009059 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009060 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009061 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09009062 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
9063 if (null != differences) {
9064 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
9065 }
Chalard Jean62edfd82019-12-02 18:39:29 +09009066 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09009067 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009068
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009069 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09009070 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09009071 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009072
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009073 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009074 // If the requestable capabilities haven't changed, and the score hasn't changed, then
9075 // the change we're processing can't affect any requests, it can only affect the listens
9076 // on this network. We might have been called by rematchNetworkAndRequests when a
9077 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09009078 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009079 } else {
9080 // If the requestable capabilities have changed or the score changed, we can't have been
9081 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009082 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009083 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009084 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009085 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009086
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009087 final boolean oldMetered = prevNc.isMetered();
9088 final boolean newMetered = newNc.isMetered();
9089 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009090
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009091 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009092 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9093 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009094 }
junyulaif2c67e42018-08-07 19:50:45 +08009095
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009096 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9097 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009098
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009099 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009100 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009101 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009102 }
9103
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009104 // This network might have been underlying another network. Propagate its capabilities.
9105 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009106
Ken Chen5a35cf92023-10-07 07:54:22 +08009107 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009108 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009109 }
lucaslin53e8a262021-06-08 01:43:59 +08009110
9111 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009112 }
9113
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009114 /** Convenience method to update the capabilities for a given network. */
9115 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009116 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009117 }
9118
Chalard Jean1e4c2182023-10-06 18:45:53 +09009119 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009120 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009121 @Nullable final LocalNetworkConfig oldConfig,
9122 @NonNull final LocalNetworkConfig newConfig) {
9123 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009124 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9125 return;
9126 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009127
Chalard Jean4fe23392023-10-17 23:02:27 +09009128 if (VDBG) {
9129 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9130 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009131 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
9132 // TODO : apply the diff for multicast routing.
9133 configBuilder.setUpstreamMulticastRoutingConfig(
9134 newConfig.getUpstreamMulticastRoutingConfig());
9135 configBuilder.setDownstreamMulticastRoutingConfig(
9136 newConfig.getDownstreamMulticastRoutingConfig());
9137
9138 final NetworkRequest oldRequest =
9139 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9140 final NetworkCapabilities oldCaps =
9141 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9142 final NetworkRequestInfo oldNri =
9143 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9144 final NetworkAgentInfo oldSatisfier =
9145 null == oldNri ? null : oldNri.getSatisfier();
9146 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9147 final NetworkCapabilities newCaps =
9148 (null == newRequest) ? null : newRequest.networkCapabilities;
9149 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9150 if (null != oldRequest && requestUpdated) {
9151 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9152 if (null == newRequest && null != oldSatisfier) {
9153 // If there is an old satisfier, but no new request, then remove the old upstream.
9154 removeLocalNetworkUpstream(nai, oldSatisfier);
9155 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009156 // When there is a new request, the rematch sees the new request and sends the
9157 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9158 // But here there is no new request, so the rematch won't see anything. Send
9159 // callbacks to apps now to tell them about the loss of upstream.
9160 notifyNetworkCallbacks(nai,
9161 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009162 return;
9163 }
9164 }
9165 if (null != newRequest && requestUpdated) {
9166 // File the new request if :
9167 // - it has changed (requestUpdated), or
9168 // - it's the first time this local info (null == oldConfig)
9169 // is updated and the request has not been filed yet.
9170 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9171 // upstream (the best) but never request it to be brought up.
9172 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9173 nextNetworkRequestId(), LISTEN_FOR_BEST);
9174 configBuilder.setUpstreamSelector(nr);
9175 final NetworkRequestInfo nri = new NetworkRequestInfo(
9176 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9177 0 /* callbackFlags */, null /* attributionTag */);
9178 if (null != oldSatisfier) {
9179 // Set the old satisfier in the new NRI so that the rematch will see any changes
9180 nri.setSatisfier(oldSatisfier, nr);
9181 }
9182 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009183 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9184 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9185 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009186 handleRegisterNetworkRequest(nri);
9187 } else {
9188 configBuilder.setUpstreamSelector(oldRequest);
9189 nai.localNetworkConfig = configBuilder.build();
9190 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009191 }
9192
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009193 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009194 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009195 *
9196 * Ingress interface filtering enforces that all apps under the given network can only receive
9197 * packets from the network's interface (and loopback). This is important for VPNs because
9198 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9199 * non-VPN interfaces.
9200 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009201 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009202 * 1. the network is an app VPN (not legacy VPN)
9203 * 2. the VPN does not allow bypass
9204 * 3. the VPN is fully-routed
9205 * 4. the VPN interface is non-null
9206 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009207 * @see INetd#firewallAddUidInterfaceRules
9208 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009209 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009210 @Nullable
9211 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009212 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009213 if (nc == null || lp == null) return null;
9214 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009215 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009216 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009217 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009218 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009219 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009220 && !lp.hasExcludeRoute()) {
9221 return lp.getInterfaceName();
9222 }
9223 return null;
9224 }
9225
9226 /**
9227 * Returns whether we need to set interface filtering rule or not
9228 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009229 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009230 String isolationIface) {
9231 // Allow rules are always needed if VPN isolation is enabled.
9232 if (isolationIface != null) return true;
9233
9234 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9235 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9236 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009237 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009238 }
9239
Chiachang Wang28afaff2020-12-10 22:24:47 +08009240 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9241 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9242 int index = 0;
9243 for (UidRange range : ranges) {
9244 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9245 index++;
9246 }
9247 return stableRanges;
9248 }
9249
Chalard Jeane6c95272022-01-25 21:04:21 +09009250 private static UidRangeParcel[] intsToUidRangeStableParcels(
9251 final @NonNull ArraySet<Integer> uids) {
9252 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9253 int index = 0;
9254 for (int uid : uids) {
9255 stableRanges[index] = new UidRangeParcel(uid, uid);
9256 index++;
9257 }
9258 return stableRanges;
9259 }
9260
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009261 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9262 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9263 for (int i = 0; i < ranges.length; i++) {
9264 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9265 }
9266 return stableRanges;
9267 }
9268
Motomu Utsumi93a22182023-03-16 17:04:21 +09009269 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009270 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009271 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9272 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009273 if (mDeps.isAtLeastU()) {
9274 final Set<Integer> exemptUidSet = new ArraySet<>();
9275 for (final int uid: exemptUids) {
9276 exemptUidSet.add(uid);
9277 }
9278 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9279 } else {
9280 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9281 }
Ken Chen5e65a852020-12-24 12:59:10 +08009282 } catch (Exception e) {
9283 loge("Exception in socket destroy: ", e);
9284 }
9285 }
9286 }
9287
paulhuaa0743d2021-05-26 21:56:03 +08009288 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009289 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009290 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9291 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9292 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009293 exemptUids[0] = VPN_UID;
9294 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009295 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9296
Motomu Utsumi6345e462023-03-13 13:24:50 +09009297 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009298 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009299 try {
9300 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009301 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009302 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009303 } else {
paulhu0e79d952021-06-09 16:11:35 +08009304 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009305 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009306 }
9307 } catch (Exception e) {
9308 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9309 " on netId " + nai.network.netId + ". " + e);
9310 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009311 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009312 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009313 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009314
lucaslin53e8a262021-06-08 01:43:59 +08009315 private boolean isProxySetOnAnyDefaultNetwork() {
9316 ensureRunningOnConnectivityServiceThread();
9317 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9318 final NetworkAgentInfo nai = nri.getSatisfier();
9319 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9320 return true;
9321 }
9322 }
9323 return false;
9324 }
9325
9326 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9327 NetworkCapabilities newNc) {
9328 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9329 // the proxy might be changed since the default network satisfied by the apps might also
9330 // changed.
9331 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9332 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009333 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9334 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009335 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009336 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9337 mProxyTracker.sendProxyBroadcast();
9338 }
9339 }
9340
Chalard Jeane6c95272022-01-25 21:04:21 +09009341 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9342 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009343 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9344 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009345 if (null == prevRanges) prevRanges = new ArraySet<>();
9346 if (null == newRanges) newRanges = new ArraySet<>();
9347 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9348
9349 prevRanges.removeAll(newRanges);
9350 newRanges.removeAll(prevRangesCopy);
9351
9352 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009353 // When updating the VPN uid routing rules, add the new range first then remove the old
9354 // range. If old range were removed first, there would be a window between the old
9355 // range being removed and the new range being added, during which UIDs contained
9356 // in both ranges are not subject to any VPN routing rules. Adding new range before
9357 // removing old range works because, unlike the filtering rules below, it's possible to
9358 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009359 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9360 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9361 // [1-5] & [1-2],[4-5] == [3]
9362 // Then we can do:
9363 // maybeCloseSockets([3])
9364 // mNetd.networkAddUidRanges([1-2],[4-5])
9365 // mNetd.networkRemoveUidRanges([1-5])
9366 // maybeCloseSockets([3])
9367 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9368 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009369 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009370 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009371 }
9372 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009373 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009374 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009375 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9376 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009377 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9378 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009379 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009380 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009381 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9382 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9383 // were added first and then newRanges got removed later, there would be only one uid
9384 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9385 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9386 // Note that this is in contrast with the (more robust) update of VPN routing rules
9387 // above, where the addition of new ranges happens before the removal of old ranges.
9388 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9389 // to be removed will never overlap with the new range to be added.
9390 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009391 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9392 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009393 }
9394 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009395 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009396 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009397 } catch (Exception e) {
9398 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009399 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009400 }
9401 }
9402
Chalard Jeande665262022-02-25 16:12:12 +09009403 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009404 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9405 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009406 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9407 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009408 if (prevEmpty && newEmpty) return;
9409
9410 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009411 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009412 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009413 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009414
9415 if (prevUids.equals(newUids)) return;
9416
9417 // This implementation is very simple and vastly faster for sets of Integers than
9418 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9419 // a key computed from the value and has storage for that.
9420 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9421 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9422 toRemove.removeAll(newUids);
9423 toAdd.removeAll(prevUids);
9424
9425 try {
9426 if (!toAdd.isEmpty()) {
9427 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9428 nai.network.netId,
9429 intsToUidRangeStableParcels(toAdd),
9430 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9431 }
9432 if (!toRemove.isEmpty()) {
9433 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9434 nai.network.netId,
9435 intsToUidRangeStableParcels(toRemove),
9436 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9437 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009438 } catch (ServiceSpecificException e) {
9439 // Has the interface disappeared since the network was built ?
9440 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009441 } catch (RemoteException e) {
9442 // Netd died. This usually causes a runtime restart anyway.
9443 }
9444 }
9445
Junyu Lai2ed7d412022-10-07 16:52:21 +08009446 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9447 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009448 ensureRunningOnConnectivityServiceThread();
9449
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009450 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009451 // Ignore updates for disconnected networks
9452 return;
9453 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009454 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009455 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009456 + "; created=" + nai.getCreatedTime()
9457 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009458 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009459 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9460 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009461 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009462 }
9463
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009464 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9465 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009466 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009467 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009468 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009469 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9470 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9471 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009472 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9473 // need to be sent as a separate extra.
9474 final NetworkRequest req = nri.isMultilayerRequest()
9475 ? nri.getActiveRequest()
9476 // Non-multilayer listen requests do not have an active request
9477 : nri.mRequests.get(0);
9478 if (req == null) {
9479 Log.wtf(TAG, "No request in NRI " + nri);
9480 }
9481 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009482 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009483 sendIntent(nri.mPendingIntent, intent);
9484 }
9485 // else not handled
9486 }
9487
Michael Groover73f69482023-01-27 11:01:25 -06009488 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9489 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009490 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9491 mPendingIntentWakeLock.acquire();
9492 try {
9493 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009494 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009495 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009496 // Explicitly disallow the receiver from starting activities, to prevent apps from
9497 // utilizing the PendingIntent as a backdoor to do this.
9498 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9499 }
9500 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9501 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009502 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009503 } catch (PendingIntent.CanceledException e) {
9504 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9505 mPendingIntentWakeLock.release();
9506 releasePendingNetworkRequest(pendingIntent);
9507 }
9508 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9509 }
9510
9511 @Override
9512 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9513 String resultData, Bundle resultExtras) {
9514 if (DBG) log("Finished sending " + pendingIntent);
9515 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009516 // Release with a delay so the receiving client has an opportunity to put in its
9517 // own request.
9518 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009519 }
9520
Chalard Jean22350c92023-10-07 19:21:45 +09009521 @Nullable
9522 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9523 if (!nai.isLocalNetwork()) return null;
9524 final Network upstream;
9525 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9526 if (null == selector) {
9527 upstream = null;
9528 } else {
9529 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9530 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9531 upstream = (null == satisfier) ? null : satisfier.network;
9532 }
9533 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9534 }
9535
Chalard Jean46bfbf02022-02-02 00:56:25 +09009536 // networkAgent is only allowed to be null if notificationType is
9537 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9538 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009539 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009540 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009541 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009542 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009543 // Default request has no msgr. Also prevents callbacks from being invoked for
9544 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9545 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9546 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009547 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009548 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009549 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009550 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009551 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009552 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009553 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009554 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9555 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009556 }
Roshan Pius951c0032020-12-22 15:10:42 -08009557 final boolean includeLocationSensitiveInfo =
9558 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009559 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009560 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009561 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009562 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009563 networkCapabilitiesRestrictedForCallerPermissions(
9564 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9565 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009566 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009567 nri.mCallingAttributionTag);
9568 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009569 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9570 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009571 // The local network info is often null, so can't use the static putParcelable
9572 // method here.
9573 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9574 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009575 // For this notification, arg1 contains the blocked status.
9576 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009577 break;
9578 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009579 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009580 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009581 break;
9582 }
9583 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009584 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009585 final NetworkCapabilities netCap =
9586 networkCapabilitiesRestrictedForCallerPermissions(
9587 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9588 putParcelable(
9589 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009590 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009591 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009592 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009593 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009594 break;
9595 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009596 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009597 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9598 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009599 break;
9600 }
junyulaif2c67e42018-08-07 19:50:45 +08009601 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009602 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009603 msg.arg1 = arg1;
9604 break;
9605 }
Chalard Jean22350c92023-10-07 19:21:45 +09009606 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9607 if (!networkAgent.isLocalNetwork()) {
9608 Log.wtf(TAG, "Callback for local info for a non-local network");
9609 return;
9610 }
9611 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9612 break;
9613 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009614 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009615 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009616 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009617 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009618 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009619 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009620 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009621 }
James Mattis45d81842021-01-10 14:24:24 -08009622 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009623 } catch (RemoteException e) {
9624 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009625 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009626 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009627 }
9628
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009629 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9630 bundle.putParcelable(t.getClass().getSimpleName(), t);
9631 }
9632
Chalard Jean0702f982021-09-16 21:50:07 +09009633 /**
9634 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9635 *
9636 * When a request should be assigned to a new network, it is normally lingered to give
9637 * time for apps to gracefully migrate their connections. When both networks are on the same
9638 * radio, but that radio can't do time-sharing efficiently, this may end up being
9639 * counter-productive because any traffic on the old network may drastically reduce the
9640 * performance of the new network.
9641 * The stack supports a configuration to let modem vendors state that their radio can't
9642 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9643 * from one cell network to another can't be done gracefully.
9644 *
9645 * @param oldNai the old network serving the request
9646 * @param newNai the new network serving the request
9647 * @return whether the switch can be graceful
9648 */
9649 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9650 @NonNull final NetworkAgentInfo newSatisfier) {
9651 if (mCellularRadioTimesharingCapable) return true;
9652 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9653 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9654 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9655 }
9656
Paul Jensenaf94b982014-09-30 15:37:41 -04009657 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009658 if (nai.numRequestNetworkRequests() != 0) {
9659 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9660 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009661 // Ignore listening and track default requests.
9662 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009663 loge("Dead network still had at least " + nr);
9664 break;
9665 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009666 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009667 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009668 }
9669
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009670 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9671 if (oldNetwork == null) {
9672 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9673 return;
9674 }
Chalard Jean49707572019-12-10 21:07:02 +09009675 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009676
9677 // If we get here it means that the last linger timeout for this network expired. So there
9678 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009679 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009680
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009681 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009682 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009683 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009684 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009685 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009686 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009687 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009688 }
9689
James Mattise3ef1912020-12-20 11:09:58 -08009690 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9691 boolean isDefaultChanged = false;
9692 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9693 final NetworkReassignment.RequestReassignment reassignment =
9694 changes.getReassignment(defaultRequestInfo);
9695 if (null == reassignment) {
9696 continue;
9697 }
9698 // reassignment only contains those instances where the satisfying network changed.
9699 isDefaultChanged = true;
9700 // Notify system services of the new default.
9701 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9702 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009703
James Mattise3ef1912020-12-20 11:09:58 -08009704 if (isDefaultChanged) {
9705 // Hold a wakelock for a short time to help apps in migrating to a new default.
9706 scheduleReleaseNetworkTransitionWakelock();
9707 }
9708 }
9709
Aaron Huang9fe47be2021-06-08 13:11:45 +08009710 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9711 if (null == oldDefaultNetwork) return;
9712 // The network stopped being the default. If it was using a PAC proxy, then the
9713 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9714 // to the local proxy server, which would forward them over the newly default network.
9715 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9716 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9717 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9718 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9719 }
9720
James Mattise3ef1912020-12-20 11:09:58 -08009721 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9722 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9723 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9724 if (DBG) {
9725 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9726 }
Chalard Jean8e382112019-12-03 20:45:30 +09009727
James Mattisd31bdfa2020-12-23 16:37:26 -08009728 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9729 if (newDefaultNetwork != null) {
9730 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009731 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009732
James Mattisd31bdfa2020-12-23 16:37:26 -08009733 // Set an app level managed default and return since further processing only applies to the
9734 // default network.
9735 if (mDefaultRequest != nri) {
9736 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9737 return;
9738 }
9739
9740 makeDefaultNetwork(newDefaultNetwork);
9741
James Mattise3ef1912020-12-20 11:09:58 -08009742 if (oldDefaultNetwork != null) {
9743 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9744 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09009745 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009746 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009747 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009748 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009749 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009750 updateTcpBufferSizes(null != newDefaultNetwork
9751 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009752 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009753 }
9754
James Mattisd31bdfa2020-12-23 16:37:26 -08009755 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9756 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9757 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9758 try {
9759 if (VDBG) {
9760 log("Setting default network for " + nri
9761 + " using UIDs " + nri.getUids()
9762 + " with old network " + (oldDefaultNetwork != null
9763 ? oldDefaultNetwork.network().getNetId() : "null")
9764 + " and new network " + (newDefaultNetwork != null
9765 ? newDefaultNetwork.network().getNetId() : "null"));
9766 }
9767 if (nri.getUids().isEmpty()) {
9768 throw new IllegalStateException("makeDefaultForApps called without specifying"
9769 + " any applications to set as the default." + nri);
9770 }
9771 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009772 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009773 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009774 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009775 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009776 }
9777 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009778 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009779 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009780 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009781 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009782 }
9783 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009784 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009785 }
9786 }
9787
Junyu Lai35665cc2022-12-19 17:37:48 +08009788 /**
9789 * Collect restricted uid ranges for the given network and UserHandle, these uids
9790 * are not restricted for matched enterprise networks but being restricted for non-matched
9791 * enterprise networks and non-enterprise networks.
9792 */
9793 @NonNull
9794 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9795 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9796 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9797 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9798 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9799
9800 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9801 // The NC is built from a `ProfileNetworkPreference` which has only one
9802 // enterprise ID, so it's guaranteed to have exactly one.
9803 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9804 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9805 continue;
9806 }
9807 }
9808
9809 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9810 pref.capabilities.getUidRanges())) {
9811 throw new IllegalArgumentException(
9812 "Overlapping uid range in preference: " + pref);
9813 }
9814 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9815 }
9816 return restrictedUidRanges;
9817 }
9818
9819 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009820 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009821 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009822
Junyu Lai35665cc2022-12-19 17:37:48 +08009823 ensureRunningOnConnectivityServiceThread();
9824 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9825 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9826 .getUserHandles(true /* excludeDying */);
9827 if (users.isEmpty()) {
9828 throw new IllegalStateException("No user is available");
9829 }
9830
9831 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9832 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9833 for (final UserHandle user : users) {
9834 final ArraySet<UidRange> restrictedUidRanges =
9835 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9836 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9837 UidRange.createForUser(user), restrictedUidRanges));
9838 }
9839
9840 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9841 configs.add(new NativeUidRangeConfig(
9842 nai.network.netId, rangesParcel, 0 /* subPriority */));
9843 }
9844
9845 // The netd API replaces the previous configs with the current configs.
9846 // Thus, for network disconnection or preference removal, no need to
9847 // unset previous config. Instead, collecting all currently needed
9848 // configs and issue to netd.
9849 try {
9850 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9851 } catch (ServiceSpecificException e) {
9852 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009853 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009854 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009855 // Netd died. This will cause a runtime restart anyway.
9856 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009857 }
9858 }
9859
James Mattisd31bdfa2020-12-23 16:37:26 -08009860 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9861 try {
9862 if (null != newDefaultNetwork) {
9863 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9864 } else {
9865 mNetd.networkClearDefault();
9866 }
9867 } catch (RemoteException | ServiceSpecificException e) {
9868 loge("Exception setting default network :" + e);
9869 }
9870 }
9871
Chalard Jean05cbe972019-12-09 11:50:38 +09009872 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009873 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009874 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009875 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009876 processNewlySatisfiedListenRequests(nai);
9877 }
9878
9879 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009880 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9881 if (nri.isMultilayerRequest()) {
9882 continue;
9883 }
9884 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009885 if (!nr.isListen()) continue;
9886 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009887 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009888 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9889 }
9890 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009891 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009892
Chalard Jeancd397a22019-11-22 22:33:33 +09009893 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009894 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9895 if (nri.isMultilayerRequest()) {
9896 continue;
9897 }
9898 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009899 if (!nr.isListen()) continue;
9900 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9901 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009902 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009903 }
9904 }
9905 }
9906
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009907 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009908 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009909 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009910 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009911 @Nullable public final NetworkRequest mOldNetworkRequest;
9912 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009913 @Nullable public final NetworkAgentInfo mOldNetwork;
9914 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009915 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009916 @Nullable final NetworkRequest oldNetworkRequest,
9917 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009918 @Nullable final NetworkAgentInfo oldNetwork,
9919 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009920 mNetworkRequestInfo = networkRequestInfo;
9921 mOldNetworkRequest = oldNetworkRequest;
9922 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009923 mOldNetwork = oldNetwork;
9924 mNewNetwork = newNetwork;
9925 }
Chalard Jean49707572019-12-10 21:07:02 +09009926
9927 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009928 final NetworkRequest requestToShow = null != mNewNetworkRequest
9929 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9930 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009931 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9932 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009933 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009934 }
9935
Chalard Jean46a62372019-12-10 21:25:24 +09009936 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009937
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009938 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009939 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009940 }
9941
9942 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009943 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009944 // The code is never supposed to add two reassignments of the same request. Make
9945 // sure this stays true, but without imposing this expensive check on all
9946 // reassignments on all user devices.
9947 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009948 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009949 throw new IllegalStateException("Trying to reassign ["
9950 + reassignment + "] but already have ["
9951 + existing + "]");
9952 }
9953 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009954 }
Chalard Jean46a62372019-12-10 21:25:24 +09009955 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009956 }
9957
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009958 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009959 // the passed request.
9960 @Nullable
9961 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009962 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009963 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009964 }
9965 return null;
9966 }
Chalard Jean49707572019-12-10 21:07:02 +09009967
9968 public String toString() {
9969 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9970 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009971 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009972 for (final RequestReassignment rr : getRequestReassignments()) {
9973 sj.add(rr.toString());
9974 }
9975 return sj.toString();
9976 }
9977
9978 public String debugString() {
9979 final StringBuilder sb = new StringBuilder();
9980 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009981 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009982 for (final RequestReassignment rr : getRequestReassignments()) {
9983 sb.append("\n ").append(rr);
9984 }
9985 return sb.append("\n").toString();
9986 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009987 }
9988
Chalard Jean24344d72019-12-04 13:32:31 +09009989 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009990 @Nullable final NetworkRequest previousRequest,
9991 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009992 @Nullable final NetworkAgentInfo previousSatisfier,
9993 @Nullable final NetworkAgentInfo newSatisfier,
9994 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009995 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009996 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009997 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009998 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009999 log(" accepting network in place of " + previousSatisfier.toShortString()
10000 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010001 }
James Mattisa076c532020-12-02 14:12:41 -080010002 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010003 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +090010004 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +090010005 // If this network switch can't be supported gracefully, the request is not
10006 // lingered. This allows letting go of the network sooner to reclaim some
10007 // performance on the new network, since the radio can't do both at the same
10008 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010009 //
10010 // Also don't linger the request if the old network has been destroyed.
10011 // A destroyed network does not provide actual network connectivity, so
10012 // lingering it is not useful. In particular this ensures that a destroyed
10013 // network is outscored by its replacement,
10014 // then it is torn down immediately instead of being lingered, and any apps that
10015 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +090010016 previousSatisfier.lingerRequest(previousRequest.requestId, now);
10017 }
Chalard Jean24344d72019-12-04 13:32:31 +090010018 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010019 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010020 }
junyulai0ac374f2020-12-14 18:41:52 +080010021
10022 // To prevent constantly CPU wake up for nascent timer, if a network comes up
10023 // and immediately satisfies a request then remove the timer. This will happen for
10024 // all networks except in the case of an underlying network for a VCN.
10025 if (newSatisfier.isNascent()) {
10026 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +080010027 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010028 }
10029
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010030 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -080010031 newSatisfier.unlingerRequest(newRequest.requestId);
10032 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +080010033 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -080010034 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010035 }
Chalard Jeana8ac2302021-03-01 22:16:08 +090010036 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010037 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010038 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -080010039 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010040 }
James Mattisa076c532020-12-02 14:12:41 -080010041 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010042 }
James Mattisa076c532020-12-02 14:12:41 -080010043 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010044 }
10045
James Mattisa076c532020-12-02 14:12:41 -080010046 /**
10047 * This function is triggered when something can affect what network should satisfy what
10048 * request, and it computes the network reassignment from the passed collection of requests to
10049 * network match to the one that the system should now have. That data is encoded in an
10050 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
10051 * satisfier.
10052 *
10053 * After the reassignment is computed, it is applied to the state objects.
10054 *
10055 * @param networkRequests the nri objects to evaluate for possible network reassignment
10056 * @return NetworkReassignment listing of proposed network assignment changes
10057 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010058 @NonNull
James Mattisa076c532020-12-02 14:12:41 -080010059 private NetworkReassignment computeNetworkReassignment(
10060 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090010061 final NetworkReassignment changes = new NetworkReassignment();
10062
Chalard Jeanc81d4c32021-04-07 17:06:19 +090010063 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090010064 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010065 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +090010066 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +090010067 }
Chalard Jean857a1712019-12-10 21:08:07 +090010068
James Mattisa076c532020-12-02 14:12:41 -080010069 for (final NetworkRequestInfo nri : networkRequests) {
10070 // Non-multilayer listen requests can be ignored.
10071 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
10072 continue;
10073 }
10074 NetworkAgentInfo bestNetwork = null;
10075 NetworkRequest bestRequest = null;
10076 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090010077 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080010078 // Stop evaluating as the highest possible priority request is satisfied.
10079 if (null != bestNetwork) {
10080 bestRequest = req;
10081 break;
10082 }
10083 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010084 if (null == bestNetwork && isDefaultBlocked(nri)) {
10085 // Remove default networking if disallowed for managed default requests.
10086 bestNetwork = mNoServiceNetwork;
10087 }
10088 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010089 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010090 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010091 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010092 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010093 }
10094 return changes;
10095 }
10096
James Mattisa076c532020-12-02 14:12:41 -080010097 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10098 return new HashSet<>(mNetworkRequests.values());
10099 }
10100
Paul Jensenc88b39b2015-06-16 14:27:36 -040010101 /**
James Mattisa076c532020-12-02 14:12:41 -080010102 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010103 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010104 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010105 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010106 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10107 }
10108
10109 /**
10110 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10111 * being disconnected.
10112 */
10113 private void rematchNetworksAndRequests(
10114 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10115 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010116 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010117 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010118 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010119 final long computed = SystemClock.elapsedRealtime();
10120 applyNetworkReassignment(changes, start);
10121 final long applied = SystemClock.elapsedRealtime();
10122 issueNetworkNeeds();
10123 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010124 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010125 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10126 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010127 log(changes.debugString());
10128 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010129 // Shorter form, only one line of log
10130 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10131 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010132 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010133 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010134
Chalard Jean1e4c2182023-10-06 18:45:53 +090010135 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10136 @Nullable final NetworkAgentInfo nai2) {
10137 if (null == nai1) return null == nai2;
10138 if (null == nai2) return false;
10139 return nai1.linkProperties.getInterfaceName()
10140 .equals(nai2.linkProperties.getInterfaceName());
10141 }
10142
Chalard Jeand7f762d2019-12-10 19:01:29 +090010143 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010144 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010145 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010146
10147 // Since most of the time there are only 0 or 1 background networks, it would probably
10148 // be more efficient to just use an ArrayList here. TODO : measure performance
10149 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10150 for (final NetworkAgentInfo nai : nais) {
10151 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10152 }
10153
Chalard Jeand7f762d2019-12-10 19:01:29 +090010154 // First, update the lists of satisfied requests in the network agents. This is necessary
10155 // because some code later depends on this state to be correct, most prominently computing
10156 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010157 for (final NetworkReassignment.RequestReassignment event :
10158 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010159 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10160 event.mOldNetworkRequest, event.mNewNetworkRequest,
10161 event.mOldNetwork, event.mNewNetwork,
10162 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010163 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010164
James Mattise3ef1912020-12-20 11:09:58 -080010165 // Process default network changes if applicable.
10166 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010167
Chalard Jean68eab722023-11-16 17:00:04 +090010168 // Update forwarding rules for the upstreams of local networks. Do this before sending
10169 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10170 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10171 // onAvailable so clients know what network the change is about. Store such changes in
10172 // an array that's only allocated if necessary (because it's almost never necessary).
10173 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10174 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10175 if (!nai.isLocalNetwork()) continue;
10176 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10177 if (null == nr) continue; // No upstream for this local network
10178 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10179 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10180 if (null == change) continue; // No change in upstreams for this network
10181 final String fromIface = nai.linkProperties.getInterfaceName();
10182 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10183 || change.mOldNetwork.isDestroyed()) {
10184 // There can be a change with the same interface name if the new network is the
10185 // replacement for the old network that was unregisteredAfterReplacement.
10186 try {
10187 if (null != change.mOldNetwork) {
10188 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10189 change.mOldNetwork.linkProperties.getInterfaceName());
10190 }
10191 // If the new upstream is already destroyed, there is no point in setting up
10192 // a forward (in fact, it might forward to the interface for some new network !)
10193 // Later when the upstream disconnects CS will try to remove the forward, which
10194 // is ignored with a benign log by RoutingCoordinatorService.
10195 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10196 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10197 change.mNewNetwork.linkProperties.getInterfaceName());
10198 }
10199 } catch (final RemoteException e) {
10200 loge("Can't update forwarding rules", e);
10201 }
10202 }
10203 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10204 localInfoChangedAgents.add(nai);
10205 }
10206
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010207 // Notify requested networks are available after the default net is switched, but
10208 // before LegacyTypeTracker sends legacy broadcasts
10209 for (final NetworkReassignment.RequestReassignment event :
10210 changes.getRequestReassignments()) {
10211 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010212 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010213 } else {
James Mattisa076c532020-12-02 14:12:41 -080010214 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010215 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010216 }
10217 }
10218
junyulai0ac374f2020-12-14 18:41:52 +080010219 // Update the inactivity state before processing listen callbacks, because the background
10220 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010221 // just yet though, because they have to be sent after the listens are processed to keep
10222 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010223 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010224 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010225 // Rematching may have altered the inactivity state of some networks, so update all
10226 // inactivity timers. updateInactivityState reads the state from the network agent
10227 // and does nothing if the state has not changed : the source of truth is controlled
10228 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10229 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010230 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010231 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010232 }
10233 }
10234
Chalard Jeanb10ab412019-12-11 14:12:30 +090010235 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010236 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010237 // Process listen requests and update capabilities if the background state has
10238 // changed for this network. For consistency with previous behavior, send onLost
10239 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010240 processNewlyLostListenRequests(nai);
10241 if (oldBackground != nai.isBackgroundNetwork()) {
10242 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010243 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010244 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010245 }
10246
junyulai0ac374f2020-12-14 18:41:52 +080010247 for (final NetworkAgentInfo nai : inactiveNetworks) {
10248 // For nascent networks, if connecting with no foreground request, skip broadcasting
10249 // LOSING for backward compatibility. This is typical when mobile data connected while
10250 // wifi connected with mobile data always-on enabled.
10251 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010252 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010253 }
10254
Chalard Jean68eab722023-11-16 17:00:04 +090010255 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10256 if (null != localInfoChangedAgents) {
10257 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10258 notifyNetworkCallbacks(nai,
10259 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010260 }
10261 }
10262
James Mattise3ef1912020-12-20 11:09:58 -080010263 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010264
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010265 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010266 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010267 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010268 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010269 // This network has active linger timers and no requests, but is not
10270 // lingering. Linger it.
10271 //
10272 // One way (the only way?) this can happen if this network is unvalidated
10273 // and became unneeded due to another network improving its score to the
10274 // point where this network will no longer be able to satisfy any requests
10275 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010276 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010277 notifyNetworkLosing(nai, now);
10278 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010279 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010280 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010281 teardownUnneededNetwork(nai);
10282 }
10283 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010284 }
10285 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010286
Chalard Jean62edfd82019-12-02 18:39:29 +090010287 /**
10288 * Apply a change in background state resulting from rematching networks with requests.
10289 *
10290 * During rematch, a network may change background states by starting to satisfy or stopping
10291 * to satisfy a foreground request. Listens don't count for this. When a network changes
10292 * background states, its capabilities need to be updated and callbacks fired for the
10293 * capability change.
10294 *
10295 * @param nai The network that changed background states
10296 */
10297 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10298 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10299 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10300 updateNetworkPermissions(nai, newNc);
10301 nai.getAndSetNetworkCapabilities(newNc);
10302 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10303 }
10304
Chalard Jeanf0344532019-11-19 19:23:38 +090010305 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010306 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010307 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010308 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10309 changes.getReassignment(mDefaultRequest);
10310 final NetworkAgentInfo oldDefaultNetwork =
10311 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10312 final NetworkAgentInfo newDefaultNetwork =
10313 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010314
Chalard Jean5b409c72021-02-04 13:12:59 +090010315 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010316 // Maintain the illusion : since the legacy API only understands one network at a time,
10317 // if the default network changed, apps should see a disconnected broadcast for the
10318 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010319 if (oldDefaultNetwork != null) {
10320 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10321 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010322 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010323 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010324 // The new default network can be newly null if and only if the old default
10325 // network doesn't satisfy the default request any more because it lost a
10326 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010327 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010328 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010329 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010330 }
10331 }
10332
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010333 // Now that all the callbacks have been sent, send the legacy network broadcasts
10334 // as needed. This is necessary so that legacy requests correctly bind dns
10335 // requests to this network. The legacy users are listening for this broadcast
10336 // and will generally do a dns request so they can ensureRouteToHost and if
10337 // they do that before the callbacks happen they'll use the default network.
10338 //
10339 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10340 // callbacks, but if apps can receive the broadcast before the callback, they still might
10341 // have an inconsistent view of networking.
10342 //
10343 // This *does* introduce a race where if the user uses the new api
10344 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10345 // they may get old info. Reverse this after the old startUsing api is removed.
10346 // This is on top of the multiple intent sequencing referenced in the todo above.
10347 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010348 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010349 addNetworkToLegacyTypeTracker(nai);
10350 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010351 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010352 }
10353
Chalard Jean0354d8c2021-01-12 10:58:56 +090010354 private void issueNetworkNeeds() {
10355 ensureRunningOnConnectivityServiceThread();
10356 for (final NetworkOfferInfo noi : mNetworkOffers) {
10357 issueNetworkNeeds(noi);
10358 }
10359 }
10360
10361 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10362 ensureRunningOnConnectivityServiceThread();
10363 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10364 informOffer(nri, noi.offer, mNetworkRanker);
10365 }
10366 }
10367
10368 /**
10369 * Inform a NetworkOffer about any new situation of a request.
10370 *
10371 * This function handles updates to offers. A number of events may happen that require
10372 * updating the registrant for this offer about the situation :
10373 * • The offer itself was updated. This may lead the offer to no longer being able
10374 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10375 * or conversely being strengthened enough to beat the satisfier (and therefore
10376 * start being needed)
10377 * • The network satisfying a request changed (including cases where the request
10378 * starts or stops being satisfied). The new network may be a stronger or weaker
10379 * match than the old one, possibly affecting whether the offer is needed.
10380 * • The network satisfying a request updated their score. This may lead the offer
10381 * to no longer be able to beat it if the current satisfier got better, or
10382 * conversely start being a good choice if the current satisfier got weaker.
10383 *
10384 * @param nri The request
10385 * @param offer The offer. This may be an updated offer.
10386 */
10387 private static void informOffer(@NonNull NetworkRequestInfo nri,
10388 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10389 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10390 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010391
10392 // Multi-layer requests have a currently active request, the one being satisfied.
10393 // Since the system will try to bring up a better network than is currently satisfying
10394 // the request, NetworkProviders need to be told the offers matching the requests *above*
10395 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10396 // not needed, and the offer is needed for the active request iff the offer can beat
10397 // the satisfier.
10398 // For non-multilayer requests, the logic above gracefully degenerates to only the
10399 // last case.
10400 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10401 // providers that the offer is needed for this request, until the active request is found.
10402 // In a second phase, deal with the currently active request. In a third phase, inform
10403 // the providers that offer is unneeded for the remaining requests.
10404
10405 // First phase : inform providers of all requests above the active request.
10406 int i;
10407 for (i = 0; nri.mRequests.size() > i; ++i) {
10408 final NetworkRequest request = nri.mRequests.get(i);
10409 if (activeRequest == request) break; // Found the active request : go to phase 2
10410 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10411 // Since this request is higher-priority than the one currently satisfied, if the
10412 // offer can satisfy it, the provider should try and bring up the network for sure ;
10413 // no need to even ask the ranker – an offer that can satisfy is always better than
10414 // no network. Hence tell the provider so unless it already knew.
10415 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10416 offer.onNetworkNeeded(request);
10417 }
10418 }
10419
10420 // Second phase : deal with the active request (if any)
10421 if (null != activeRequest && activeRequest.isRequest()) {
10422 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010423 // If an offer can satisfy the request, it is considered needed if it is currently
10424 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010425 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010426 && satisfier.factorySerialNumber == offer.providerId
10427 && activeRequest.canBeSatisfiedBy(offer.caps);
10428 final boolean newNeeded = currentlyServing
10429 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010430 if (newNeeded != oldNeeded) {
10431 if (newNeeded) {
10432 offer.onNetworkNeeded(activeRequest);
10433 } else {
10434 // The offer used to be able to beat the satisfier. Now it can't.
10435 offer.onNetworkUnneeded(activeRequest);
10436 }
10437 }
10438 }
10439
10440 // Third phase : inform the providers that the offer isn't needed for any request
10441 // below the active one.
10442 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10443 final NetworkRequest request = nri.mRequests.get(i);
10444 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10445 // Since this request is lower-priority than the one currently satisfied, if the
10446 // offer can satisfy it, the provider should not try and bring up the network.
10447 // Hence tell the provider so unless it already knew.
10448 if (offer.neededFor(request)) {
10449 offer.onNetworkUnneeded(request);
10450 }
10451 }
10452 }
10453
Chalard Jean61c79252019-11-07 23:07:32 +090010454 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10455 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10456 NetworkRequest nr = nai.requestAt(i);
10457 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10458 // legacy type tracker filters out repeat adds
10459 mLegacyTypeTracker.add(nr.legacyType, nai);
10460 }
10461 }
10462
10463 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010464 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010465 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10466 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10467 if (nai.isVPN()) {
10468 mLegacyTypeTracker.add(TYPE_VPN, nai);
10469 }
10470 }
10471
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010472 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010473 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010474 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010475 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010476 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010477 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010478
Chalard Jean254bd162022-08-25 13:04:51 +090010479 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010480 // Don't repeat publish.
10481 if (newInetCondition == mDefaultInetConditionPublished) return;
10482
10483 mDefaultInetConditionPublished = newInetCondition;
10484 sendInetConditionBroadcast(nai.networkInfo);
10485 }
10486
Chalard Jeand61375d2020-01-14 22:46:36 +090010487 @NonNull
10488 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10489 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010490 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010491 final boolean suspended =
10492 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10493 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10494 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10495 // state. This is because the network could have been suspended before connecting,
10496 // or it could be disconnecting while being suspended, and in both these cases
10497 // the state should not be overridden. Note that the only detailed state that
10498 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10499 // worry about multiple different substates of CONNECTED.
10500 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10501 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010502 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10503 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10504 // network agent is created, then goes to suspended, then goes out of suspended without
10505 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010506 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010507 ? NetworkInfo.DetailedState.CONNECTED
10508 : NetworkInfo.DetailedState.CONNECTING,
10509 info.getReason(),
10510 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010511 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010512 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010513 return newInfo;
10514 }
10515
10516 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10517 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10518
Erik Kline99f301b2017-02-15 19:59:17 +090010519 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010520 NetworkInfo oldInfo = null;
10521 synchronized (networkAgent) {
10522 oldInfo = networkAgent.networkInfo;
10523 networkAgent.networkInfo = newInfo;
10524 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010525
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010526 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010527 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10528 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010529 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010530
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010531 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010532 // A network that has just connected has zero requests and is thus a foreground network.
10533 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10534
Luke Huangfdd11f82019-04-09 18:41:49 +080010535 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010536
10537 networkAgent.setCreated();
10538
10539 // If the network is created immediately on register, then apply the LinkProperties now.
10540 // Otherwise, this is done further down when the network goes into connected state.
10541 // Applying the LinkProperties means that the network is ready to carry traffic -
10542 // interfaces and routing rules have been added, DNS servers programmed, etc.
10543 // For VPNs, this must be done before the capabilities are updated, because as soon as
10544 // that happens, UIDs are routed to the network.
10545 if (shouldCreateNetworksImmediately()) {
10546 applyInitialLinkProperties(networkAgent);
10547 }
10548
10549 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10550 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010551 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010552 // Initialize the network's capabilities to their starting values according to the
10553 // underlying networks. This ensures that the capabilities are correct before
10554 // anything happens to the network.
10555 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010556 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010557 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010558 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010559 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010560 }
10561
Chalard Jean254bd162022-08-25 13:04:51 +090010562 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10563 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010564
lucaslin45e639b2019-04-03 17:09:28 +080010565 // NetworkCapabilities need to be set before sending the private DNS config to
10566 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010567 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10568
Erik Kline9a62f012018-03-21 07:18:33 -070010569 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010570 if (!shouldCreateNetworksImmediately()) {
10571 applyInitialLinkProperties(networkAgent);
10572 } else {
10573 // The network was created when the agent registered, and the LinkProperties are
10574 // already up-to-date. However, updateLinkProperties also makes some changes only
10575 // when the network connects. Apply those changes here. On T and below these are
10576 // handled by the applyInitialLinkProperties call just above.
10577 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10578 // If something depends on both LinkProperties and connected state, it should be in
10579 // this method as well.
10580 networkAgent.clatd.update();
10581 updateProxy(networkAgent.linkProperties, null);
10582 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010583
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010584 // If a rate limit has been configured and is applicable to this network (network
10585 // provides internet connectivity), apply it. The tc police filter cannot be attached
10586 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010587 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010588 // Note: in case of a system server crash, the NetworkController constructor in netd
10589 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10590 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10591 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10592 mIngressRateLimit);
10593 }
10594
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010595 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10596 // command must be sent after updating LinkProperties to maximize chances of
10597 // NetworkMonitor seeing the correct LinkProperties when starting.
10598 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010599 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010600 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010601 }
Chalard Jeand4900722022-02-06 12:25:38 +090010602 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10603 params.networkAgentConfig = networkAgent.networkAgentConfig;
10604 params.networkCapabilities = networkAgent.networkCapabilities;
10605 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10606 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010607 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10608 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10609 // call that would cause a Log.wtf to be emitted from the system_server process, and
10610 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10611 // process to check the interface version, just use an SDK check. NetworkStack will
10612 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010613 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010614 networkAgent.networkMonitor().notifyNetworkConnected(params);
10615 } else {
10616 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10617 params.networkCapabilities);
10618 }
Chalard Jean0f141332023-06-05 19:26:17 +090010619 final long evaluationDelay;
10620 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10621 // If the network is anything other than pure wifi, use the default timeout.
10622 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10623 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10624 // If the network is explicitly selected, use the default timeout because it's
10625 // shorter and the user is likely staring at the screen expecting it to validate
10626 // right away.
10627 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10628 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10629 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10630 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10631 } else {
10632 // It's wifi, automatically connected, and bad wifi is preferred : use the
10633 // longer timeout to avoid the device switching to captive portals with bad
10634 // signal or very slow response.
10635 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10636 }
10637 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010638
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010639 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10640 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10641 // capabilities, so it only needs to be done once on initial connect, not every time the
10642 // network's capabilities change. Note that we do this before rematching the network,
10643 // so we could decide to tear it down immediately afterwards. That's fine though - on
10644 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10645 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010646 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010647
junyulai0ac374f2020-12-14 18:41:52 +080010648 // Before first rematching networks, put an inactivity timer without any request, this
10649 // allows {@code updateInactivityState} to update the state accordingly and prevent
10650 // tearing down for any {@code unneeded} evaluation in this period.
10651 // Note that the timer will not be rescheduled since the expiry time is
10652 // fixed after connection regardless of the network satisfying other requests or not.
10653 // But it will be removed as soon as the network satisfies a request for the first time.
10654 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10655 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010656 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010657
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010658 if (mTrackMultiNetworkActivities) {
10659 // Start tracking activity of this network.
10660 // This must be called before rematchAllNetworksAndRequests since the network
10661 // should be tracked when the network becomes the default network.
10662 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
10663 // can be triggered later if this network becomes the default network.
10664 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
10665 }
10666
Paul Jensen05e85ee2014-09-11 11:00:39 -040010667 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010668 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010669
10670 // This has to happen after matching the requests, because callbacks are just requests.
10671 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010672 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010673 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010674 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010675 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010676 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010677 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010678 if (networkAgent.isVPN()) {
10679 // As the active or bound network changes for apps, broadcast the default proxy, as
10680 // apps may need to update their proxy data. This is called after disconnecting from
10681 // VPN to make sure we do not broadcast the old proxy data.
10682 // TODO(b/122649188): send the broadcast only to VPN users.
10683 mProxyTracker.sendProxyBroadcast();
10684 }
Chalard Jean254bd162022-08-25 13:04:51 +090010685 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10686 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010687 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010688 }
10689 }
10690
Chalard Jean28018572020-12-21 18:36:52 +090010691 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010692 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10693 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010694 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010695 }
10696
Erik Kline99f301b2017-02-15 19:59:17 +090010697 // Notify only this one new request of the current state. Transfer all the
10698 // current state by calling NetworkCapabilities and LinkProperties callbacks
10699 // so that callers can be guaranteed to have as close to atomicity in state
10700 // transfer as can be supported by this current API.
10701 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010702 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010703 if (nri.mPendingIntent != null) {
10704 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10705 // Attempt no subsequent state pushes where intents are involved.
10706 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010707 }
Erik Kline99f301b2017-02-15 19:59:17 +090010708
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010709 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010710 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010711 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10712 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10713 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010714 }
10715
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010716 // Notify the requests on this NAI that the network is now lingered.
10717 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010718 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010719 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10720 }
10721
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010722 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10723 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10724 return vpnBlocked
10725 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10726 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10727 }
10728
10729 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10730 if (blockedReasons == BLOCKED_REASON_NONE) {
10731 mUidBlockedReasons.delete(uid);
10732 } else {
10733 mUidBlockedReasons.put(uid, blockedReasons);
10734 }
10735 }
10736
junyulaif2c67e42018-08-07 19:50:45 +080010737 /**
10738 * Notify of the blocked state apps with a registered callback matching a given NAI.
10739 *
10740 * Unlike other callbacks, blocked status is different between each individual uid. So for
10741 * any given nai, all requests need to be considered according to the uid who filed it.
10742 *
10743 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010744 * @param oldMetered True if the previous network capabilities were metered.
10745 * @param newMetered True if the current network capabilities are metered.
10746 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10747 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010748 */
10749 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010750 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10751 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010752
10753 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10754 NetworkRequest nr = nai.requestAt(i);
10755 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010756
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010757 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10758 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10759 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010760 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010761 : oldVpnBlocked;
10762
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010763 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10764 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10765 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010766 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010767 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010768 }
10769 }
10770 }
10771
10772 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010773 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010774 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010775 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010776 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010777 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010778 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010779 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010780 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010781
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010782 final int oldBlockedState = getBlockedState(
10783 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10784 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10785 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010786 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010787 }
junyulaif2c67e42018-08-07 19:50:45 +080010788 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10789 NetworkRequest nr = nai.requestAt(i);
10790 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010791 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010792 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10793 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010794 }
10795 }
10796 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010797 }
10798
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010799 @VisibleForTesting
10800 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010801 // The NetworkInfo we actually send out has no bearing on the real
10802 // state of affairs. For example, if the default connection is mobile,
10803 // and a request for HIPRI has just gone away, we need to pretend that
10804 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10805 // the state to DISCONNECTED, even though the network is of type MOBILE
10806 // and is still connected.
10807 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10808 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010809 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010810 if (state != DetailedState.DISCONNECTED) {
10811 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010812 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010813 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010814 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010815 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10816 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10817 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10818 if (info.isFailover()) {
10819 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10820 nai.networkInfo.setFailover(false);
10821 }
10822 if (info.getReason() != null) {
10823 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10824 }
10825 if (info.getExtraInfo() != null) {
10826 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10827 }
10828 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010829 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010830 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010831 if (newDefaultAgent != null) {
10832 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10833 newDefaultAgent.networkInfo);
10834 } else {
10835 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10836 }
10837 }
10838 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10839 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010840 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010841 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010842 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010843 }
10844 }
10845 }
10846
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010847 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010848 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010849 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010850 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010851 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010852 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10853 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010854 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10855 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010856 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010857 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010858 } else {
10859 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10860 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010861 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010862 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010863
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010864 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10865 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10866 }
10867
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010868 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010869 * Returns the list of all interfaces that could be used by network traffic that does not
10870 * explicitly specify a network. This includes the default network, but also all VPNs that are
10871 * currently connected.
10872 *
10873 * Must be called on the handler thread.
10874 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010875 @NonNull
10876 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010877 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010878 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010879 final Set<Integer> activeNetIds = new ArraySet<>();
10880 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10881 if (nri.isBeingSatisfied()) {
10882 activeNetIds.add(nri.getSatisfier().network().netId);
10883 }
10884 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010885 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010886 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010887 defaultNetworks.add(nai.network);
10888 }
10889 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010890 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010891 }
10892
10893 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010894 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10895 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010896 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010897 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010898 ensureRunningOnConnectivityServiceThread();
10899 String activeIface = null;
10900 LinkProperties activeLinkProperties = getActiveLinkProperties();
10901 if (activeLinkProperties != null) {
10902 activeIface = activeLinkProperties.getInterfaceName();
10903 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010904
junyulai2050bed2021-01-23 09:46:34 +080010905 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010906 try {
junyulaide41fc22021-01-22 22:46:01 +080010907 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010908 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010909 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10910 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010911 } catch (Exception ignored) {
10912 }
10913 }
10914
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010915 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010916 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010917 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010918 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010919 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010920
10921 if (!TextUtils.isEmpty(settingUrl)) {
10922 return settingUrl;
10923 }
10924
10925 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010926 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010927 if (!TextUtils.isEmpty(settingUrl)) {
10928 return settingUrl;
10929 }
10930
10931 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010932 }
10933
10934 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010935 public void startNattKeepalive(Network network, int intervalSeconds,
10936 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010937 enforceKeepalivePermission();
10938 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010939 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010940 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10941 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010942 // false and set the underpinned network to null because there is no way and no
10943 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10944 // deprecated method.
10945 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010946 }
10947
10948 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010949 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010950 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010951 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010952 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010953 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010954 mKeepaliveTracker.startNattKeepalive(
10955 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010956 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10957 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010958 } finally {
10959 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10960 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010961 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10962 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010963 }
10964 }
junyulaid05a1922019-01-15 11:32:44 +080010965 }
10966
10967 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010968 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010969 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010970 try {
10971 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010972 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010973 mKeepaliveTracker.startTcpKeepalive(
10974 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10975 } finally {
10976 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10977 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010978 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10979 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010980 }
10981 }
junyulai0835a1e2019-01-08 20:04:33 +080010982 }
10983
10984 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010985 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010986 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010987 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10988 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010989 }
10990
10991 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010992 public int[] getSupportedKeepalives() {
10993 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10994 // Backwards compatibility with CTS 13
10995 android.Manifest.permission.QUERY_ALL_PACKAGES);
10996
10997 return BinderUtils.withCleanCallingIdentity(() ->
10998 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10999 }
11000
11001 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070011002 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080011003 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070011004
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011005 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080011006 final long token = Binder.clearCallingIdentity();
11007 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011008 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
11009 UserHandle.getUserHandleForUid(uid))) {
11010 return;
11011 }
11012
Heemin Seogdb8489d2019-06-12 09:21:44 -070011013 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
11014 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011015
11016 // Turn airplane mode off
11017 setAirplaneMode(false);
11018
11019 // restore private DNS settings to default mode (opportunistic)
11020 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
11021 UserHandle.getUserHandleForUid(uid))) {
11022 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
11023 PRIVATE_DNS_MODE_OPPORTUNISTIC);
11024 }
11025
11026 Settings.Global.putString(mContext.getContentResolver(),
11027 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080011028 } finally {
11029 Binder.restoreCallingIdentity(token);
11030 }
Stuart Scottd5463642015-04-02 18:00:02 -070011031 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040011032
Ricky Wai7097cc92018-01-23 04:09:45 +000011033 @Override
11034 public byte[] getNetworkWatchlistConfigHash() {
11035 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
11036 if (nwm == null) {
11037 loge("Unable to get NetworkWatchlistManager");
11038 return null;
11039 }
11040 // Redirect it to network watchlist service to access watchlist file and calculate hash.
11041 return nwm.getWatchlistConfigHash();
11042 }
11043
Hugo Benichibe0c7652016-05-31 16:28:06 +090011044 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090011045 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080011046 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090011047 }
Hugo Benichif4210292017-04-21 15:07:12 +090011048
11049 private static boolean toBool(int encodedBoolean) {
11050 return encodedBoolean != 0; // Only 0 means false.
11051 }
11052
11053 private static int encodeBool(boolean b) {
11054 return b ? 1 : 0;
11055 }
mswest4632928412018-03-12 10:34:34 -070011056
11057 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011058 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
11059 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
11060 @NonNull String[] args) {
11061 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
11062 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070011063 }
11064
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011065 private Boolean parseBooleanArgument(final String arg) {
11066 if ("true".equals(arg)) {
11067 return true;
11068 } else if ("false".equals(arg)) {
11069 return false;
11070 } else {
11071 return null;
11072 }
11073 }
11074
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011075 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070011076 @Override
11077 public int onCommand(String cmd) {
11078 if (cmd == null) {
11079 return handleDefaultCommands(cmd);
11080 }
11081 final PrintWriter pw = getOutPrintWriter();
11082 try {
11083 switch (cmd) {
11084 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011085 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11086 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011087 final String action = getNextArg();
11088 if ("enable".equals(action)) {
11089 setAirplaneMode(true);
11090 return 0;
11091 } else if ("disable".equals(action)) {
11092 setAirplaneMode(false);
11093 return 0;
11094 } else if (action == null) {
11095 final ContentResolver cr = mContext.getContentResolver();
11096 final int enabled = Settings.Global.getInt(cr,
11097 Settings.Global.AIRPLANE_MODE_ON);
11098 pw.println(enabled == 0 ? "disabled" : "enabled");
11099 return 0;
11100 } else {
11101 onHelp();
11102 return -1;
11103 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011104 case "set-chain3-enabled": {
11105 final Boolean enabled = parseBooleanArgument(getNextArg());
11106 if (null == enabled) {
11107 onHelp();
11108 return -1;
11109 }
11110 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11111 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11112 enabled);
11113 return 0;
11114 }
11115 case "get-chain3-enabled": {
11116 final boolean chainEnabled = getFirewallChainEnabled(
11117 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11118 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11119 return 0;
11120 }
11121 case "set-package-networking-enabled": {
11122 final Boolean enabled = parseBooleanArgument(getNextArg());
11123 final String packageName = getNextArg();
11124 if (null == enabled || null == packageName) {
11125 onHelp();
11126 return -1;
11127 }
11128 // Throws NameNotFound if the package doesn't exist.
11129 final int appId = setPackageFirewallRule(
11130 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11131 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11132 final String msg = (enabled ? "Enabled" : "Disabled")
11133 + " networking for " + packageName + ", appId " + appId;
11134 Log.i(TAG, msg);
11135 pw.println(msg);
11136 return 0;
11137 }
11138 case "get-package-networking-enabled": {
11139 final String packageName = getNextArg();
11140 final int rule = getPackageFirewallRule(
11141 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11142 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11143 pw.println(packageName + ":" + "allow");
11144 } else if (FIREWALL_RULE_DENY == rule) {
11145 pw.println(packageName + ":" + "deny");
11146 } else {
11147 throw new IllegalStateException("Unknown rule " + rule + " for package "
11148 + packageName);
11149 }
11150 return 0;
11151 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011152 case "reevaluate":
11153 // Usage : adb shell cmd connectivity reevaluate <netId>
11154 // If netId is omitted, then reevaluate the default network
11155 final String netId = getNextArg();
11156 final NetworkAgentInfo nai;
11157 if (null == netId) {
11158 // Note that the command is running on the wrong thread to call this,
11159 // so this could in principle return stale data. But it can't crash.
11160 nai = getDefaultNetwork();
11161 } else {
11162 // If netId can't be parsed, this throws NumberFormatException, which
11163 // is passed back to adb who prints it.
11164 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11165 }
11166 if (null == nai) {
11167 pw.println("Unknown network (net ID not found or no default network)");
11168 return 0;
11169 }
11170 Log.d(TAG, "Reevaluating network " + nai.network);
11171 reportNetworkConnectivity(nai.network, !nai.isValidated());
11172 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011173 case "bpf-get-cgroup-program-id": {
11174 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11175 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11176 // for more detail.
11177 // If type can't be parsed, this throws NumberFormatException, which
11178 // is passed back to adb who prints it.
11179 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011180 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011181 pw.println(ret);
11182 return 0;
11183 }
mswest4632928412018-03-12 10:34:34 -070011184 default:
11185 return handleDefaultCommands(cmd);
11186 }
11187 } catch (Exception e) {
11188 pw.println(e);
11189 }
11190 return -1;
11191 }
11192
11193 @Override
11194 public void onHelp() {
11195 PrintWriter pw = getOutPrintWriter();
11196 pw.println("Connectivity service commands:");
11197 pw.println(" help");
11198 pw.println(" Print this help text.");
11199 pw.println(" airplane-mode [enable|disable]");
11200 pw.println(" Turn airplane mode on or off.");
11201 pw.println(" airplane-mode");
11202 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011203 pw.println(" set-chain3-enabled [true|false]");
11204 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11205 pw.println(" get-chain3-enabled");
11206 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11207 pw.println(" set-package-networking-enabled [true|false] [package name]");
11208 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11209 + " no effect if the chain is disabled.");
11210 pw.println(" get-package-networking-enabled [package name]");
11211 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011212 }
11213 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011214
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011215 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011216 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11217 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11218 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011219 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011220 }
11221
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011222 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11223 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011224 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11225 final TransportInfo newInfo = nc.getTransportInfo();
11226 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11227 return;
11228 }
11229 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011230 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011231 }
11232 }
11233
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011234 /**
11235 * @param connectionInfo the connection to resolve.
11236 * @return {@code uid} if the connection is found and the app has permission to observe it
11237 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11238 * connection is not found.
11239 */
11240 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011241 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11242 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11243 }
11244
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011245 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011246 connectionInfo.local, connectionInfo.remote);
11247
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011248 if (uid == INVALID_UID) return uid; // Not found.
11249
11250 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11251 // VPN, if any, that applies to the UID that owns the connection.
11252 if (checkNetworkStackPermission()) return uid;
11253
11254 final NetworkAgentInfo vpn = getVpnForUid(uid);
11255 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011256 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011257 return INVALID_UID;
11258 }
11259
11260 return uid;
11261 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011262
Benedict Wong493e04b2018-11-09 14:45:34 -080011263 /**
11264 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11265 *
11266 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11267 */
11268 @Override
11269 public IBinder startOrGetTestNetworkService() {
11270 synchronized (mTNSLock) {
11271 TestNetworkService.enforceTestNetworkPermissions(mContext);
11272
11273 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011274 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011275 }
11276
11277 return mTNS;
11278 }
11279 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011280
Cody Kesting73708bf2019-12-18 10:57:50 -080011281 /**
11282 * Handler used for managing all Connectivity Diagnostics related functions.
11283 *
11284 * @see android.net.ConnectivityDiagnosticsManager
11285 *
11286 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11287 */
11288 @VisibleForTesting
11289 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011290 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11291
Cody Kesting73708bf2019-12-18 10:57:50 -080011292 /**
11293 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11294 * android.net.ConnectivityDiagnosticsManager}.
11295 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11296 * NetworkRequestInfo to be registered
11297 */
11298 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11299
11300 /**
11301 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11302 * android.net.ConnectivityDiagnosticsManager}.
11303 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11304 * arg1 = the uid of the caller
11305 */
11306 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11307
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011308 /**
11309 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011310 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011311 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11312 * NetworkMonitor.
11313 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011314 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011315 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011316
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011317 /**
11318 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11319 * been detected on the network.
11320 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11321 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11322 * arg2 = NetID.
11323 * data = PersistableBundle of extras passed from NetworkMonitor.
11324 */
11325 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11326
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011327 /**
11328 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11329 * the platform. This event will invoke {@link
11330 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11331 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011332 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011333 */
11334 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11335
Cody Kesting73708bf2019-12-18 10:57:50 -080011336 private ConnectivityDiagnosticsHandler(Looper looper) {
11337 super(looper);
11338 }
11339
11340 @Override
11341 public void handleMessage(Message msg) {
11342 switch (msg.what) {
11343 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11344 handleRegisterConnectivityDiagnosticsCallback(
11345 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11346 break;
11347 }
11348 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11349 handleUnregisterConnectivityDiagnosticsCallback(
11350 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11351 break;
11352 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011353 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011354 final ConnectivityReportEvent reportEvent =
11355 (ConnectivityReportEvent) msg.obj;
11356
Aaron Huang959d3642021-01-21 15:47:41 +080011357 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011358 break;
11359 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011360 case EVENT_DATA_STALL_SUSPECTED: {
11361 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011362 final Pair<Long, PersistableBundle> arg =
11363 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011364 if (nai == null) break;
11365
Aaron Huang959d3642021-01-21 15:47:41 +080011366 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011367 break;
11368 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011369 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011370 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011371 break;
11372 }
11373 default: {
11374 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11375 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011376 }
11377 }
11378 }
11379
11380 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11381 @VisibleForTesting
11382 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11383 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11384 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011385 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011386
11387 @VisibleForTesting
11388 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011389 @NonNull IConnectivityDiagnosticsCallback cb,
11390 @NonNull NetworkRequestInfo nri,
11391 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011392 mCb = cb;
11393 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011394 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011395 }
11396
11397 @Override
11398 public void binderDied() {
11399 log("ConnectivityDiagnosticsCallback IBinder died.");
11400 unregisterConnectivityDiagnosticsCallback(mCb);
11401 }
11402 }
11403
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011404 /**
11405 * Class used for sending information from {@link
11406 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11407 */
11408 private static class NetworkTestedResults {
11409 private final int mNetId;
11410 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011411 @Nullable private final String mRedirectUrl;
11412
11413 private NetworkTestedResults(
11414 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11415 mNetId = netId;
11416 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011417 mRedirectUrl = redirectUrl;
11418 }
11419 }
11420
11421 /**
11422 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11423 * ConnectivityDiagnosticsHandler}.
11424 */
11425 private static class ConnectivityReportEvent {
11426 private final long mTimestampMillis;
11427 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011428 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011429
Aaron Huang959d3642021-01-21 15:47:41 +080011430 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11431 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011432 mTimestampMillis = timestampMillis;
11433 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011434 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011435 }
11436 }
11437
Cody Kestingf1120be2020-08-03 18:01:40 -070011438 /**
11439 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11440 * ConnectivityDiagnosticsHandler}.
11441 */
11442 private static class ReportedNetworkConnectivityInfo {
11443 public final boolean hasConnectivity;
11444 public final boolean isNetworkRevalidating;
11445 public final int reporterUid;
11446 @NonNull public final NetworkAgentInfo nai;
11447
11448 private ReportedNetworkConnectivityInfo(
11449 boolean hasConnectivity,
11450 boolean isNetworkRevalidating,
11451 int reporterUid,
11452 @NonNull NetworkAgentInfo nai) {
11453 this.hasConnectivity = hasConnectivity;
11454 this.isNetworkRevalidating = isNetworkRevalidating;
11455 this.reporterUid = reporterUid;
11456 this.nai = nai;
11457 }
11458 }
11459
Cody Kesting73708bf2019-12-18 10:57:50 -080011460 private void handleRegisterConnectivityDiagnosticsCallback(
11461 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11462 ensureRunningOnConnectivityServiceThread();
11463
11464 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011465 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011466 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11467
James Mattis64b8b0f2020-11-24 17:40:49 -080011468 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11469 // confusing for these networks to change when an NRI is satisfied in another layer.
11470 if (nri.isMultilayerRequest()) {
11471 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11472 + "network requests.");
11473 }
11474
Cody Kesting73708bf2019-12-18 10:57:50 -080011475 // This means that the client registered the same callback multiple times. Do
11476 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011477 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011478 if (VDBG) log("Diagnostics callback is already registered");
11479
11480 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11481 // incremented when the NetworkRequestInfo is created as part of
11482 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011483 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011484 return;
11485 }
11486
Cody Kesting31f1ff62020-03-05 10:46:02 -080011487 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011488
11489 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011490 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011491 } catch (RemoteException e) {
11492 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011493 return;
11494 }
11495
11496 // Once registered, provide ConnectivityReports for matching Networks
11497 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11498 synchronized (mNetworkForNetId) {
11499 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11500 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011501 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11502 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011503 matchingNetworks.add(nai);
11504 }
11505 }
11506 }
11507 for (final NetworkAgentInfo nai : matchingNetworks) {
11508 final ConnectivityReport report = nai.getConnectivityReport();
11509 if (report == null) {
11510 continue;
11511 }
11512 if (!checkConnectivityDiagnosticsPermissions(
11513 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11514 continue;
11515 }
11516
11517 try {
11518 cb.onConnectivityReportAvailable(report);
11519 } catch (RemoteException e) {
11520 // Exception while sending the ConnectivityReport. Move on to the next network.
11521 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011522 }
11523 }
11524
11525 private void handleUnregisterConnectivityDiagnosticsCallback(
11526 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11527 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011528 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011529
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011530 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11531 mConnectivityDiagnosticsCallbacks.remove(iCb);
11532 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011533 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11534 return;
11535 }
11536
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011537 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011538
Cody Kesting70fa2b22020-12-02 12:16:56 -080011539 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11540 // (if the Binder died)
11541 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11542 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011543 return;
11544 }
11545
Cody Kesting46cb1672020-03-04 13:35:20 -080011546 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11547 // incremented when the NetworkRequestInfo is created as part of
11548 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011549 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011550
Cody Kesting31f1ff62020-03-05 10:46:02 -080011551 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011552 }
11553
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011554 private void handleNetworkTestedWithExtras(
11555 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11556 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011557 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011558 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011559 final ConnectivityReport report =
11560 new ConnectivityReport(
11561 reportEvent.mNai.network,
11562 reportEvent.mTimestampMillis,
11563 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011564 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011565 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011566 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011567
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011568 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011569 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011570 for (final IConnectivityDiagnosticsCallback cb : results) {
11571 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011572 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011573 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011574 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011575 }
11576 }
11577 }
11578
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011579 private void handleDataStallSuspected(
11580 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11581 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011582 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011583 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011584 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011585 new DataStallReport(
11586 nai.network,
11587 timestampMillis,
11588 detectionMethod,
11589 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011590 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011591 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011592 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011593 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011594 for (final IConnectivityDiagnosticsCallback cb : results) {
11595 try {
11596 cb.onDataStallSuspected(report);
11597 } catch (RemoteException ex) {
11598 loge("Error invoking onDataStallSuspected", ex);
11599 }
11600 }
11601 }
11602
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011603 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011604 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11605 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11606 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11607
11608 // If the Network is being re-validated as a result of this call to
11609 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11610 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011611 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011612 getMatchingPermissionedCallbacks(
11613 nai,
11614 reportedNetworkConnectivityInfo.isNetworkRevalidating
11615 ? Process.INVALID_UID
11616 : reportedNetworkConnectivityInfo.reporterUid);
11617
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011618 for (final IConnectivityDiagnosticsCallback cb : results) {
11619 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011620 cb.onNetworkConnectivityReported(
11621 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011622 } catch (RemoteException ex) {
11623 loge("Error invoking onNetworkConnectivityReported", ex);
11624 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011625
11626 // If the Network isn't re-validating, also provide the cached report. If there is no
11627 // cached report, the Network is still being validated and a report will be sent once
11628 // validation is complete. Note that networks which never undergo validation will still
11629 // have a cached ConnectivityReport with RESULT_SKIPPED.
11630 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11631 try {
11632 cb.onConnectivityReportAvailable(cachedReport);
11633 } catch (RemoteException ex) {
11634 loge("Error invoking onConnectivityReportAvailable", ex);
11635 }
11636 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011637 }
11638 }
11639
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011640 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011641 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11642 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011643 sanitized.setUids(null);
11644 sanitized.setAdministratorUids(new int[0]);
11645 sanitized.setOwnerUid(Process.INVALID_UID);
11646 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011647 }
11648
Cody Kestingf1120be2020-08-03 18:01:40 -070011649 /**
11650 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11651 *
11652 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11653 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011654 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011655 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011656 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011657 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011658 mConnectivityDiagnosticsCallbacks.entrySet()) {
11659 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11660 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011661
James Mattis64b8b0f2020-11-24 17:40:49 -080011662 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011663 if (!nai.satisfies(nri.mRequests.get(0))) {
11664 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011665 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011666
11667 // UID for this callback must either be:
11668 // - INVALID_UID (which sends callbacks to all UIDs), or
11669 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11670 // notified as a result)
11671 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11672 continue;
11673 }
11674
11675 if (!checkConnectivityDiagnosticsPermissions(
11676 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11677 continue;
11678 }
11679
11680 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011681 }
11682 return results;
11683 }
11684
Cody Kesting7474f672021-05-11 14:22:40 -070011685 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11686 @NonNull NetworkAgentInfo nai) {
11687 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11688 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11689 }
11690
Cody Kesting160ef392021-05-05 13:17:22 -070011691 private boolean hasLocationPermission(String packageName, int uid) {
11692 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11693 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11694 // call in a try-catch.
11695 try {
11696 if (!mLocationPermissionChecker.checkLocationPermission(
11697 packageName, null /* featureId */, uid, null /* message */)) {
11698 return false;
11699 }
11700 } catch (SecurityException e) {
11701 return false;
11702 }
11703
11704 return true;
11705 }
11706
11707 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11708 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011709 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011710 && virtual.networkCapabilities.getOwnerUid() == uid
11711 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11712 return true;
11713 }
11714 }
11715
11716 return false;
11717 }
11718
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011719 @VisibleForTesting
11720 boolean checkConnectivityDiagnosticsPermissions(
11721 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11722 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11723 return true;
11724 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011725 if (mAllowSysUiConnectivityReports
Chris Göllnercc962022023-12-26 09:55:32 +000011726 && checkSystemBarServicePermission(callbackPid, callbackUid)) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011727 return true;
11728 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011729
Cody Kesting160ef392021-05-05 13:17:22 -070011730 // Administrator UIDs also contains the Owner UID
11731 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11732 if (!CollectionUtils.contains(administratorUids, callbackUid)
11733 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011734 return false;
11735 }
11736
Cody Kesting7474f672021-05-11 14:22:40 -070011737 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11738 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011739 }
11740
Cody Kestingd199a9d2019-12-17 12:55:28 -080011741 @Override
11742 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011743 @NonNull IConnectivityDiagnosticsCallback callback,
11744 @NonNull NetworkRequest request,
11745 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011746 Objects.requireNonNull(callback, "callback must not be null");
11747 Objects.requireNonNull(request, "request must not be null");
11748 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11749
Cody Kesting73708bf2019-12-18 10:57:50 -080011750 if (request.legacyType != TYPE_NONE) {
11751 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11752 + " Please use NetworkCapabilities instead.");
11753 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011754 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011755 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011756
11757 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11758 // and administrator uids to be safe.
11759 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011760 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011761
11762 final NetworkRequest requestWithId =
11763 new NetworkRequest(
11764 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11765
11766 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11767 //
11768 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11769 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11770 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011771 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011772 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011773 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011774
11775 mConnectivityDiagnosticsHandler.sendMessage(
11776 mConnectivityDiagnosticsHandler.obtainMessage(
11777 ConnectivityDiagnosticsHandler
11778 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11779 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011780 }
11781
11782 @Override
11783 public void unregisterConnectivityDiagnosticsCallback(
11784 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011785 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011786 mConnectivityDiagnosticsHandler.sendMessage(
11787 mConnectivityDiagnosticsHandler.obtainMessage(
11788 ConnectivityDiagnosticsHandler
11789 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011790 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011791 0,
11792 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011793 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011794
Yan Yanfe96dde2022-12-05 23:00:01 +000011795 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11796 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11797 if (underlyingNetworks == null) return false;
11798
11799 for (Network network : underlyingNetworks) {
11800 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11801 return true;
11802 }
11803 }
11804 return false;
11805 }
11806
Cody Kestingf53a0752020-04-15 12:33:28 -070011807 @Override
11808 public void simulateDataStall(int detectionMethod, long timestampMillis,
11809 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011810 Objects.requireNonNull(network, "network must not be null");
11811 Objects.requireNonNull(extras, "extras must not be null");
11812
paulhu3ffffe72021-09-16 10:15:22 +080011813 enforceAnyPermissionOf(mContext,
11814 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011815 android.Manifest.permission.NETWORK_STACK);
11816 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011817 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11818 throw new SecurityException(
11819 "Data Stall simulation is only possible for test networks or networks built on"
11820 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011821 }
11822
11823 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011824 if (nai == null
11825 || (nai.creatorUid != mDeps.getCallingUid()
11826 && nai.creatorUid != Process.SYSTEM_UID)) {
11827 throw new SecurityException(
11828 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011829 }
11830
Cody Kesting652e3ec2020-05-21 12:08:21 -070011831 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11832 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11833 // Data Stall information as a DataStallReportParcelable and passing to
11834 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11835 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011836 final DataStallReportParcelable p = new DataStallReportParcelable();
11837 p.timestampMillis = timestampMillis;
11838 p.detectionMethod = detectionMethod;
11839
11840 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11841 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11842 }
11843 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11844 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11845 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11846 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11847 }
11848
Serik Beketayevec8ad212020-12-07 22:43:07 -080011849 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011850 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011851
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011852 /**
11853 * Class to hold the information for network activity change event from idle timers
11854 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11855 */
11856 private static final class NetworkActivityParams {
11857 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011858 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
11859 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011860 public final int label;
11861 public final long timestampNs;
11862 // Uid represents the uid that was responsible for waking the radio.
11863 // -1 for no uid and uid is -1 if isActive is false.
11864 public final int uid;
11865
11866 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11867 this.isActive = isActive;
11868 this.label = label;
11869 this.timestampNs = timestampNs;
11870 this.uid = uid;
11871 }
11872 }
11873
lucaslin66f44212021-02-23 01:12:55 +080011874 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11875 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011876 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011877 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011878 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11879 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011880 }
lucaslin37a16d92021-01-21 19:48:09 +080011881
11882 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011883 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011884 mHandler.post(() -> {
11885 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011886 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011887 }
11888 });
lucaslin37a16d92021-01-21 19:48:09 +080011889 }
11890
11891 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011892 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011893 mHandler.post(() -> {
11894 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011895 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011896 }
11897 });
lucaslin66f44212021-02-23 01:12:55 +080011898 }
11899 }
11900
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011901 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080011902 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11903
11904 /**
11905 * Class used for updating network activity tracking with netd and notify network activity
11906 * changes.
11907 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011908 @VisibleForTesting
11909 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011910 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011911 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011912 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011913 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011914 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11915 new RemoteCallbackList<>();
11916 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011917 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011918 // If there is no default network, default network is considered active to keep the existing
11919 // behavior. Initial value is used until first connect to the default network.
11920 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011921 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011922 // Key is netId. Value is configured idle timer information.
11923 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011924 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011925 // Store netIds of Wi-Fi networks whose idletimers report that they are active
11926 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
11927 // Store netIds of cellular networks whose idletimers report that they are active
11928 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011929
Chalard Jean46bfbf02022-02-02 00:56:25 +090011930 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011931 public final int timeout;
11932 public final int transportType;
11933
11934 IdleTimerParams(int timeout, int transport) {
11935 this.timeout = timeout;
11936 this.transportType = transport;
11937 }
11938 }
11939
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011940 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011941 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011942 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011943 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011944 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011945 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011946 }
11947
11948 private void ensureRunningOnConnectivityServiceThread() {
11949 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11950 throw new IllegalStateException("Not running on ConnectivityService thread: "
11951 + Thread.currentThread().getName());
11952 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011953 }
11954
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011955 /**
11956 * Update network activity and call BatteryStats to update radio power state if the
11957 * mobile or Wi-Fi activity is changed.
11958 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
11959 * mobile network is active since BatteryStatsService only maintains a single power state
11960 * for the mobile network.
11961 * The Wi-Fi network is also the same.
11962 *
11963 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
11964 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
11965 * transports.
11966 */
11967 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
11968 final boolean isActive, final int uid) {
11969 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
11970 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
11971 + transportType);
11972 return;
11973 }
11974 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
11975 ? mActiveWifiNetworks : mActiveCellularNetworks;
11976
11977 final boolean wasEmpty = activeNetworks.isEmpty();
11978 if (isActive) {
11979 activeNetworks.add(netId);
11980 } else {
11981 activeNetworks.remove(netId);
11982 }
11983
11984 if (wasEmpty != activeNetworks.isEmpty()) {
11985 updateRadioPowerState(isActive, transportType, uid);
11986 }
11987 }
11988
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011989 private void handleDefaultNetworkActivity(final int transportType,
11990 final boolean isActive, final long timestampNs) {
11991 mIsDefaultNetworkActive = isActive;
11992 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
11993 isActive, timestampNs);
11994 if (isActive) {
11995 reportNetworkActive();
11996 }
11997 }
11998
11999 private void handleReportNetworkActivityWithNetIdLabel(
12000 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012001 final int netId = activityParams.label;
12002 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012003 if (idleTimerParams == null) {
12004 // This network activity change is not tracked anymore
12005 // This can happen if netd callback post activity change event message but idle
12006 // timer is removed before processing this message.
12007 return;
12008 }
12009 // TODO: if a network changes transports, storing the transport type in the
12010 // IdleTimerParams is not correct. Consider getting it from the network's
12011 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012012 final int transportType = idleTimerParams.transportType;
12013 maybeUpdateRadioPowerState(netId, transportType,
12014 activityParams.isActive, activityParams.uid);
12015
12016 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
12017 // This activity change is not for the default network.
12018 return;
12019 }
12020
12021 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012022 activityParams.timestampNs);
12023 }
12024
12025 private void handleReportNetworkActivityWithTransportTypeLabel(
12026 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012027 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012028 // This activity change is not for the current default network.
12029 // This can happen if netd callback post activity change event message but
12030 // the default network is lost before processing this message.
12031 return;
12032 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012033 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
12034 activityParams.timestampNs);
12035 }
12036
12037 /**
12038 * Handle network activity change
12039 */
12040 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
12041 ensureRunningOnConnectivityServiceThread();
12042 if (mTrackMultiNetworkActivities) {
12043 handleReportNetworkActivityWithNetIdLabel(activityParams);
12044 } else {
12045 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080012046 }
12047 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012048
lucaslin1193a5d2021-01-21 02:04:15 +080012049 private void reportNetworkActive() {
12050 final int length = mNetworkActivityListeners.beginBroadcast();
12051 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
12052 try {
12053 for (int i = 0; i < length; i++) {
12054 try {
12055 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
12056 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012057 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080012058 }
12059 }
12060 } finally {
12061 mNetworkActivityListeners.finishBroadcast();
12062 }
12063 }
12064
lucaslin1a8b4c62021-01-21 02:02:55 +080012065 // This is deprecated and only to support legacy use cases.
12066 private int transportTypeToLegacyType(int type) {
12067 switch (type) {
12068 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012069 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080012070 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012071 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080012072 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012073 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080012074 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012075 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080012076 default:
12077 loge("Unexpected transport in transportTypeToLegacyType: " + type);
12078 }
12079 return ConnectivityManager.TYPE_NONE;
12080 }
12081
12082 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12083 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12084 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12085 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12086 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12087 final long ident = Binder.clearCallingIdentity();
12088 try {
12089 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12090 RECEIVE_DATA_ACTIVITY_CHANGE,
12091 null /* resultReceiver */,
12092 null /* scheduler */,
12093 0 /* initialCode */,
12094 null /* initialData */,
12095 null /* initialExtra */);
12096 } finally {
12097 Binder.restoreCallingIdentity(ident);
12098 }
12099 }
12100
12101 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012102 * Get idle timer label
12103 */
12104 @VisibleForTesting
12105 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12106 final int netId, final int transportType) {
12107 return trackMultiNetworkActivities ? netId : transportType;
12108 }
12109
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012110 private boolean maybeCreateIdleTimer(
12111 String iface, int netId, int timeout, int transportType) {
12112 if (timeout <= 0 || iface == null) return false;
12113 try {
12114 final String label = Integer.toString(getIdleTimerLabel(
12115 mTrackMultiNetworkActivities, netId, transportType));
12116 mNetd.idletimerAddInterface(iface, timeout, label);
12117 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12118 return true;
12119 } catch (Exception e) {
12120 loge("Exception in createIdleTimer", e);
12121 return false;
12122 }
12123 }
12124
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012125 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012126 * Setup data activity tracking for the given network.
12127 *
12128 * Every {@code setupDataActivityTracking} should be paired with a
12129 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012130 *
12131 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012132 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012133 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012134 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012135 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012136 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012137
12138 final int timeout;
12139 final int type;
12140
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012141 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12142 // Do not track VPN network.
12143 return false;
12144 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012145 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12146 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012147 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012148 10);
12149 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12150 } else if (networkAgent.networkCapabilities.hasTransport(
12151 NetworkCapabilities.TRANSPORT_WIFI)) {
12152 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012153 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012154 15);
12155 type = NetworkCapabilities.TRANSPORT_WIFI;
12156 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012157 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012158 }
12159
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012160 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12161 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12162 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12163 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12164 // state only about a network that has an idletimer.
12165 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012166 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012167 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012168 }
12169
12170 /**
12171 * Remove data activity tracking when network disconnects.
12172 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012173 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12174 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012175 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012176 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012177 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12178
lucaslinb961efc2021-01-21 02:03:17 +080012179 if (iface == null) return;
12180
12181 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012182 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12183 // Do not track VPN network.
12184 return;
12185 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012186 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12187 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12188 type = NetworkCapabilities.TRANSPORT_WIFI;
12189 } else {
12190 return; // do not track any other networks
12191 }
12192
12193 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012194 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012195 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012196 if (params == null) {
12197 // IdleTimer is not added if the configured timeout is 0 or negative value
12198 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012199 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012200 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012201 final String label = Integer.toString(getIdleTimerLabel(
12202 mTrackMultiNetworkActivities, netId, params.transportType));
12203 // The call fails silently if no idle timer setup for this interface
12204 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012205 } catch (Exception e) {
12206 // You shall not crash!
12207 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012208 }
12209 }
12210
Motomu Utsumi6225d572023-05-29 15:08:57 +090012211 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12212 boolean hasIdleTimer) {
12213 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012214 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012215 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012216 // If only the default network is tracked, callbacks are called only when the
12217 // network has the idle timer.
12218 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012219 reportNetworkActive();
12220 }
12221 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012222 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012223 // If there is no default network, default network is considered active to keep the
12224 // existing behavior.
12225 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090012226 }
12227 }
12228
lucaslin1a8b4c62021-01-21 02:02:55 +080012229 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012230 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012231 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012232 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012233 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012234 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012235 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12236 // first connected and remove when the network is disconnected.
12237 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12238 // becomes the default network and remove when the network becomes no longer the default
12239 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012240 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012241 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012242 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012243 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012244 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012245 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012246 removeDataActivityTracking(oldNetwork);
12247 }
12248 }
lucaslinb961efc2021-01-21 02:03:17 +080012249
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012250 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012251 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12252 switch (transportType) {
12253 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012254 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012255 break;
12256 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012257 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012258 break;
12259 default:
12260 logw("Untracked transport type:" + transportType);
12261 }
12262 }
lucaslin1193a5d2021-01-21 02:04:15 +080012263
12264 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012265 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012266 }
12267
12268 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12269 mNetworkActivityListeners.register(l);
12270 }
12271
12272 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12273 mNetworkActivityListeners.unregister(l);
12274 }
lucaslin012f7a12021-01-21 02:04:35 +080012275
12276 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012277 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012278 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012279 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012280 pw.println("Idle timers:");
12281 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012282 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12283 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12284 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012285 pw.print(" timeout="); pw.print(params.timeout);
12286 pw.print(" type="); pw.println(params.transportType);
12287 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012288 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12289 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012290 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012291 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12292 // be accessed from handler thread, except dump(). As dump() is never called in
12293 // normal usage, it would be needlessly expensive to lock the collection only for
12294 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012295 // So catching the exception and logging.
12296 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012297 }
12298 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012299 }
James Mattis47db0582021-01-01 14:13:35 -080012300
Daniel Brightf9e945b2020-06-15 16:10:01 -070012301 /**
12302 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12303 *
12304 * @param socketInfo the socket information
12305 * @param callback the callback to register
12306 */
12307 @Override
12308 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12309 @NonNull final IQosCallback callback) {
12310 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12311 if (nai == null || nai.networkCapabilities == null) {
12312 try {
12313 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12314 } catch (final RemoteException ex) {
12315 loge("registerQosCallbackInternal: RemoteException", ex);
12316 }
12317 return;
12318 }
12319 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12320 }
12321
12322 /**
12323 * Register a {@link IQosCallback} with base {@link QosFilter}.
12324 *
12325 * @param filter the filter to register
12326 * @param callback the callback to register
12327 * @param nai the agent information related to the filter's network
12328 */
12329 @VisibleForTesting
12330 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12331 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012332 Objects.requireNonNull(filter, "filter must be non-null");
12333 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012334
12335 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012336 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12337 // on this network is unregistered when the app loses permission or b) no QoS
12338 // callbacks are sent for restricted networks unless the app currently has permission
12339 // to access restricted networks.
12340 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012341 }
12342 mQosCallbackTracker.registerCallback(callback, filter, nai);
12343 }
12344
12345 /**
12346 * Unregisters the given callback.
12347 *
12348 * @param callback the callback to unregister
12349 */
12350 @Override
12351 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012352 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012353 mQosCallbackTracker.unregisterCallback(callback);
12354 }
James Mattis47db0582021-01-01 14:13:35 -080012355
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012356 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12357 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12358 // Enterprise device can be fully managed like device owner and such use case
12359 // also should be supported. Calling app check for work profile and fully managed device
12360 // is already done in DevicePolicyManager.
12361 // This check is an extra caution to be sure device is fully managed or not.
12362 final UserManager um = mContext.getSystemService(UserManager.class);
12363 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12364 if (um.isManagedProfile(profile.getIdentifier())) {
12365 return true;
12366 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012367 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012368 return false;
12369 }
12370
James Mattis45d81842021-01-10 14:24:24 -080012371 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012372 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012373 *
12374 * See the documentation for the individual preferences for a description of the supported
12375 * behaviors.
12376 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012377 * @param profile If the device owner is set, any profile is allowed.
12378 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012379 * @param preferences the list of profile network preferences for the
12380 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012381 * @param listener an optional listener to listen for completion of the operation.
12382 */
12383 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012384 public void setProfileNetworkPreferences(
12385 @NonNull final UserHandle profile,
12386 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012387 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012388 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012389 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012390
12391 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012392 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12393 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12394 .build();
12395 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012396 }
12397
paulhu3ffffe72021-09-16 10:15:22 +080012398 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012399 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012400 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012401 }
12402 if (profile.getIdentifier() < 0) {
12403 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12404 + "UserHandle.CURRENT not supported)");
12405 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012406 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12407 throw new IllegalArgumentException("Profile must be a managed profile "
12408 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012409 }
paulhuaa0743d2021-05-26 21:56:03 +080012410
Chalard Jean0606fc82022-12-14 20:34:43 +090012411 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012412 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012413 for (final ProfileNetworkPreference preference : preferences) {
12414 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012415 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012416 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012417 switch (preference.getPreference()) {
12418 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12419 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012420 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012421 if (preference.getPreferenceEnterpriseId() != 0) {
12422 throw new IllegalArgumentException(
12423 "Invalid enterprise identifier in setProfileNetworkPreferences");
12424 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012425 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012426 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12427 blockingNonEnterprise = true;
12428 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012429 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12430 allowFallback = false;
12431 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012432 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012433 // This code is needed even though there is a check later on,
12434 // because isRangeAlreadyInPreferenceList assumes that every preference
12435 // has a UID list.
12436 if (hasDefaultPreference) {
12437 throw new IllegalArgumentException(
12438 "Default profile preference should not be set along with other "
12439 + "preference");
12440 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012441 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12442 throw new IllegalArgumentException(
12443 "Invalid enterprise identifier in setProfileNetworkPreferences");
12444 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012445 final Set<UidRange> uidRangeSet =
12446 getUidListToBeAppliedForNetworkPreference(profile, preference);
12447 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12448 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12449 } else {
12450 throw new IllegalArgumentException(
12451 "Overlapping uid range in setProfileNetworkPreferences");
12452 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012453 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012454 nc.addEnterpriseId(
12455 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012456 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12457 break;
12458 default:
12459 throw new IllegalArgumentException(
12460 "Invalid preference in setProfileNetworkPreferences");
12461 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012462 preferenceList.add(new ProfileNetworkPreferenceInfo(
12463 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012464 if (hasDefaultPreference && preferenceList.size() > 1) {
12465 throw new IllegalArgumentException(
12466 "Default profile preference should not be set along with other preference");
12467 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012468 }
12469 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012470 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012471 }
12472
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012473 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12474 @NonNull final UserHandle profile,
12475 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12476 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012477 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12478 profileNetworkPreference.getIncludedUids());
12479
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012480 if (uidRangeSet.size() > 0) {
12481 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12482 throw new IllegalArgumentException(
12483 "Allow uid range is outside the uid range of profile.");
12484 }
12485 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012486 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012487 profileNetworkPreference.getExcludedUids());
12488 if (disallowUidRangeSet.size() > 0) {
12489 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12490 throw new IllegalArgumentException(
12491 "disallow uid range is outside the uid range of profile.");
12492 }
12493 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12494 disallowUidRangeSet);
12495 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012496 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012497 uidRangeSet.add(profileUids);
12498 }
12499 }
12500 return uidRangeSet;
12501 }
12502
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012503 private boolean isEnterpriseIdentifierValid(
12504 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012505 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012506 return true;
12507 }
12508 return false;
12509 }
12510
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012511 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012512 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012513 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012514 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012515 // The NRI for a user should contain the request for capabilities.
12516 // If fallback to default network is needed then NRI should include
12517 // the request for the default network. Create an image of it to
12518 // have the correct UIDs in it (also a request can only be part of one NRI, because
12519 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012520 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12521 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012522 if (pref.allowFallback) {
12523 nrs.add(createDefaultInternetRequestForTransport(
12524 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12525 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012526 if (VDBG) {
12527 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12528 pref.capabilities.getUids()));
12529 }
12530
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012531 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012532 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012533 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012534 result.add(nri);
12535 }
12536 return result;
12537 }
12538
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012539 /**
12540 * Compare if the given UID range sets have the same UIDs.
12541 *
12542 */
12543 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012544 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012545 @NonNull Set<UidRange> uidRangeSet) {
12546 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12547 return false;
12548 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012549 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012550 if (UidRangeUtils.doesRangeSetOverlap(
12551 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12552 return true;
12553 }
12554 }
12555 return false;
12556 }
12557
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012558 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012559 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012560 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012561 /*
12562 * handleSetProfileNetworkPreference is always called for single user.
12563 * preferenceList only contains preferences for different uids within the same user
12564 * (enforced by getUidListToBeAppliedForNetworkPreference).
12565 * Clear all the existing preferences for the user before applying new preferences.
12566 *
12567 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012568 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12569 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012570 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12571 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012572
paulhu74128522021-09-28 02:29:03 +000012573 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12574 addPerAppDefaultNetworkRequests(
12575 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012576 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012577
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012578 // Finally, rematch.
12579 rematchAllNetworksAndRequests();
12580
12581 if (null != listener) {
12582 try {
12583 listener.onComplete();
12584 } catch (RemoteException e) {
12585 loge("Listener for setProfileNetworkPreference has died");
12586 }
12587 }
12588 }
12589
paulhu51f77dc2021-06-07 02:34:20 +000012590 @VisibleForTesting
12591 @NonNull
12592 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12593 @NonNull final Set<Integer> uids) {
12594 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12595 if (uids.size() == 0) {
12596 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12597 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12598 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12599 return nris;
12600 }
12601
12602 final List<NetworkRequest> requests = new ArrayList<>();
12603 // The NRI should be comprised of two layers:
12604 // - The request for the mobile network preferred.
12605 // - The request for the default network, for fallback.
12606 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012607 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012608 requests.add(createDefaultInternetRequestForTransport(
12609 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12610 final Set<UidRange> ranges = new ArraySet<>();
12611 for (final int uid : uids) {
12612 ranges.add(new UidRange(uid, uid));
12613 }
12614 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012615 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012616 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012617 return nris;
12618 }
12619
12620 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012621 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012622 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12623 addPerAppDefaultNetworkRequests(
12624 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012625 // Finally, rematch.
12626 rematchAllNetworksAndRequests();
12627 }
12628
Patrick Rohr2857ac42022-01-21 14:58:16 +010012629 private void handleIngressRateLimitChanged() {
12630 final long oldIngressRateLimit = mIngressRateLimit;
12631 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12632 mContext);
12633 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12634 if (canNetworkBeRateLimited(networkAgent)) {
12635 // If rate limit has previously been enabled, remove the old limit first.
12636 if (oldIngressRateLimit >= 0) {
12637 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12638 }
12639 if (mIngressRateLimit >= 0) {
12640 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12641 mIngressRateLimit);
12642 }
12643 }
12644 }
12645 }
12646
12647 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012648 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012649 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012650
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012651 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12652 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12653 // internet connectivity can be rate limited.
12654 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12655 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012656 return false;
12657 }
12658
12659 final String iface = networkAgent.linkProperties.getInterfaceName();
12660 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012661 // This may happen in tests, but if there is no interface then there is nothing that
12662 // can be rate limited.
12663 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012664 return false;
12665 }
12666 return true;
12667 }
12668
James Mattis45d81842021-01-10 14:24:24 -080012669 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012670 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12671 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012672 }
12673
12674 /**
12675 * Used by automotive devices to set the network preferences used to direct traffic at an
12676 * application level as per the given OemNetworkPreferences. An example use-case would be an
12677 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12678 * vehicle via a particular network.
12679 *
12680 * Calling this will overwrite the existing preference.
12681 *
James Mattisda32cfe2021-01-26 16:23:52 -080012682 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012683 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012684 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012685 */
James Mattis47db0582021-01-01 14:13:35 -080012686 @Override
James Mattis45d81842021-01-10 14:24:24 -080012687 public void setOemNetworkPreference(
12688 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012689 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012690
James Mattisfa270db2021-05-31 17:11:10 -070012691 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12692 // Only bypass the permission/device checks if this is a valid test request.
12693 if (isValidTestOemNetworkPreference(preference)) {
12694 enforceManageTestNetworksPermission();
12695 } else {
12696 enforceAutomotiveDevice();
12697 enforceOemNetworkPreferencesPermission();
12698 validateOemNetworkPreferences(preference);
12699 }
James Mattis45d81842021-01-10 14:24:24 -080012700
James Mattis45d81842021-01-10 14:24:24 -080012701 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12702 new Pair<>(preference, listener)));
12703 }
12704
James Mattisfa270db2021-05-31 17:11:10 -070012705 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012706 * Sets the specified UIDs to get/receive the VPN as the only default network.
12707 *
12708 * Calling this will overwrite the existing network preference for this session, and the
12709 * specified UIDs won't get any default network when no VPN is connected.
12710 *
12711 * @param session The VPN session which manages the passed UIDs.
12712 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12713 * setting for this session if the array is empty. Null is not allowed, the
12714 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12715 * @hide
12716 */
12717 @Override
12718 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12719 Objects.requireNonNull(ranges);
12720 enforceNetworkStackOrSettingsPermission();
12721 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12722 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12723 throw new IllegalArgumentException(
12724 "setVpnNetworkPreference: Passed UID ranges overlap");
12725 }
12726
12727 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12728 new VpnNetworkPreferenceInfo(session,
12729 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12730 }
12731
12732 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12733 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12734
12735 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12736 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12737
12738 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12739 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12740 // Finally, rematch.
12741 rematchAllNetworksAndRequests();
12742 }
12743
12744 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12745 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12746 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12747 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12748 final List<NetworkRequest> requests = new ArrayList<>();
12749 // Request VPN only, so other networks won't be the fallback options when VPN is not
12750 // connected temporarily.
12751 requests.add(createVpnRequest());
12752 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12753 setNetworkRequestUids(requests, uidRanges);
12754 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12755 }
12756 return nris;
12757 }
12758
12759 /**
James Mattisfa270db2021-05-31 17:11:10 -070012760 * Check the validity of an OEM network preference to be used for testing purposes.
12761 * @param preference the preference to validate
12762 * @return true if this is a valid OEM network preference test request.
12763 */
12764 private boolean isValidTestOemNetworkPreference(
12765 @NonNull final OemNetworkPreferences preference) {
12766 // Allow for clearing of an existing OemNetworkPreference used for testing.
12767 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12768 // changes after this check is complete. This is an unlikely scenario as calling of this API
12769 // is controlled by the OEM therefore the added complexity is not worth adding given those
12770 // circumstances. That said, it is an edge case to be aware of hence this comment.
12771 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12772 && isTestOemNetworkPreference(mOemNetworkPreferences);
12773 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12774 }
12775
12776 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12777 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12778 return prefMap.size() == 1
12779 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12780 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12781 }
12782
James Mattis45d81842021-01-10 14:24:24 -080012783 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12784 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12785 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012786 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12787 throw new IllegalArgumentException(
12788 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12789 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012790 }
12791 }
12792 }
12793
12794 private void handleSetOemNetworkPreference(
12795 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012796 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012797 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12798 if (DBG) {
12799 log("set OEM network preferences :" + preference.toString());
12800 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012801
James Mattiscb1e0362021-04-06 17:07:42 -070012802 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012803 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12804 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12805 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012806 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012807
12808 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012809 try {
12810 listener.onComplete();
12811 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012812 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012813 }
James Mattis45d81842021-01-10 14:24:24 -080012814 }
12815 }
12816
paulhu74128522021-09-28 02:29:03 +000012817 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012818 // Skip the requests which are set by other network preference. Because the uid range rules
12819 // should stay in netd.
12820 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012821 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012822 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012823 }
12824
James Mattis3ce3d3c2021-02-09 18:18:28 -080012825 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12826 ensureRunningOnConnectivityServiceThread();
12827 mDefaultNetworkRequests.addAll(nris);
12828 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12829 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012830 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012831 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12832 nrisToRegister.addAll(
12833 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12834 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012835 }
12836
12837 /**
12838 * All current requests that are tracking the default network need to be assessed as to whether
12839 * or not the current set of per-application default requests will be changing their default
12840 * network. If so, those requests will need to be updated so that they will send callbacks for
12841 * default network changes at the appropriate time. Additionally, those requests tracking the
12842 * default that were previously updated by this flow will need to be reassessed.
12843 * @return the nris which will need to be updated.
12844 */
12845 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12846 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12847 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12848 // same nri in the map's values for each of its NetworkRequest objects.
12849 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012850 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012851 // Include this nri if it is currently being tracked.
12852 if (isPerAppTrackedNri(nri)) {
12853 defaultCallbackRequests.add(nri);
12854 continue;
12855 }
12856 // We only track callbacks for requests tracking the default.
12857 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12858 continue;
12859 }
12860 // Include this nri if it will be tracked by the new per-app default requests.
12861 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012862 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012863 if (isNriGoingToBeTracked) {
12864 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012865 }
12866 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012867 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012868 }
12869
James Mattis3ce3d3c2021-02-09 18:18:28 -080012870 /**
12871 * Create nris for those network requests that are currently tracking the default network that
12872 * are being controlled by a per-application default.
12873 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12874 * foundation when creating the nri. Important items include the calling uid's original
12875 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12876 * requests are assumed to have already been validated as needing to be updated.
12877 * @return the Set of nris to use when registering network requests.
12878 */
12879 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12880 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12881 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12882 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12883 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012884 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012885
Chalard Jean9473c982021-07-29 20:03:04 +090012886 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012887 if (trackingNri == mDefaultRequest) {
12888 callbackRequestsToRegister.add(new NetworkRequestInfo(
12889 callbackRequest,
12890 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12891 continue;
12892 }
12893
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012894 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012895 callbackRequestsToRegister.add(new NetworkRequestInfo(
12896 callbackRequest,
12897 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012898 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012899 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012900 }
12901 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012902 }
12903
Chalard Jean17215832021-03-01 14:06:28 +090012904 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12905 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012906 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012907 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012908 }
12909 }
12910
James Mattis45d81842021-01-10 14:24:24 -080012911 /**
12912 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12913 */
12914 @VisibleForTesting
12915 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012916 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012917 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012918 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012919 final SparseArray<Set<Integer>> uids =
12920 createUidsFromOemNetworkPreferences(preference);
12921 for (int i = 0; i < uids.size(); i++) {
12922 final int key = uids.keyAt(i);
12923 final Set<Integer> value = uids.valueAt(i);
12924 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12925 // No need to add an nri without any requests.
12926 if (0 == nri.mRequests.size()) {
12927 continue;
12928 }
12929 nris.add(nri);
12930 }
12931
12932 return nris;
12933 }
12934
12935 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12936 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012937 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012938 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012939 final List<UserHandle> users =
12940 mContext.getSystemService(UserManager.class).getUserHandles(true);
12941 if (null == users || users.size() == 0) {
12942 if (VDBG || DDBG) {
12943 log("No users currently available for setting the OEM network preference.");
12944 }
James Mattisb6b6a432021-06-01 22:30:36 -070012945 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012946 }
James Mattis45d81842021-01-10 14:24:24 -080012947 for (final Map.Entry<String, Integer> entry :
12948 preference.getNetworkPreferences().entrySet()) {
12949 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012950 // Add the rules for all users as this policy is device wide.
12951 for (final UserHandle user : users) {
12952 try {
12953 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12954 if (!prefToUids.contains(pref)) {
12955 prefToUids.put(pref, new ArraySet<>());
12956 }
12957 prefToUids.get(pref).add(uid);
12958 } catch (PackageManager.NameNotFoundException e) {
12959 // Although this may seem like an error scenario, it is ok that uninstalled
12960 // packages are sent on a network preference as the system will watch for
12961 // package installations associated with this network preference and update
12962 // accordingly. This is done to minimize race conditions on app install.
12963 continue;
James Mattis45d81842021-01-10 14:24:24 -080012964 }
James Mattis45d81842021-01-10 14:24:24 -080012965 }
12966 }
James Mattisb6b6a432021-06-01 22:30:36 -070012967 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012968 }
12969
12970 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12971 @OemNetworkPreferences.OemNetworkPreference final int preference,
12972 @NonNull final Set<Integer> uids) {
12973 final List<NetworkRequest> requests = new ArrayList<>();
12974 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12975 switch (preference) {
12976 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12977 requests.add(createUnmeteredNetworkRequest());
12978 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012979 requests.add(createDefaultInternetRequestForTransport(
12980 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012981 break;
12982 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12983 requests.add(createUnmeteredNetworkRequest());
12984 requests.add(createOemPaidNetworkRequest());
12985 break;
12986 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12987 requests.add(createOemPaidNetworkRequest());
12988 break;
12989 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12990 requests.add(createOemPrivateNetworkRequest());
12991 break;
James Mattisfa270db2021-05-31 17:11:10 -070012992 case OEM_NETWORK_PREFERENCE_TEST:
12993 requests.add(createUnmeteredNetworkRequest());
12994 requests.add(createTestNetworkRequest());
12995 requests.add(createDefaultRequest());
12996 break;
12997 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12998 requests.add(createTestNetworkRequest());
12999 break;
James Mattis45d81842021-01-10 14:24:24 -080013000 default:
13001 // This should never happen.
13002 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
13003 + " called with invalid preference of " + preference);
13004 }
13005
James Mattisfa270db2021-05-31 17:11:10 -070013006 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090013007 for (final int uid : uids) {
13008 ranges.add(new UidRange(uid, uid));
13009 }
13010 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080013011 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080013012 }
13013
13014 private NetworkRequest createUnmeteredNetworkRequest() {
13015 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13016 .addCapability(NET_CAPABILITY_NOT_METERED)
13017 .addCapability(NET_CAPABILITY_VALIDATED);
13018 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
13019 }
13020
13021 private NetworkRequest createOemPaidNetworkRequest() {
13022 // NET_CAPABILITY_OEM_PAID is a restricted capability.
13023 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13024 .addCapability(NET_CAPABILITY_OEM_PAID)
13025 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13026 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13027 }
13028
13029 private NetworkRequest createOemPrivateNetworkRequest() {
13030 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
13031 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13032 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
13033 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13034 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13035 }
13036
13037 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070013038 final NetworkCapabilities netcap = new NetworkCapabilities();
13039 netcap.addCapability(NET_CAPABILITY_INTERNET);
13040 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
13041 return netcap;
13042 }
13043
13044 private NetworkRequest createTestNetworkRequest() {
13045 final NetworkCapabilities netcap = new NetworkCapabilities();
13046 netcap.clearAll();
13047 netcap.addTransportType(TRANSPORT_TEST);
13048 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080013049 }
James Mattis47db0582021-01-01 14:13:35 -080013050 }
markchien738ad912021-12-09 18:15:45 +080013051
Junyu Lai38c75032023-12-04 07:52:19 +000013052 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080013053 @Override
Junyu Laidf210362023-10-24 02:47:50 +000013054 public void setDataSaverEnabled(final boolean enable) {
13055 enforceNetworkStackOrSettingsPermission();
13056 try {
13057 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
13058 if (!ret) {
13059 throw new IllegalStateException("Error when changing iptables: " + enable);
13060 }
13061 } catch (RemoteException e) {
13062 // Lack of permission or binder errors.
13063 throw new IllegalStateException(e);
13064 }
Ken Chen24330172023-10-20 13:02:14 +080013065
13066 try {
13067 mBpfNetMaps.setDataSaverEnabled(enable);
13068 } catch (ServiceSpecificException | UnsupportedOperationException e) {
13069 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
13070 }
Junyu Laidf210362023-10-24 02:47:50 +000013071 }
13072
13073 @Override
markchien738ad912021-12-09 18:15:45 +080013074 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
13075 enforceNetworkStackOrSettingsPermission();
13076
13077 try {
13078 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013079 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013080 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013081 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013082 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013083 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013084 throw new IllegalStateException(e);
13085 }
13086 }
13087
13088 @Override
13089 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13090 enforceNetworkStackOrSettingsPermission();
13091
13092 try {
13093 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013094 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013095 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013096 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013097 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013098 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013099 throw new IllegalStateException(e);
13100 }
13101 }
markchiene1561fa2021-12-09 22:00:56 +080013102
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013103 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13104 throws PackageManager.NameNotFoundException {
13105 final PackageManager pm = mContext.getPackageManager();
13106 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13107 if (appId < Process.FIRST_APPLICATION_UID) {
13108 throw new RuntimeException("Can't set package firewall rule for system app "
13109 + packageName + " with appId " + appId);
13110 }
13111 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13112 final int uid = uh.getUid(appId);
13113 setUidFirewallRule(chain, uid, rule);
13114 }
13115 return appId;
13116 }
13117
markchiene1561fa2021-12-09 22:00:56 +080013118 @Override
markchien3c04e662022-03-22 16:29:56 +080013119 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013120 enforceNetworkStackOrSettingsPermission();
13121
markchien3c04e662022-03-22 16:29:56 +080013122 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13123 int firewallRule = getFirewallRuleType(chain, rule);
13124
13125 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13126 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13127 }
13128
markchiene1561fa2021-12-09 22:00:56 +080013129 try {
markchien3c04e662022-03-22 16:29:56 +080013130 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013131 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013132 throw new IllegalStateException(e);
13133 }
13134 }
markchien98a6f952022-01-13 23:43:53 +080013135
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013136 private int getPackageFirewallRule(final int chain, final String packageName)
13137 throws PackageManager.NameNotFoundException {
13138 final PackageManager pm = mContext.getPackageManager();
13139 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13140 return getUidFirewallRule(chain, appId);
13141 }
13142
Motomu Utsumi900b8062023-01-19 16:16:49 +090013143 @Override
13144 public int getUidFirewallRule(final int chain, final int uid) {
13145 enforceNetworkStackOrSettingsPermission();
13146 return mBpfNetMaps.getUidRule(chain, uid);
13147 }
13148
markchien3c04e662022-03-22 16:29:56 +080013149 private int getFirewallRuleType(int chain, int rule) {
13150 final int defaultRule;
13151 switch (chain) {
13152 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013153 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13154 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013155 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013156 defaultRule = FIREWALL_RULE_ALLOW;
13157 break;
13158 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13159 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13160 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13161 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013162 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013163 defaultRule = FIREWALL_RULE_DENY;
13164 break;
13165 default:
13166 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13167 }
13168 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13169
13170 return rule;
13171 }
13172
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013173 private void closeSocketsForFirewallChainLocked(final int chain)
13174 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013175 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013176 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13177 // So, close all non-system socket owned by uids that are not explicitly allowed
13178 Set<Range<Integer>> ranges = new ArraySet<>();
13179 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13180 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13181 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13182 } else {
13183 // Denylist means the firewall allows all by default, uids must be explicitly denied
13184 // So, close socket owned by uids that are explicitly denied
13185 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13186 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13187 }
13188 }
13189
markchien98a6f952022-01-13 23:43:53 +080013190 @Override
13191 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13192 enforceNetworkStackOrSettingsPermission();
13193
13194 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013195 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013196 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013197 throw new IllegalStateException(e);
13198 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013199
Chalard Jeandf29a852023-05-29 17:02:43 +090013200 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013201 try {
13202 closeSocketsForFirewallChainLocked(chain);
13203 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13204 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13205 }
13206 }
markchien98a6f952022-01-13 23:43:53 +080013207 }
13208
markchien00a0bed2022-01-13 23:46:13 +080013209 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013210 public boolean getFirewallChainEnabled(final int chain) {
13211 enforceNetworkStackOrSettingsPermission();
13212
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013213 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013214 }
13215
13216 @Override
markchien00a0bed2022-01-13 23:46:13 +080013217 public void replaceFirewallChain(final int chain, final int[] uids) {
13218 enforceNetworkStackOrSettingsPermission();
13219
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013220 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013221 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013222
13223 @Override
13224 public IBinder getCompanionDeviceManagerProxyService() {
13225 enforceNetworkStackPermission(mContext);
13226 return mCdmps;
13227 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013228
13229 @Override
13230 public IBinder getRoutingCoordinatorService() {
13231 enforceNetworkStackPermission(mContext);
13232 return mRoutingCoordinatorService;
13233 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013234}