blob: 66e10a2ca10388b23c5587ab09e0d35a769fda1b [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;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700331import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900332import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900333import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700334import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900335import com.android.server.connectivity.RoutingCoordinatorService;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800336import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000337import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800338import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600339
Josh Gao461a1222020-06-16 15:58:11 -0700340import libcore.io.IoUtils;
341
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900342import org.xmlpull.v1.XmlPullParserException;
343
The Android Open Source Project28527d22009-03-03 19:31:44 -0800344import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100345import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900346import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800347import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900348import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700349import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700350import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900351import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900352import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700353import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700354import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700355import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700356import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800357import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900358import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800359import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700360import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700361import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700362import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700363import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900364import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700365import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900366import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600367import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900368import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600369import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900370import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900371import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800372
373/**
374 * @hide
375 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800376public class ConnectivityService extends IConnectivityManager.Stub
377 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900378 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800379
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900380 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900381 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900382 private static final String NETWORK_ARG = "networks";
383 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800384 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900385
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900386 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900387 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
388 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800389
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900390 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700391
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100392 /**
393 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
394 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800395 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100396 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
397 * (preferably via runtime resource overlays).
398 */
399 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
400 "http://connectivitycheck.gstatic.com/generate_204";
401
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700402 // TODO: create better separation between radio types and network types
403
Robert Greenwalt2034b912009-08-12 16:08:25 -0700404 // how long to wait before switching back to a radio's default network
405 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
406 // system property that can override the above value
407 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
408 "android.telephony.apn-restore";
409
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900410 // How long to wait before putting up a "This network doesn't have an Internet connection,
411 // connect anyway?" dialog after the user selects a network that doesn't validate.
412 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
413
Chalard Jean5fb43c72022-09-08 19:03:14 +0900414 // How long to wait before considering that a network is bad in the absence of any form
415 // of connectivity (valid, partial, captive portal). If none has been detected after this
416 // delay, the stack considers this network bad, which may affect how it's handled in ranking
417 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900418 // Timeout in case the "actively prefer bad wifi" feature is on
419 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
420 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900421 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900422
junyulai0ac374f2020-12-14 18:41:52 +0800423 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900424 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
425 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800426 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700427
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800428 // Delimiter used when creating the broadcast delivery group for sending
429 // CONNECTIVITY_ACTION broadcast.
430 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
431
he_won.hwang881307a2022-03-15 21:23:52 +0900432 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900433 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900434
Daniel Brightf9e945b2020-06-15 16:10:01 -0700435 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900436 @VisibleForTesting
437 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700438
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900439 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700440 @VisibleForTesting
441 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900442
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900443 @VisibleForTesting
444 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800445 @VisibleForTesting
446 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900447 // True if the cell radio of the device is capable of time-sharing.
448 @VisibleForTesting
449 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900450
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800451 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800452 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800453 private final int mReleasePendingIntentDelayMs;
454
Chalard Jean46bfbf02022-02-02 00:56:25 +0900455 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900456
Motomu Utsumif360aa62023-01-30 17:52:20 +0900457 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700458
Chalard Jean9473c982021-07-29 20:03:04 +0900459 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800460 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700461 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800462 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700463
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900464 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700465
junyulaif2c67e42018-08-07 19:50:45 +0800466 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000467 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
468 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800469 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900470 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800471
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900472 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900473 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000474 private final int mWakeUpMark;
475 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000476 // The Context is created for UserHandle.ALL.
477 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900478 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900479 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700480 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700481 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800482
Chenbo Feng15416292018-11-08 17:36:21 -0800483 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800484 protected IDnsResolver mDnsResolver;
485 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800486 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700487 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900488 private final NetworkStatsManager mStatsManager;
489 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800490 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700491
Benedict Wong493e04b2018-11-09 14:45:34 -0800492 /**
493 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
494 * instances.
495 */
496 @GuardedBy("mTNSLock")
497 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800498 private final CompanionDeviceManagerProxyService mCdmps;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900499 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800500
501 private final Object mTNSLock = new Object();
502
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700503 private String mCurrentTcpBufferSizes;
504
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900505 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000506 new Class[] {
507 ConnectivityService.class,
508 NetworkAgent.class,
509 NetworkAgentInfo.class,
510 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900511
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500512 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400513 // Tear down networks that have no chance (e.g. even if validated) of becoming
514 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500515 // all networks have been rematched against all NetworkRequests.
516 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400517 // Don't reap networks. This should be passed when some networks have not yet been
518 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500519 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900520 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500521
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900522 private enum UnneededFor {
523 LINGER, // Determine whether this network is unneeded and should be lingered.
524 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
525 }
526
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700527 /**
paulhuaa0743d2021-05-26 21:56:03 +0800528 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800529 * should have priority. The order is passed to netd which will use it together
530 * with UID ranges to generate the corresponding IP rule. This serves to
531 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800532 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800533 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000534 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800535 *
paulhu48291862021-07-14 14:53:57 +0800536 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
537 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800538 */
paulhu48291862021-07-14 14:53:57 +0800539 // Used when sending to netd to code for "no order".
540 static final int PREFERENCE_ORDER_NONE = 0;
541 // Order for requests that don't code for a per-app preference. As it is
542 // out of the valid range, the corresponding order should be
543 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800544 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800545 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800546 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800547 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
548 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800549 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800550 static final int PREFERENCE_ORDER_OEM = 10;
551 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800552 // See {@link #setProfileNetworkPreference}.
553 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800554 static final int PREFERENCE_ORDER_PROFILE = 20;
555 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800556 // better scores are connected.
557 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800558 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800559 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900560 // Preference order that signifies the network shouldn't be set as a default network for
561 // the UIDs, only give them access to it. TODO : replace this with a boolean
562 // in NativeUidRangeConfig
563 @VisibleForTesting
564 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
565 // Bound for the lowest valid preference order.
566 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800567
568 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700569 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700570 * from one net to another. Clear happens when we get a new
571 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
572 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700573 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700574 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700575
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700576 /**
577 * used internally to reload global proxy settings
578 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700579 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700580
Robert Greenwalt34848c02011-03-25 13:09:25 -0700581 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400582 * PAC manager has received new port.
583 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800584 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400585
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700586 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900587 * used internally when registering NetworkProviders
588 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700589 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900590 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700591
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700592 /**
593 * used internally when registering NetworkAgents
594 * obj = Messenger
595 */
596 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
597
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700598 /**
599 * used to add a network request
600 * includes a NetworkRequestInfo
601 */
602 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
603
604 /**
605 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900606 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700607 * cancel it.
608 * includes a NetworkRequestInfo
609 */
610 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
611
612 /**
613 * used to add a network listener - no request
614 * includes a NetworkRequestInfo
615 */
616 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
617
618 /**
619 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400620 * arg1 = UID of caller
621 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700622 */
623 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
624
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700625 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900626 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700627 * obj = Messenger
628 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900629 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700630
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700631 /**
632 * used internally to expire a wakelock when transitioning
633 * from one net to another. Expire happens when we fail to find
634 * a new network (typically after 1 minute) -
635 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
636 * a replacement network.
637 */
638 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
639
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700640 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800641 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400642 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800643 */
644 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
645
646 /**
647 * used to remove a pending intent and its associated network request.
648 * arg1 = UID of caller
649 * obj = PendingIntent
650 */
651 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
652
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900653 /**
654 * used to specify whether a network should be used even if unvalidated.
655 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
656 * arg2 = whether to remember this choice in the future (1 or 0)
657 * obj = network
658 */
659 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
660
661 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700662 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900663 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700664 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900665
Paul Jensenc8873fc2015-06-17 14:15:39 -0400666 /**
667 * used to add a network listener with a pending intent
668 * obj = NetworkRequestInfo
669 */
670 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
671
Hugo Benichid6b510a2017-04-06 17:22:18 +0900672 /**
673 * used to specify whether a network should not be penalized when it becomes unvalidated.
674 */
675 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
676
677 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700678 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900679 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700680 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900681
Erik Kline31b4a9e2018-01-11 21:07:29 +0900682 // Handle changes in Private DNS settings.
683 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
684
dalyk1720e542018-03-05 12:42:22 -0500685 // Handle private DNS validation status updates.
686 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
687
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900688 /**
689 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
690 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800691 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
692 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
693 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900694 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900695 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900696
697 /**
698 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
699 * config was resolved.
700 * obj = PrivateDnsConfig
701 * arg2 = netid
702 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900703 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900704
705 /**
706 * Request ConnectivityService display provisioning notification.
707 * arg1 = Whether to make the notification visible.
708 * arg2 = NetID.
709 * obj = Intent to be launched when notification selected by user, null if !arg1.
710 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900711 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900712
713 /**
lucaslin2240ef62019-03-12 13:08:03 +0800714 * Used to specify whether a network should be used even if connectivity is partial.
715 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
716 * false)
717 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
718 * obj = network
719 */
lucaslin444d43a2020-02-20 16:56:59 +0800720 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800721
722 /**
lucasline117e2e2019-10-22 18:27:33 +0800723 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
724 * Both of the arguments are bitmasks, and the value of bits come from
725 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900726 * arg1 = unused
727 * arg2 = netId
728 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800729 */
lucaslin444d43a2020-02-20 16:56:59 +0800730 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800731
732 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900733 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
734 * arg1 = unused
735 * arg2 = netId
736 * obj = captive portal data
737 */
lucaslin444d43a2020-02-20 16:56:59 +0800738 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900739
740 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900741 * Used by setRequireVpnForUids.
742 * arg1 = whether the specified UID ranges are required to use a VPN.
743 * obj = Array of UidRange objects.
744 */
745 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
746
747 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900748 * Used internally when setting the default networks for OemNetworkPreferences.
749 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800750 */
751 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
752
753 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800754 * Used to indicate the system default network becomes active.
755 */
756 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
757
758 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900759 * Used internally when setting a network preference for a user profile.
760 * obj = Pair<ProfileNetworkPreference, Listener>
761 */
762 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
763
764 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000765 * Event to specify that reasons for why an uid is blocked changed.
766 * arg1 = uid
767 * arg2 = blockedReasons
768 */
769 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
770
771 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900772 * Event to register a new network offer
773 * obj = NetworkOffer
774 */
775 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
776
777 /**
778 * Event to unregister an existing network offer
779 * obj = INetworkOfferCallback
780 */
781 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
782
783 /**
paulhu51f77dc2021-06-07 02:34:20 +0000784 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
785 */
786 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
787
788 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800789 * Event to set temporary allow bad wifi within a limited time to override
790 * {@code config_networkAvoidBadWifi}.
791 */
792 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
793
794 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100795 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
796 */
797 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
798
799 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900800 * The initial evaluation period is over for this network.
801 *
802 * If no form of connectivity has been found on this network (valid, partial, captive portal)
803 * then the stack will now consider it to have been determined bad.
804 */
805 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
806
807 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000808 * Used internally when the user does not want the network from captive portal app.
809 * obj = Network
810 */
811 private static final int EVENT_USER_DOES_NOT_WANT = 58;
812
813 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000814 * Event to set VPN as preferred network for specific apps.
815 * obj = VpnNetworkPreferenceInfo
816 */
817 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
818
819 /**
chiachangwange0192a72023-02-06 13:25:01 +0000820 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
821 */
822 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
823
824 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000825 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
826 */
827 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
828
829 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900830 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
831 * should be shown.
832 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900833 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900834
835 /**
836 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
837 * should be hidden.
838 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900839 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900840
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800841 /**
842 * The maximum alive time to allow bad wifi configuration for testing.
843 */
844 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
845
Patrick Rohr2857ac42022-01-21 14:58:16 +0100846 /**
chiachangwange0192a72023-02-06 13:25:01 +0000847 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
848 * testing.
849 */
850 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
851
852 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100853 * The priority of the tc police rate limiter -- smaller value is higher priority.
854 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
855 */
856 private static final short TC_PRIO_POLICE = 1;
857
858 /**
859 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
860 */
861 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700862 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100863
Hugo Benichi47011212017-03-30 10:46:05 +0900864 private static String eventName(int what) {
865 return sMagicDecoderRing.get(what, Integer.toString(what));
866 }
867
paulhua10d8212020-11-10 15:32:56 +0800868 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900869 final DnsResolverServiceManager dsm = context.getSystemService(
870 DnsResolverServiceManager.class);
871 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800872 }
873
Cody Kesting73708bf2019-12-18 10:57:50 -0800874 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900875 @VisibleForTesting
876 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700877 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700878 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700879 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700880 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800881 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
882 @VisibleForTesting
883 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
884
Erik Kline32120082017-12-13 19:40:49 +0900885 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900886 @VisibleForTesting
887 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700888
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400889 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800890 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400891
Chalard Jean46bfbf02022-02-02 00:56:25 +0900892 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800893 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700894
Chalard Jean5d70ba42018-06-07 16:44:04 +0900895 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
896 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800897 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400898
Erik Kline05f2b402015-04-30 12:58:40 +0900899 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700900
Chalard Jean46bfbf02022-02-02 00:56:25 +0900901 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400902
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700903 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900904 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700905
Valentin Iftime9fa35092019-09-24 13:32:13 +0200906 private Set<String> mWolSupportedInterfaces;
907
Roshan Pius08c94fb2020-01-16 12:17:17 -0800908 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800909 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800910 private final AppOpsManager mAppOpsManager;
911
912 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400913
chiachangwang3d60bac2023-01-17 14:38:08 +0000914 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900915 private final QosCallbackTracker mQosCallbackTracker;
916 private final NetworkNotificationManager mNotifier;
917 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900918
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700919 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800920 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700921
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900922 // Sequence number for NetworkProvider IDs.
923 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
924 NetworkProvider.FIRST_PROVIDER_ID);
925
Erik Klineedf878b2015-07-09 18:24:03 +0900926 // NetworkRequest activity String log entries.
927 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
928 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
929
Hugo Benichid159fdd2016-07-11 11:05:12 +0900930 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900931 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900932 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
933
Hugo Benichi47011212017-03-30 10:46:05 +0900934 private static final int MAX_WAKELOCK_LOGS = 20;
935 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900936 private int mTotalWakelockAcquisitions = 0;
937 private int mTotalWakelockReleases = 0;
938 private long mTotalWakelockDurationMs = 0;
939 private long mMaxWakelockDurationMs = 0;
940 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900941
Hugo Benichi208c0102016-07-28 17:53:06 +0900942 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900943
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700944 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900945 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700946
Erik Kline95ecfee2016-10-02 18:02:14 +0900947 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900948 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900949
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900950 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800951 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
952 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800953
Patrick Rohr2857ac42022-01-21 14:58:16 +0100954 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
955 // configured via {@link
956 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
957 // Only the handler thread is allowed to access this field.
958 private long mIngressRateLimit = -1;
959
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900960 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
961 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900962 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900963 @GuardedBy("mSelfCertifiedCapabilityCache")
964 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
965 mSelfCertifiedCapabilityCache = new HashMap<>();
966
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900967 // Flag to enable the feature of closing frozen app sockets.
968 private final boolean mDestroyFrozenSockets;
969
970 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
971 private final boolean mDelayDestroyFrozenSockets;
972
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900973 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
974 private final boolean mAllowSysUiConnectivityReports;
975
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900976 // Uids that ConnectivityService is pending to close sockets of.
977 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
978
Robert Greenwalt802c1102014-06-02 15:32:02 -0700979 /**
980 * Implements support for the legacy "one network per network type" model.
981 *
982 * We used to have a static array of NetworkStateTrackers, one for each
983 * network type, but that doesn't work any more now that we can have,
984 * for example, more that one wifi network. This class stores all the
985 * NetworkAgentInfo objects that support a given type, but the legacy
986 * API will only see the first one.
987 *
988 * It serves two main purposes:
989 *
990 * 1. Provide information about "the network for a given type" (since this
991 * API only supports one).
992 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
993 * the first network for a given type changes, or if the default network
994 * changes.
995 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900996 @VisibleForTesting
997 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900998
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900999 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001000 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001001
Robert Greenwalt802c1102014-06-02 15:32:02 -07001002 /**
1003 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1004 * Each list holds references to all NetworkAgentInfos that are used to
1005 * satisfy requests for that network type.
1006 *
1007 * This array is built out at startup such that an unsupported network
1008 * doesn't get an ArrayList instance, making this a tristate:
1009 * unsupported, supported but not active and active.
1010 *
1011 * The actual lists are populated when we scan the network types that
1012 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001013 *
1014 * Threading model:
1015 * - addSupportedType() is only called in the constructor
1016 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1017 * They are therefore not thread-safe with respect to each other.
1018 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1019 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001020 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001021 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001022 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001023 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001024 @NonNull
1025 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001026
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001027 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1028 // an entry have no timer (equivalent to -1). Lazily loaded.
1029 @NonNull
1030 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1031
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001032 LegacyTypeTracker(@NonNull ConnectivityService service) {
1033 mService = service;
1034 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001035 }
1036
Chiachang Wang3bc52762021-11-25 14:17:57 +08001037 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1038 // addressed.
1039 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001040 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1041 final PackageManager pm = ctx.getPackageManager();
1042 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1043 addSupportedType(TYPE_WIFI);
1044 }
1045 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1046 addSupportedType(TYPE_WIFI_P2P);
1047 }
1048 if (tm.isDataCapable()) {
1049 // Telephony does not have granular support for these types: they are either all
1050 // supported, or none is supported
1051 addSupportedType(TYPE_MOBILE);
1052 addSupportedType(TYPE_MOBILE_MMS);
1053 addSupportedType(TYPE_MOBILE_SUPL);
1054 addSupportedType(TYPE_MOBILE_DUN);
1055 addSupportedType(TYPE_MOBILE_HIPRI);
1056 addSupportedType(TYPE_MOBILE_FOTA);
1057 addSupportedType(TYPE_MOBILE_IMS);
1058 addSupportedType(TYPE_MOBILE_CBS);
1059 addSupportedType(TYPE_MOBILE_IA);
1060 addSupportedType(TYPE_MOBILE_EMERGENCY);
1061 }
1062 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1063 addSupportedType(TYPE_BLUETOOTH);
1064 }
1065 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1066 // TYPE_PROXY is only used on Wear
1067 addSupportedType(TYPE_PROXY);
1068 }
1069 // Ethernet is often not specified in the configs, although many devices can use it via
1070 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001071 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001072 addSupportedType(TYPE_ETHERNET);
1073 }
1074
1075 // Always add TYPE_VPN as a supported type
1076 addSupportedType(TYPE_VPN);
1077 }
1078
1079 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001080 if (mTypeLists[type] != null) {
1081 throw new IllegalStateException(
1082 "legacy list for type " + type + "already initialized");
1083 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001084 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001085 }
1086
Robert Greenwalt802c1102014-06-02 15:32:02 -07001087 public boolean isTypeSupported(int type) {
1088 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1089 }
1090
1091 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001092 synchronized (mTypeLists) {
1093 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1094 return mTypeLists[type].get(0);
1095 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001096 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001097 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001098 }
1099
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001100 public int getRestoreTimerForType(int type) {
1101 synchronized (mTypeLists) {
1102 if (mRestoreTimers == null) {
1103 mRestoreTimers = loadRestoreTimers();
1104 }
1105 return mRestoreTimers.getOrDefault(type, -1);
1106 }
1107 }
1108
1109 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1110 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001111 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001112 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1113 for (final String config : configs) {
1114 final String[] splits = TextUtils.split(config, ",");
1115 if (splits.length != 2) {
1116 logwtf("Invalid restore timer token count: " + config);
1117 continue;
1118 }
1119 try {
1120 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1121 } catch (NumberFormatException e) {
1122 logwtf("Invalid restore timer number format: " + config, e);
1123 }
1124 }
1125 return ret;
1126 }
1127
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001128 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001129 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001130 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001131 log("Sending " + state
1132 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001133 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001134 }
1135 }
1136
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001137 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1138 // network type, to preserve previous behaviour.
1139 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1140 if (vpnNai != mService.getLegacyLockdownNai()) return;
1141
1142 if (vpnNai.declaredUnderlyingNetworks == null
1143 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1144 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1145 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1146 return;
1147 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001148 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001149 vpnNai.declaredUnderlyingNetworks[0]);
1150 if (underlyingNai == null) return;
1151
1152 final int type = underlyingNai.networkInfo.getType();
1153 final DetailedState state = DetailedState.CONNECTED;
1154 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1155 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1156 }
1157
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001158 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001159 public void add(int type, NetworkAgentInfo nai) {
1160 if (!isTypeSupported(type)) {
1161 return; // Invalid network type.
1162 }
1163 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1164
1165 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1166 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001167 return;
1168 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001169 synchronized (mTypeLists) {
1170 list.add(nai);
1171 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001172
Chalard Jean5b409c72021-02-04 13:12:59 +09001173 // Send a broadcast if this is the first network of its type or if it's the default.
1174 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001175
1176 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1177 // to preserve previous behaviour.
1178 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001179 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001180 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1181 mService.sendLegacyNetworkBroadcast(nai, state, type);
1182 }
1183
1184 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1185 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001186 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001187 }
1188
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001189 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001190 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001191 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1192 if (list == null || list.isEmpty()) {
1193 return;
1194 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001195 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001196
Hugo Benichi389633f2016-06-21 09:48:07 +09001197 synchronized (mTypeLists) {
1198 if (!list.remove(nai)) {
1199 return;
1200 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001201 }
1202
Lorenzo Colitti49767722015-05-01 00:30:10 +09001203 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001204 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1205 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001206 }
1207
1208 if (!list.isEmpty() && wasFirstNetwork) {
1209 if (DBG) log("Other network available for type " + type +
1210 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001211 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001212 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001213 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001214 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001215 }
1216 }
1217
1218 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001219 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1220 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001221 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001222 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001223 }
1224 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001225
Chalard Jean46bfbf02022-02-02 00:56:25 +09001226 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001227 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001228 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001229 final DetailedState state = nai.networkInfo.getDetailedState();
1230 for (int type = 0; type < mTypeLists.length; type++) {
1231 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001232 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001233 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001234 if (isFirst || contains && isDefault) {
1235 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001236 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001237 }
1238 }
1239 }
1240
Robert Greenwalt94e22142014-07-30 16:31:24 -07001241 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001242 pw.println("mLegacyTypeTracker:");
1243 pw.increaseIndent();
1244 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001245 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001246 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001247 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001248 pw.println();
1249 pw.println("Current state:");
1250 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001251 synchronized (mTypeLists) {
1252 for (int type = 0; type < mTypeLists.length; type++) {
1253 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1254 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001255 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001256 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001257 }
1258 }
1259 pw.decreaseIndent();
1260 pw.decreaseIndent();
1261 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001262 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001263 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001264 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001265
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001266 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001267 /**
1268 * Helper class which parses out priority arguments and dumps sections according to their
1269 * priority. If priority arguments are omitted, function calls the legacy dump command.
1270 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001271 private class LocalPriorityDump {
1272 private static final String PRIORITY_ARG = "--dump-priority";
1273 private static final String PRIORITY_ARG_HIGH = "HIGH";
1274 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001275 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001276
1277 LocalPriorityDump() {}
1278
1279 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001280 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> {
Junyu Laif8dba342023-10-12 17:01:03 +08001281 doDump(fd, pw, new String[]{DIAG_ARG});
1282 doDump(fd, pw, new String[]{SHORT_ARG});
1283 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1284 pw.println("dumpHigh timeout");
1285 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001286 }
1287
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001288 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001289 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> doDump(fd, pw, args),
Junyu Laif8dba342023-10-12 17:01:03 +08001290 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1291 pw.println("dumpNormal timeout");
1292 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001293 }
1294
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001295 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1296 if (args == null) {
1297 dumpNormal(fd, pw, args);
1298 return;
1299 }
1300
1301 String priority = null;
1302 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1303 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1304 argIndex++;
1305 priority = args[argIndex];
1306 }
1307 }
1308
1309 if (PRIORITY_ARG_HIGH.equals(priority)) {
1310 dumpHigh(fd, pw);
1311 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1312 dumpNormal(fd, pw, args);
1313 } else {
1314 // ConnectivityService publishes binder service using publishBinderService() with
1315 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001316 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1317 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001318 // TODO: Integrate into signal dump.
1319 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001320 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001321 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001322 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001323
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001324 /**
1325 * Dependencies of ConnectivityService, for injection in tests.
1326 */
1327 @VisibleForTesting
1328 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001329 public int getCallingUid() {
1330 return Binder.getCallingUid();
1331 }
1332
Chalard Jeandf29a852023-05-29 17:02:43 +09001333 public boolean isAtLeastS() {
1334 return SdkLevel.isAtLeastS();
1335 }
1336
1337 public boolean isAtLeastT() {
1338 return SdkLevel.isAtLeastT();
1339 }
1340
1341 public boolean isAtLeastU() {
1342 return SdkLevel.isAtLeastU();
1343 }
1344
Chalard Jeaneb663892023-10-07 15:17:07 +09001345 public boolean isAtLeastV() {
1346 return SdkLevel.isAtLeastV();
1347 }
1348
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001349 /**
1350 * Get system properties to use in ConnectivityService.
1351 */
1352 public MockableSystemProperties getSystemProperties() {
1353 return new MockableSystemProperties();
1354 }
1355
1356 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001357 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1358 */
1359 public ConnectivityResources getResources(@NonNull Context ctx) {
1360 return new ConnectivityResources(ctx);
1361 }
1362
1363 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001364 * Create a HandlerThread to use in ConnectivityService.
1365 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001366 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1367 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001368 }
1369
1370 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001371 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001372 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001373 public NetworkStackClientBase getNetworkStack() {
1374 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001375 }
1376
1377 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001378 * @see ProxyTracker
1379 */
1380 public ProxyTracker makeProxyTracker(@NonNull Context context,
1381 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001382 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001383 }
1384
1385 /**
1386 * @see NetIdManager
1387 */
1388 public NetIdManager makeNetIdManager() {
1389 return new NetIdManager();
1390 }
1391
1392 /**
1393 * @see NetworkUtils#queryUserAccess(int, int)
1394 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001395 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1396 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001397 }
1398
1399 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001400 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1401 * requires CAP_NET_ADMIN, which the unit tests do not have.
1402 */
1403 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1404 InetSocketAddress remote) {
1405 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1406 }
1407
1408 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001409 * @see MultinetworkPolicyTracker
1410 */
1411 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1412 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1413 return new MultinetworkPolicyTracker(c, h, r);
1414 }
1415
Aaron Huang330a4c02020-10-27 03:36:19 +08001416 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001417 * @see AutomaticOnOffKeepaliveTracker
1418 */
1419 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1420 @NonNull Context c, @NonNull Handler h) {
1421 return new AutomaticOnOffKeepaliveTracker(c, h);
1422 }
1423
1424 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001425 * @see BatteryStatsManager
1426 */
1427 public void reportNetworkInterfaceForTransports(Context context, String iface,
1428 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001429 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001430 context.getSystemService(BatteryStatsManager.class);
1431 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1432 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001433
1434 public boolean getCellular464XlatEnabled() {
1435 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1436 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001437
1438 /**
1439 * @see PendingIntent#intentFilterEquals
1440 */
1441 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1442 return a.intentFilterEquals(b);
1443 }
1444
1445 /**
1446 * @see LocationPermissionChecker
1447 */
1448 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1449 return new LocationPermissionChecker(context);
1450 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001451
1452 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001453 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001454 *
1455 * This method returns null in versions before T, where carrier privilege
1456 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001457 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001458 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001459 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1460 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001461 if (isAtLeastT()) {
Chalard Jean96ff9542023-11-02 14:24:47 +09001462 return new CarrierPrivilegeAuthenticator(context, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001463 } else {
1464 return null;
1465 }
1466 }
1467
1468 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001469 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001470 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001471 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001472 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001473 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001474
1475 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001476 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1477 */
1478 public boolean isFeatureNotChickenedOut(Context context, String name) {
1479 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1480 }
1481
1482 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001483 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001484 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001485 * @return BpfNetMaps implementation.
1486 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001487 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1488 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001489 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001490
1491 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001492 * @see ClatCoordinator
1493 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001494 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001495 public ClatCoordinator getClatCoordinator(INetd netd) {
1496 return new ClatCoordinator(
1497 new ClatCoordinator.Dependencies() {
1498 @NonNull
1499 public INetd getNetd() {
1500 return netd;
1501 }
1502 });
1503 }
1504
1505 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001506 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1507 */
1508 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1509 final InterfaceParams params = InterfaceParams.getByName(iface);
1510 if (params == null) {
1511 // the interface might have disappeared.
1512 logw("Failed to get interface params for interface " + iface);
1513 return;
1514 }
1515 try {
1516 // converting rateInBytesPerSecond from long to int is safe here because the
1517 // setting's range is limited to INT_MAX.
1518 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001519 Log.i(TAG,
1520 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001521 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1522 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1523 } catch (IOException e) {
1524 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1525 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1526 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1527 + ") failure: ", e);
1528 }
1529 }
1530
1531 /**
1532 * Wraps {@link TcUtils#tcFilterDelDev}
1533 */
1534 public void disableIngressRateLimit(String iface) {
1535 final InterfaceParams params = InterfaceParams.getByName(iface);
1536 if (params == null) {
1537 // the interface might have disappeared.
1538 logw("Failed to get interface params for interface " + iface);
1539 return;
1540 }
1541 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001542 Log.i(TAG,
1543 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001544 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1545 } catch (IOException e) {
1546 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1547 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1548 }
1549 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001550
1551 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001552 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1553 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001554 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001555 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001556 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001557 }
1558
1559 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001560 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1561 */
1562 // TODO: when available in all active branches:
1563 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1564 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1565 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1566 return BroadcastOptionsShimImpl.newInstance(options);
1567 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001568
1569 /**
1570 * Wrapper method for
1571 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1572 *
1573 * @param changeId The ID of the compatibility change in question.
1574 * @param packageName The package name of the app in question.
1575 * @param user The user that the operation is done for.
1576 * @return {@code true} if the change is enabled for the specified package.
1577 */
1578 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1579 @NonNull final UserHandle user) {
1580 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1581 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001582
1583 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001584 * As above but with a UID.
1585 * @see CompatChanges#isChangeEnabled(long, int)
1586 */
1587 public boolean isChangeEnabled(final long changeId, final int uid) {
1588 return CompatChanges.isChangeEnabled(changeId, uid);
1589 }
1590
1591 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001592 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1593 *
1594 * @param ranges target uid ranges
1595 * @param exemptUids uids to skip close socket
1596 */
1597 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1598 @NonNull final Set<Integer> exemptUids)
1599 throws SocketException, InterruptedIOException, ErrnoException {
1600 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1601 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001602
1603 /**
1604 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1605 *
1606 * @param ownerUids target uids to close sockets
1607 */
1608 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1609 throws SocketException, InterruptedIOException, ErrnoException {
1610 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1611 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001612
1613 /**
1614 * Schedule the evaluation timeout.
1615 *
1616 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1617 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1618 * of these events happen, this time will run out, after which the network is considered
1619 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1620 * on this network and considers it won't provide connectivity. In particular, that means
1621 * it's when the system prefers it to cell if it's wifi and configuration says it should
1622 * prefer bad wifi to cell.
1623 */
1624 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1625 @NonNull final Network network, final long delayMs) {
1626 handler.sendMessageDelayed(
1627 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1628 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001629 }
1630
junyulaie7c7d2a2021-01-26 15:29:15 +08001631 public ConnectivityService(Context context) {
1632 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001633 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1634 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001635 }
1636
1637 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001638 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1639 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001640 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001641
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001642 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001643 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001644 mSystemProperties = mDeps.getSystemProperties();
1645 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001646 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001647 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001648 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1649 // Pass limit - 1 to maintain backward compatibility.
1650 // TODO: Remove the workaround.
1651 mNetworkRequestCounter =
1652 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1653 mSystemNetworkRequestCounter =
1654 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001655
Hugo Benichi208c0102016-07-28 17:53:06 +09001656 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001657 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1658 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001659 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001660 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001661 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001662 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1663 mDefaultNetworkRequests.add(mDefaultRequest);
1664 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001665
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001666 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001667 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001668
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001669 // The default WiFi request is a background request so that apps using WiFi are
1670 // migrated to a better network (typically ethernet) when one comes up, instead
1671 // of staying on WiFi forever.
1672 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1673 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1674
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001675 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1676 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1677 NetworkRequest.Type.BACKGROUND_REQUEST);
1678
Chalard Jean0702f982021-09-16 21:50:07 +09001679 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1680 // TODO: Consider making the timer customizable.
1681 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1682 mCellularRadioTimesharingCapable =
1683 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1684
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001685 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1686 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1687
1688 if (SdkLevel.isAtLeastU()) {
1689 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1690 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1691 final int defaultUMarkMask = 0x80000000; // u32
1692
1693 if ((mark == 0) || (mask == 0)) {
1694 // simply treat unset/disabled as the default U value
1695 mark = defaultUMarkMask;
1696 mask = defaultUMarkMask;
1697 }
1698 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1699 // invalid device overlay settings
1700 throw new IllegalArgumentException(
1701 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1702 }
1703 }
1704
1705 mWakeUpMark = mark;
1706 mWakeUpMask = mask;
1707
Paul Hu51f816b2022-08-11 14:43:47 +00001708 mNetd = netd;
1709 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Chalard Jean96ff9542023-11-02 14:24:47 +09001710 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Paul Hu51f816b2022-08-11 14:43:47 +00001711 mPermissionMonitor =
1712 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001713 mHandlerThread.start();
1714 mHandler = new InternalHandler(mHandlerThread.getLooper());
1715 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001716 mConnectivityDiagnosticsHandler =
1717 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001718
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001719 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001720 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001721
junyulaie7c7d2a2021-01-26 15:29:15 +08001722 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001723 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001724 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001725 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001726
Wink Saville32506bc2013-06-29 21:10:57 -07001727 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001728 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001729 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001730 mCarrierPrivilegeAuthenticator =
1731 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001732
Sudheer Shanka9967d462021-03-18 19:09:25 +00001733 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001734 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1735 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001736 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001737
1738 final PowerManager powerManager = (PowerManager) context.getSystemService(
1739 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001740 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001741 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001742
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001743 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1744 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001745 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001746 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001747 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001748 mProtectedNetworks.add(p);
1749 } else {
1750 if (DBG) loge("Ignoring protectedNetwork " + p);
1751 }
1752 }
1753
soma, kawata29444ae2019-05-23 09:30:40 +09001754 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1755
James Mattis02220e22021-03-13 19:27:21 -08001756 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001757 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001758 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001759 final IntentFilter userIntentFilter = new IntentFilter();
1760 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1761 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1762 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1763 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001764
James Mattis02220e22021-03-13 19:27:21 -08001765 // Listen to package add/removes for netd
1766 final IntentFilter packageIntentFilter = new IntentFilter();
1767 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1768 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1769 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1770 packageIntentFilter.addDataScheme("package");
1771 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001772 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001773
Junyu Lai38c75032023-12-04 07:52:19 +00001774 // This is needed for pre-V devices to propagate the data saver status
1775 // to the BPF map. This isn't supported before Android T because BPF maps are
1776 // unsupported, and it's also unnecessary on Android V and later versions,
1777 // as the platform code handles data saver bit updates. Additionally, checking
1778 // the initial data saver status here is superfluous because the intent won't
1779 // be sent until the system is ready.
1780 if (mDeps.isAtLeastT() && !mDeps.isAtLeastV()) {
1781 final IntentFilter dataSaverIntentFilter =
1782 new IntentFilter(ACTION_RESTRICT_BACKGROUND_CHANGED);
1783 mUserAllContext.registerReceiver(mDataSaverReceiver, dataSaverIntentFilter,
1784 null /* broadcastPermission */, mHandler);
1785 }
1786
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09001787 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
1788 // But reading the trunk stable flags from mainline modules is not supported yet.
1789 // So enabling this feature on V+ release.
1790 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
1791 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
1792 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001793
Chalard Jean46bfbf02022-02-02 00:56:25 +09001794 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001795 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001796 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001797 } catch (RemoteException | ServiceSpecificException e) {
1798 loge("Error registering event listener :" + e);
1799 }
1800
Erik Kline05f2b402015-04-30 12:58:40 +09001801 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1802 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001803
chiachangwang7c17c282023-02-02 05:58:59 +00001804 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001805 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001806 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001807
1808 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001809 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001810 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1811 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001812 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001813 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1814 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001815
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001816 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001817 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001818 mNetworkRanker =
1819 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1820
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001821 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001822
Chiachang Wangc1215d32020-10-20 15:38:58 +08001823 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001824 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001825
Chalard Jean28018572020-12-21 18:36:52 +09001826 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1827 // request that doesn't allow fallback to the default network. It should never be visible
1828 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1829 // arguments like the handler or the DnsResolver.
1830 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001831 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001832 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001833 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001834 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001835 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001836 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1837 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001838
1839 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001840 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1841 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1842 // Even if it could, running on S would at least require mocking out the BPF map,
1843 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1844 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001845 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001846 mDscpPolicyTracker = new DscpPolicyTracker();
1847 }
Tyler Wear72388212021-09-09 14:49:02 -07001848 } catch (ErrnoException e) {
1849 loge("Unable to create DscpPolicyTracker");
1850 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001851
1852 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1853 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001854
Chalard Jeandf29a852023-05-29 17:02:43 +09001855 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001856 mCdmps = new CompanionDeviceManagerProxyService(context);
1857 } else {
1858 mCdmps = null;
1859 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001860
Chalard Jean2fb66f12023-08-25 12:50:37 +09001861 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
1862
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001863 mDestroyFrozenSockets = mDeps.isAtLeastU()
1864 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1865 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1866 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001867 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1868 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001869 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001870 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1871 new UidFrozenStateChangedCallback() {
1872 @Override
1873 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1874 if (uids.length != frozenStates.length) {
1875 Log.wtf(TAG, "uids has length " + uids.length
1876 + " but frozenStates has length " + frozenStates.length);
1877 return;
1878 }
1879
1880 final UidFrozenStateChangedArgs args =
1881 new UidFrozenStateChangedArgs(uids, frozenStates);
1882
1883 mHandler.sendMessage(
1884 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1885 }
1886 };
1887
1888 final ActivityManager activityManager =
1889 mContext.getSystemService(ActivityManager.class);
1890 activityManager.registerUidFrozenStateChangedCallback(
1891 (Runnable r) -> r.run(), frozenStateChangedCallback);
1892 }
Yuyang Huang41557552023-11-28 12:47:22 +09001893
1894 if (mDeps.isFeatureNotChickenedOut(mContext, LOG_BPF_RC)) {
1895 mHandler.post(BpfLoaderRcUtils::checkBpfLoaderRc);
1896 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001897 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001898
Xiao Ma0a171c02022-01-23 16:14:51 +00001899 /**
1900 * Check whether or not the device supports Ethernet transport.
1901 */
1902 public static boolean deviceSupportsEthernet(final Context context) {
1903 final PackageManager pm = context.getPackageManager();
1904 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1905 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1906 }
1907
Chalard Jean46adcf32018-04-18 20:18:38 +09001908 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001909 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1910 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001911 }
1912
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001913 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1914 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001915 final NetworkCapabilities netCap = new NetworkCapabilities();
1916 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001917 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001918 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001919 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001920 return netCap;
1921 }
1922
James Mattis45d81842021-01-10 14:24:24 -08001923 private NetworkRequest createDefaultRequest() {
1924 return createDefaultInternetRequestForTransport(
1925 TYPE_NONE, NetworkRequest.Type.REQUEST);
1926 }
1927
lucaslin3ba7cc22022-12-19 02:35:33 +00001928 private NetworkRequest createVpnRequest() {
1929 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1930 .withoutDefaultCapabilities()
1931 .addTransportType(TRANSPORT_VPN)
1932 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1933 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1934 .build();
1935 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1936 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1937 }
1938
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001939 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001940 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001941 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001942 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001943 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001944 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001945 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001946 netCap.addTransportType(transportType);
1947 }
James Mattis45d81842021-01-10 14:24:24 -08001948 return createNetworkRequest(type, netCap);
1949 }
1950
1951 private NetworkRequest createNetworkRequest(
1952 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001953 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001954 }
1955
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001956 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1957 NetworkRequest.Type type) {
1958 final NetworkCapabilities netCap = new NetworkCapabilities();
1959 netCap.clearAll();
1960 netCap.addCapability(capability);
1961 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1962 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1963 }
1964
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001965 // Used only for testing.
1966 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001967 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001968 // changing ContentResolver to make registerContentObserver non-final).
1969 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1970 // by subclassing SettingsObserver.
1971 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001972 void updateAlwaysOnNetworks() {
1973 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001974 }
1975
Erik Kline9a62f012018-03-21 07:18:33 -07001976 // See FakeSettingsProvider comment above.
1977 @VisibleForTesting
1978 void updatePrivateDnsSettings() {
1979 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1980 }
1981
paulhu51f77dc2021-06-07 02:34:20 +00001982 @VisibleForTesting
1983 void updateMobileDataPreferredUids() {
1984 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1985 }
1986
Patrick Rohr2857ac42022-01-21 14:58:16 +01001987 @VisibleForTesting
1988 void updateIngressRateLimit() {
1989 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1990 }
1991
Aaron Huang40b52442021-06-08 04:34:24 +08001992 @VisibleForTesting
1993 void simulateUpdateProxyInfo(@Nullable final Network network,
1994 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001995 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001996 new Pair<>(network, proxyInfo)).sendToTarget();
1997 }
1998
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001999 private void handleAlwaysOnNetworkRequest(
2000 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002001 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002002 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002003 handleAlwaysOnNetworkRequest(networkRequest, enable);
2004 }
2005
2006 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002007 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002008 if (enable == isEnabled) {
2009 return; // Nothing to do.
2010 }
2011
2012 if (enable) {
2013 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002014 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002015 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002016 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002017 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002018 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2019 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002020 }
2021 }
2022
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002023 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002024 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2025 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2026 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2027 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002028 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2029 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002030 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002031 }
2032
paulhu51f77dc2021-06-07 02:34:20 +00002033 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002034 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002035 private void registerSettingsCallbacks() {
2036 // Watch for global HTTP proxy changes.
2037 mSettingsObserver.observe(
2038 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2039 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2040
Chalard Jean46bfbf02022-02-02 00:56:25 +09002041 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002042 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002043 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002044 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2045
Chalard Jean46bfbf02022-02-02 00:56:25 +09002046 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002047 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002048 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002049 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002050
2051 // Watch for mobile data preferred uids changes.
2052 mSettingsObserver.observe(
2053 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2054 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002055
2056 // Watch for ingress rate limit changes.
2057 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002058 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002059 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2060 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002061 }
2062
Erik Kline31b4a9e2018-01-11 21:07:29 +09002063 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002064 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2065 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002066 }
2067 }
2068
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002069 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002070 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2071 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002072 return mNextNetworkRequestId++;
2073 }
2074
junyulai74f9a8b2018-06-13 15:00:37 +08002075 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002076 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002077 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002078 if (network == null) {
2079 return null;
2080 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002081 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002082 }
2083
2084 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002085 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002086 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002087 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002088 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002089
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002090 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002091 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002092 private NetworkAgentInfo getVpnForUid(int uid) {
2093 synchronized (mNetworkForNetId) {
2094 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2095 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002096 if (nai.isVPN() && nai.everConnected()
2097 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002098 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002099 }
2100 }
2101 }
2102 return null;
2103 }
2104
Chalard Jean46bfbf02022-02-02 00:56:25 +09002105 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002106 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002107 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002108 final NetworkAgentInfo nai = getVpnForUid(uid);
2109 if (nai != null) return nai.declaredUnderlyingNetworks;
2110 return null;
2111 }
2112
Lorenzo Colittia7574052021-01-19 01:33:05 +09002113 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002114 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002115
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002116 final Network[] networks = getVpnUnderlyingNetworks(uid);
2117 if (networks != null) {
2118 // getUnderlyingNetworks() returns:
2119 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2120 // empty array => the VPN explicitly said "no default network".
2121 // non-empty array => the VPN specified one or more default networks; we use the
2122 // first one.
2123 if (networks.length > 0) {
2124 nai = getNetworkAgentInfoForNetwork(networks[0]);
2125 } else {
2126 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002127 }
2128 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002129 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002130 }
2131
2132 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002133 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002134 */
paulhu7aeba372020-12-30 00:42:19 +08002135 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2136 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002137 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002138 if (ignoreBlocked) {
2139 return false;
2140 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002141 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002142 final long ident = Binder.clearCallingIdentity();
2143 try {
2144 final boolean metered = nc == null ? true : nc.isMetered();
2145 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2146 } finally {
2147 Binder.restoreCallingIdentity(ident);
2148 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002149 }
2150
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002151 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002152 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2153 return;
2154 }
Hugo Benichi47011212017-03-30 10:46:05 +09002155 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002156 synchronized (mBlockedAppUids) {
2157 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002158 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002159 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002160 blocked = false;
2161 } else {
2162 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002163 }
2164 }
Hugo Benichi47011212017-03-30 10:46:05 +09002165 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2166 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2167 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002168 }
2169
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002170 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002171 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2172 return;
2173 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002174 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002175 final int requestId = nri.getActiveRequest() != null
2176 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002177 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002178 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002179 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002180 }
2181
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002182 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002183 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002184 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002185 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002186 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002187 @NonNull
2188 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2189 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002190 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2191 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2192 // but only exists if an app asks about them or requests them. Ensure the requesting app
2193 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002194 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002195 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2196 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2197 null /* extraInfo */);
2198 }
2199 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002200 return filtered;
2201 }
2202
2203 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2204 boolean ignoreBlocked) {
2205 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2206 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002207 }
2208
2209 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002210 * Return NetworkInfo for the active (i.e., connected) network interface.
2211 * It is assumed that at most one network is active at a time. If more
2212 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002213 * @return the info for the active network, or {@code null} if none is
2214 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002215 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002216 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002217 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002218 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002219 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002220 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002221 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2222 if (nai == null) return null;
2223 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2224 maybeLogBlockedNetworkInfo(networkInfo, uid);
2225 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002226 }
2227
Paul Jensen1f567382015-02-13 14:18:39 -05002228 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002229 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002230 public Network getActiveNetwork() {
2231 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002232 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002233 }
2234
2235 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002236 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002237 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002238 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002239 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002240 }
2241
Chalard Jean46bfbf02022-02-02 00:56:25 +09002242 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002243 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002244 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2245 if (vpnNai != null) {
2246 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2247 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2248 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002249 }
Paul Jensen1f567382015-02-13 14:18:39 -05002250 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002251
James Mattis2516da32021-01-31 17:06:19 -08002252 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002253 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2254 ignoreBlocked)) {
2255 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002256 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002257 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002258 }
2259
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002260 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002261 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002262 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002263 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002264 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2265 if (nai == null) return null;
2266 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002267 }
2268
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002269 /** Returns a NetworkInfo object for a network that doesn't exist. */
2270 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2271 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2272 getNetworkTypeName(networkType), "" /* subtypeName */);
2273 info.setIsAvailable(true);
2274 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2275 // background data is restricted.
2276 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2277 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2278 ? DetailedState.BLOCKED
2279 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002280 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2281 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002282 return info;
2283 }
2284
Lorenzo Colittia7574052021-01-19 01:33:05 +09002285 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002286 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2287 return null;
2288 }
2289 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002290 if (nai == null) {
2291 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002292 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002293 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2294 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002295 }
2296
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002297 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002298 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002299 public NetworkInfo getNetworkInfo(int networkType) {
2300 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002301 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002302 if (getVpnUnderlyingNetworks(uid) != null) {
2303 // A VPN is active, so we may need to return one of its underlying networks. This
2304 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002305 // getNetworkAgentInfoForUid.
2306 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2307 if (nai == null) return null;
2308 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2309 if (networkInfo.getType() == networkType) {
2310 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002311 }
2312 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002313 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002314 }
2315
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002316 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002317 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002318 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002319 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002320 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002321 if (nai == null) return null;
2322 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002323 }
2324
2325 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002326 public NetworkInfo[] getAllNetworkInfo() {
2327 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002328 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002329 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2330 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002331 NetworkInfo info = getNetworkInfo(networkType);
2332 if (info != null) {
2333 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002334 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002335 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002336 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002337 }
2338
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002339 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002340 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002341 public Network getNetworkForType(int networkType) {
2342 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002343 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2344 return null;
2345 }
2346 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2347 if (nai == null) {
2348 return null;
2349 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002350 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002351 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2352 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002353 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002354 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002355 }
2356
2357 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002358 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002359 public Network[] getAllNetworks() {
2360 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002361 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002362 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002363 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002364 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002365 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002366 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002367 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002368 }
2369
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002370 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002371 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002372 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002373 // The basic principle is: if an app's traffic could possibly go over a
2374 // network, without the app doing anything multinetwork-specific,
2375 // (hence, by "default"), then include that network's capabilities in
2376 // the array.
2377 //
2378 // In the normal case, app traffic only goes over the system's default
2379 // network connection, so that's the only network returned.
2380 //
2381 // With a VPN in force, some app traffic may go into the VPN, and thus
2382 // over whatever underlying networks the VPN specifies, while other app
2383 // traffic may go over the system default network (e.g.: a split-tunnel
2384 // VPN, or an app disallowed by the VPN), so the set of networks
2385 // returned includes the VPN's underlying networks and the system
2386 // default.
2387 enforceAccessPermission();
2388
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002389 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002390
James Mattis2516da32021-01-31 17:06:19 -08002391 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2392 if (!nri.isBeingSatisfied()) {
2393 continue;
2394 }
2395 final NetworkAgentInfo nai = nri.getSatisfier();
2396 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2397 if (null != nc
2398 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2399 && !result.containsKey(nai.network)) {
2400 result.put(
2401 nai.network,
2402 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002403 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002404 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2405 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002406 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002407 }
2408
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002409 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002410 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002411 if (null != networks) {
2412 for (final Network network : networks) {
2413 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2414 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002415 result.put(
2416 network,
2417 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002418 nc,
2419 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002420 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002421 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002422 }
2423 }
2424 }
2425
2426 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2427 out = result.values().toArray(out);
2428 return out;
2429 }
2430
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002431 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2432 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2433 // can call sampleConnectivityState and make the checks on it.
2434 @NonNull
2435 private StatsEvent sampleConnectivityStateToStatsEvent() {
2436 final ConnectivityStateSample sample = sampleConnectivityState();
2437 return ConnectivityStatsLog.buildStatsEvent(
2438 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2439 sample.getNetworkCountPerTransports().toByteArray(),
2440 sample.getConnectionDurationPerTransports().toByteArray(),
2441 sample.getNetworkRequestCount().toByteArray(),
2442 sample.getNetworks().toByteArray());
2443 }
2444
2445 /**
2446 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2447 *
2448 * This is used for metrics. These snapshots will be sampled and constitute a base for
2449 * statistics about connectivity state of devices.
2450 */
2451 @VisibleForTesting
2452 @NonNull
2453 public ConnectivityStateSample sampleConnectivityState() {
2454 ensureRunningOnConnectivityServiceThread();
2455 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2456 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2457 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2458 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2459 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2460 return builder.build();
2461 }
2462
2463 private static NetworkCountPerTransports sampleNetworkCount(
2464 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2465 final SparseIntArray countPerTransports = new SparseIntArray();
2466 for (final NetworkAgentInfo nai : nais) {
2467 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2468 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2469 }
2470 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2471 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2472 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2473 c.setTransportTypes(countPerTransports.keyAt(i));
2474 c.setNetworkCount(countPerTransports.valueAt(i));
2475 builder.addNetworkCountForTransports(c);
2476 }
2477 return builder.build();
2478 }
2479
2480 private static ConnectionDurationPerTransports sampleConnectionDuration(
2481 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2482 final ConnectionDurationPerTransports.Builder builder =
2483 ConnectionDurationPerTransports.newBuilder();
2484 for (final NetworkAgentInfo nai : nais) {
2485 final ConnectionDurationForTransports.Builder c =
2486 ConnectionDurationForTransports.newBuilder();
2487 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2488 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2489 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2490 // Add millisPerSecond/2 to round up or down to the nearest value
2491 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2492 builder.addConnectionDurationForTransports(c);
2493 }
2494 return builder.build();
2495 }
2496
2497 private static NetworkRequestCount sampleNetworkRequestCount(
2498 @NonNull final Collection<NetworkRequestInfo> nris) {
2499 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2500 final SparseIntArray countPerType = new SparseIntArray();
2501 for (final NetworkRequestInfo nri : nris) {
2502 final int type;
2503 if (Process.SYSTEM_UID == nri.mAsUid) {
2504 // The request is filed "as" the system, so it's the system on its own behalf.
2505 type = RequestType.RT_SYSTEM.getNumber();
2506 } else if (Process.SYSTEM_UID == nri.mUid) {
2507 // The request is filed by the system as some other app, so it's the system on
2508 // behalf of an app.
2509 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2510 } else {
2511 // Not the system, so it's an app requesting on its own behalf.
2512 type = RequestType.RT_APP.getNumber();
2513 }
2514 countPerType.put(type, countPerType.get(type, 0));
2515 }
2516 for (int i = countPerType.size() - 1; i >= 0; --i) {
2517 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2518 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2519 r.setRequestCount(countPerType.valueAt(i));
2520 builder.addRequestCountForType(r);
2521 }
2522 return builder.build();
2523 }
2524
2525 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2526 final NetworkList.Builder builder = NetworkList.newBuilder();
2527 for (final NetworkAgentInfo nai : nais) {
2528 final NetworkCapabilities nc = nai.networkCapabilities;
2529 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2530 d.setTransportTypes((int) nc.getTransportTypesInternal());
2531 final MeteredState meteredState;
2532 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2533 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2534 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2535 meteredState = MeteredState.METERED_NO;
2536 } else {
2537 meteredState = MeteredState.METERED_YES;
2538 }
2539 d.setMeteredState(meteredState);
2540 final ValidatedState validatedState;
2541 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2542 validatedState = ValidatedState.VS_PORTAL;
2543 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2544 validatedState = ValidatedState.VS_PARTIAL;
2545 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2546 validatedState = ValidatedState.VS_VALID;
2547 } else {
2548 validatedState = ValidatedState.VS_INVALID;
2549 }
2550 d.setValidatedState(validatedState);
2551 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2552 d.setCapabilities(nc.getCapabilitiesInternal());
2553 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2554 builder.addNetworkDescription(d);
2555 }
2556 return builder.build();
2557 }
2558
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002559 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002560 public boolean isNetworkSupported(int networkType) {
2561 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002562 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002563 }
2564
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002565 /**
2566 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002567 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002568 * @return the ip properties for the active network, or {@code null} if
2569 * none is active
2570 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002571 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002572 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002573 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002574 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002575 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2576 if (nai == null) return null;
2577 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002578 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002579 }
2580
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002581 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002582 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002583 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002584 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002585 final LinkProperties lp = getLinkProperties(nai);
2586 if (lp == null) return null;
2587 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002588 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002589 }
2590
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002591 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002592 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002593 public LinkProperties getLinkProperties(Network network) {
2594 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002595 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2596 if (lp == null) return null;
2597 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002598 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002599 }
2600
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002601 @Nullable
2602 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002603 if (nai == null) {
2604 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002605 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002606 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002607 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002608 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002609 }
2610
lucaslinc582d502022-01-27 09:07:00 +08002611 @Override
2612 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002613 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002614 @NonNull String packageName, @Nullable String callingAttributionTag) {
2615 Objects.requireNonNull(packageName);
2616 Objects.requireNonNull(lp);
2617 enforceNetworkStackOrSettingsPermission();
2618 if (!checkAccessPermission(-1 /* pid */, uid)) {
2619 return null;
2620 }
2621 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2622 }
2623
Qingxi Lib2748102020-01-08 12:51:49 -08002624 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2625 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2626 }
2627
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002628 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002629 if (nai == null) return null;
2630 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002631 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002632 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002633 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002634 }
2635
2636 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002637 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2638 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002639 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002640 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002641 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002642 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002643 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002644 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002645 }
2646
lucaslinc582d502022-01-27 09:07:00 +08002647 @Override
lucaslind2b06132022-03-02 10:56:57 +08002648 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2649 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2650 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002651 Objects.requireNonNull(nc);
2652 Objects.requireNonNull(packageName);
2653 enforceNetworkStackOrSettingsPermission();
2654 if (!checkAccessPermission(-1 /* pid */, uid)) {
2655 return null;
2656 }
2657 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2658 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2659 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2660 callingAttributionTag);
2661 }
2662
lucaslin69e1aa92022-03-22 18:15:09 +08002663 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2664 if (nc.getUnderlyingNetworks() != null
2665 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2666 nc.setUnderlyingNetworks(null);
2667 }
2668 }
2669
Chalard Jean53017782022-11-24 17:13:44 +09002670 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
2671 return Process.SYSTEM_UID == uid
Chalard Jean53017782022-11-24 17:13:44 +09002672 || checkAnyPermissionOf(mContext, pid, uid,
2673 android.Manifest.permission.NETWORK_FACTORY);
2674 }
2675
Qingxi Libb8da982020-01-17 17:54:27 -08002676 @VisibleForTesting
2677 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002678 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002679 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2680 // this would be expensive (one more permission check every time any NC callback is
2681 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2682 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2683 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002684 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002685 if (!checkSettingsPermission(callerPid, callerUid)) {
2686 newNc.setUids(null);
2687 newNc.setSSID(null);
2688 }
Etan Cohen107ae952018-12-30 17:59:59 -08002689 if (newNc.getNetworkSpecifier() != null) {
2690 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2691 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002692 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2693 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002694 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2695 newNc.setAdministratorUids(new int[0]);
2696 }
Chalard Jean53017782022-11-24 17:13:44 +09002697 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09002698 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002699 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002700 }
lucaslin69e1aa92022-03-22 18:15:09 +08002701 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002702
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002703 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002704 }
2705
Roshan Pius98f59ec2021-02-23 08:47:39 -08002706 /**
2707 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002708 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002709 * NetworkCapabilities.
2710 * Note: This wrapper does not support any sort of invalidation and thus must not be
2711 * persistent or long-lived. It may only be used for the time necessary to
2712 * compute the redactions required by one particular NetworkCallback or
2713 * synchronous call.
2714 */
2715 private class RedactionPermissionChecker {
2716 private final int mCallingPid;
2717 private final int mCallingUid;
2718 @NonNull private final String mCallingPackageName;
2719 @Nullable private final String mCallingAttributionTag;
2720
2721 private Boolean mHasLocationPermission = null;
2722 private Boolean mHasLocalMacAddressPermission = null;
2723 private Boolean mHasSettingsPermission = null;
2724
2725 RedactionPermissionChecker(int callingPid, int callingUid,
2726 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2727 mCallingPid = callingPid;
2728 mCallingUid = callingUid;
2729 mCallingPackageName = callingPackageName;
2730 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002731 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002732
2733 private boolean hasLocationPermissionInternal() {
2734 final long token = Binder.clearCallingIdentity();
2735 try {
2736 return mLocationPermissionChecker.checkLocationPermission(
2737 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2738 null /* message */);
2739 } finally {
2740 Binder.restoreCallingIdentity(token);
2741 }
2742 }
2743
2744 /**
2745 * Returns whether the app holds location permission or not (might return cached result
2746 * if the permission was already checked before).
2747 */
2748 public boolean hasLocationPermission() {
2749 if (mHasLocationPermission == null) {
2750 // If there is no cached result, perform the check now.
2751 mHasLocationPermission = hasLocationPermissionInternal();
2752 }
2753 return mHasLocationPermission;
2754 }
2755
2756 /**
2757 * Returns whether the app holds local mac address permission or not (might return cached
2758 * result if the permission was already checked before).
2759 */
2760 public boolean hasLocalMacAddressPermission() {
2761 if (mHasLocalMacAddressPermission == null) {
2762 // If there is no cached result, perform the check now.
2763 mHasLocalMacAddressPermission =
2764 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2765 }
2766 return mHasLocalMacAddressPermission;
2767 }
2768
2769 /**
2770 * Returns whether the app holds settings permission or not (might return cached
2771 * result if the permission was already checked before).
2772 */
2773 public boolean hasSettingsPermission() {
2774 if (mHasSettingsPermission == null) {
2775 // If there is no cached result, perform the check now.
2776 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2777 }
2778 return mHasSettingsPermission;
2779 }
2780 }
2781
2782 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2783 @NetworkCapabilities.NetCapability long redaction) {
2784 return (redactions & redaction) != 0;
2785 }
2786
2787 /**
2788 * Use the provided |applicableRedactions| to check the receiving app's
2789 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2790 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2791 * before being sent to the corresponding app.
2792 */
2793 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2794 @NetworkCapabilities.RedactionType long applicableRedactions,
2795 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2796 boolean includeLocationSensitiveInfo) {
2797 long redactions = applicableRedactions;
2798 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2799 if (includeLocationSensitiveInfo
2800 && redactionPermissionChecker.hasLocationPermission()) {
2801 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2802 }
2803 }
2804 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2805 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2806 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2807 }
2808 }
2809 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2810 if (redactionPermissionChecker.hasSettingsPermission()) {
2811 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2812 }
2813 }
2814 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002815 }
2816
Qingxi Lib2748102020-01-08 12:51:49 -08002817 @VisibleForTesting
2818 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002819 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002820 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002821 int callingPid, int callingUid, @NonNull String callingPkgName,
2822 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002823 if (nc == null) {
2824 return null;
2825 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002826 // Avoid doing location permission check if the transport info has no location sensitive
2827 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002828 final RedactionPermissionChecker redactionPermissionChecker =
2829 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2830 callingAttributionTag);
2831 final long redactions = retrieveRequiredRedactions(
2832 nc.getApplicableRedactions(), redactionPermissionChecker,
2833 includeLocationSensitiveInfo);
2834 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002835 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002836 // TODO : calling UID is redacted because apps should generally not know what UID is
2837 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002838 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002839 newNc.setOwnerUid(INVALID_UID);
2840 return newNc;
2841 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002842 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2843 if (nc.hasTransport(TRANSPORT_VPN)) {
2844 // Owner UIDs already checked above. No need to re-check.
2845 return newNc;
2846 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002847 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2848 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002849 // compatibility for older apps.
2850 if (!includeLocationSensitiveInfo
2851 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002852 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002853 newNc.setOwnerUid(INVALID_UID);
2854 return newNc;
2855 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002856 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002857 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002858 newNc.setOwnerUid(INVALID_UID);
2859 }
Qingxi Lib2748102020-01-08 12:51:49 -08002860 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002861 }
2862
lucaslinc582d502022-01-27 09:07:00 +08002863 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002864 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2865 LinkProperties lp, int callerPid, int callerUid) {
2866 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002867 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2868 // this would be expensive (one more permission check every time any LP callback is
2869 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2870 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2871 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002872
2873 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2874 final boolean needsSanitization =
2875 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2876 if (!needsSanitization) {
2877 return new LinkProperties(lp);
2878 }
2879
2880 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002881 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002882 }
2883
2884 final LinkProperties newLp = new LinkProperties(lp);
2885 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2886 // object gets parceled.
2887 newLp.setCaptivePortalApiUrl(null);
2888 newLp.setCaptivePortalData(null);
2889 return newLp;
2890 }
2891
Roshan Pius08c94fb2020-01-16 12:17:17 -08002892 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2893 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002894 // There is no need to track the effective UID of the request here. If the caller
2895 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002896 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002897 // Unprivileged apps can only pass in null or their own UID.
2898 if (nc.getUids() == null) {
2899 // If the caller passes in null, the callback will also match networks that do not
2900 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2901 // In this case, redact everything in the request immediately. This ensures that the
2902 // app is not able to get any redacted information by filing an unredacted request
2903 // and observing whether the request matches something.
2904 if (nc.getNetworkSpecifier() != null) {
2905 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2906 }
2907 } else {
2908 nc.setSingleUid(callerUid);
2909 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002910 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002911 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002912 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002913
2914 // Clear owner UID; this can never come from an app.
2915 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002916 }
2917
Chalard Jean38354d12018-03-20 19:13:57 +09002918 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002919 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002920 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2921 }
2922 }
2923
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002924 @Override
2925 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2926 enforceAccessPermission();
2927 final int callerUid = Binder.getCallingUid();
2928 final long token = Binder.clearCallingIdentity();
2929 try {
2930 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2931 } finally {
2932 Binder.restoreCallingIdentity(token);
2933 }
2934 }
2935
junyulaiebd15162021-03-03 12:09:05 +08002936 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002937 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002938 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002939 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002940 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002941
Serik Beketayev05130302021-01-15 16:47:25 -08002942 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002943 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002944 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2945 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002946 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002947 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002948 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002949 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2950 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002951 }
2952 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002953 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002954 }
2955
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002956 @Override
junyulaiebd15162021-03-03 12:09:05 +08002957 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002958 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002959 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002960 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002961
2962 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2963 for (Network network : getAllNetworks()) {
2964 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002965 final boolean includeNetwork = (nai != null) && nai.isCreated();
2966 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002967 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2968 // NetworkCapabilities, which may contain UIDs of apps to which the
2969 // network applies. Should the UIDs be cleared so as not to leak or
2970 // interfere ?
2971 result.add(nai.getNetworkStateSnapshot());
2972 }
2973 }
2974 return result;
2975 }
2976
2977 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002978 public boolean isActiveNetworkMetered() {
2979 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002980
Qingxi Lib2748102020-01-08 12:51:49 -08002981 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002982 if (caps != null) {
2983 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2984 } else {
2985 // Always return the most conservative value
2986 return true;
2987 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002988 }
2989
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002990 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002991 * Ensures that the system cannot call a particular method.
2992 */
2993 private boolean disallowedBecauseSystemCaller() {
2994 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002995 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2996 // for devices launched with Q and above. However, existing devices upgrading to Q and
2997 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002998 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002999 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003000 log("This method exists only for app backwards compatibility"
3001 + " and must not be called by system services.");
3002 return true;
3003 }
3004 return false;
3005 }
3006
3007 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003008 * Ensure that a network route exists to deliver traffic to the specified
3009 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003010 * @param networkType the type of the network over which traffic to the
3011 * specified host is to be routed
3012 * @param hostAddress the IP address of the host to which the route is
3013 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003014 * @return {@code true} on success, {@code false} on failure
3015 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003016 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003017 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3018 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003019 if (disallowedBecauseSystemCaller()) {
3020 return false;
3021 }
Junyu Lai8fdc4312024-01-16 11:19:43 +08003022 PermissionUtils.enforcePackageNameMatchesUid(
3023 mContext, mDeps.getCallingUid(), callingPackageName);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003024 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003025 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003026 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003027 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003028
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003029 InetAddress addr;
3030 try {
3031 addr = InetAddress.getByAddress(hostAddress);
3032 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003033 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003034 return false;
3035 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003036
The Android Open Source Project28527d22009-03-03 19:31:44 -08003037 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003038 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003039 return false;
3040 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003041
3042 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3043 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003044 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003045 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3046 } else {
3047 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3048 }
3049 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003050 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003051
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003052 DetailedState netState;
3053 synchronized (nai) {
3054 netState = nai.networkInfo.getDetailedState();
3055 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003056
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003057 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003058 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003059 log("requestRouteToHostAddress on down network "
3060 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003061 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003062 }
3063 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003064 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003065
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003066 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003067 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003068 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003069 LinkProperties lp;
3070 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003071 synchronized (nai) {
3072 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003073 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003074 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003075 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003076 if (DBG) {
3077 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3078 }
Wink Saville32506bc2013-06-29 21:10:57 -07003079 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003080 } finally {
3081 Binder.restoreCallingIdentity(token);
3082 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003083 }
3084
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003085 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003086 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003087 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003088 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003089 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003090 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003091 if (bestRoute.getGateway().equals(addr)) {
3092 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003093 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003094 } else {
3095 // if we will connect to this through another route, add a direct route
3096 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003097 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003098 }
3099 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003100 if (DBG) log("Adding legacy route " + bestRoute +
3101 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003102
3103 final String dst = bestRoute.getDestinationLinkAddress().toString();
3104 final String nextHop = bestRoute.hasGateway()
3105 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003106 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003107 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3108 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003109 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003110 return false;
3111 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003112 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003113 }
3114
paulhu7c0a2e62021-01-08 00:51:49 +08003115 class DnsResolverUnsolicitedEventCallback extends
3116 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003117 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003118 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003119 try {
3120 mHandler.sendMessage(mHandler.obtainMessage(
3121 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003122 new PrivateDnsValidationUpdate(event.netId,
3123 InetAddresses.parseNumericAddress(event.ipAddress),
3124 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003125 } catch (IllegalArgumentException e) {
3126 loge("Error parsing ip address in validation event");
3127 }
3128 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003129
3130 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003131 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3132 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003133 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3134 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3135 // event callback for certain nai. e.g. cellular. Register here to pass to
3136 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003137 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003138 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3139 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003140 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003141 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003142 }
3143 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003144
3145 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003146 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3147 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3148 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003149 }
dalyk1720e542018-03-05 12:42:22 -05003150
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003151 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003152 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003153 return this.VERSION;
3154 }
3155
3156 @Override
3157 public String getInterfaceHash() {
3158 return this.HASH;
3159 }
paulhu7c0a2e62021-01-08 00:51:49 +08003160 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003161
3162 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003163 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3164 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003165
paulhu7c0a2e62021-01-08 00:51:49 +08003166 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003167 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003168 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003169 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003170 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003171 }
3172 }
3173
Sudheer Shanka9967d462021-03-18 19:09:25 +00003174 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003175 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003176 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003177 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3178 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003179 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003180 };
3181
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003182 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003183 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003184 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003185 }
3186
Mark Fasheh7c999d82023-05-04 20:23:11 +00003187 static final class UidFrozenStateChangedArgs {
3188 final int[] mUids;
3189 final int[] mFrozenStates;
3190
3191 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3192 mUids = uids;
3193 mFrozenStates = frozenStates;
3194 }
3195 }
3196
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003197 /**
3198 * Check if the cell network is idle.
3199 * @return true if the cell network state is idle
3200 * false if the cell network state is active or unknown
3201 */
3202 private boolean isCellNetworkIdle() {
3203 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3204 if (defaultNai == null
3205 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3206 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3207 // cell network is not the default network, cell network state is unknown.
3208 // TODO(b/279380356): Track cell network state when the cell is not the default network
3209 return false;
3210 }
3211
3212 return !mNetworkActivityTracker.isDefaultNetworkActive();
3213 }
3214
Mark Fasheh7c999d82023-05-04 20:23:11 +00003215 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003216 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003217
3218 for (int i = 0; i < uids.length; i++) {
3219 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003220 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003221 } else {
3222 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003223 }
3224 }
3225
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003226 if (ownerUids.isEmpty()) {
3227 return;
3228 }
3229
3230 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3231 // Delay closing sockets to avoid waking the cell modem up.
3232 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3233 // than waking cell modem up.
3234 mPendingFrozenUids.addAll(ownerUids);
3235 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003236 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003237 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003238 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003239 loge("Exception in socket destroy: " + e);
3240 }
3241 }
3242 }
3243
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003244 private void closePendingFrozenSockets() {
3245 ensureRunningOnConnectivityServiceThread();
3246
3247 try {
3248 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3249 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3250 loge("Failed to close pending frozen app sockets: " + e);
3251 }
3252 mPendingFrozenUids.clear();
3253 }
3254
3255 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3256 mNetworkActivityTracker.handleReportNetworkActivity(params);
3257
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003258 final boolean isCellNetworkActivity;
3259 if (mTrackMultiNetworkActivities) {
3260 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3261 // nai could be null if netd receives a netlink message and calls the network
3262 // activity change callback after the network is unregistered from ConnectivityService.
3263 isCellNetworkActivity = nai != null
3264 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3265 } else {
3266 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3267 }
3268
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003269 if (mDelayDestroyFrozenSockets
3270 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003271 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003272 && !mPendingFrozenUids.isEmpty()) {
3273 closePendingFrozenSockets();
3274 }
3275 }
3276
3277 /**
3278 * If the cellular network is no longer the default network, close pending frozen sockets.
3279 *
3280 * @param newNetwork new default network
3281 * @param oldNetwork old default network
3282 */
3283 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3284 NetworkAgentInfo oldNetwork) {
3285 final boolean isOldNetworkCellular = oldNetwork != null
3286 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3287 final boolean isNewNetworkCellular = newNetwork != null
3288 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3289
3290 if (isOldNetworkCellular
3291 && !isNewNetworkCellular
3292 && !mPendingFrozenUids.isEmpty()) {
3293 closePendingFrozenSockets();
3294 }
3295 }
3296
3297 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3298 pw.println("CloseFrozenAppSockets:");
3299 pw.increaseIndent();
3300 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3301 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3302 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3303 pw.decreaseIndent();
3304 }
3305
Junyu Lai155760b2023-10-05 14:51:00 +08003306 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3307 pw.println("Bpf Program Status:");
3308 pw.increaseIndent();
3309 try {
3310 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003311 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003312 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003313 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003314 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003315 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003316 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003317 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003318 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003319 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003320 } catch (IOException e) {
3321 pw.println(" IOException");
3322 }
3323 pw.decreaseIndent();
3324 }
3325
Mark Fasheh7c999d82023-05-04 20:23:11 +00003326 @VisibleForTesting
3327 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003328 @VisibleForTesting
3329 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3330 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003331
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003332 @VisibleForTesting
3333 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3334 "allow_sysui_connectivity_reports";
3335
Yuyang Huang41557552023-11-28 12:47:22 +09003336 public static final String LOG_BPF_RC = "log_bpf_rc_force_disable";
3337
Paul Jensen83f5d572014-08-29 09:54:01 -04003338 private void enforceInternetPermission() {
3339 mContext.enforceCallingOrSelfPermission(
3340 android.Manifest.permission.INTERNET,
3341 "ConnectivityService");
3342 }
3343
The Android Open Source Project28527d22009-03-03 19:31:44 -08003344 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003345 mContext.enforceCallingOrSelfPermission(
3346 android.Manifest.permission.ACCESS_NETWORK_STATE,
3347 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003348 }
3349
lucaslinc582d502022-01-27 09:07:00 +08003350 private boolean checkAccessPermission(int pid, int uid) {
3351 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3352 == PERMISSION_GRANTED;
3353 }
3354
paulhua6ee2122021-02-22 15:40:43 +08003355 /**
3356 * Performs a strict and comprehensive check of whether a calling package is allowed to
3357 * change the state of network, as the condition differs for pre-M, M+, and
3358 * privileged/preinstalled apps. The caller is expected to have either the
3359 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3360 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3361 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3362 * permission and cannot be revoked. See http://b/23597341
3363 *
3364 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3365 * of this app will be updated to the current time.
3366 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003367 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003368 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3369 == PackageManager.PERMISSION_GRANTED) {
3370 return;
3371 }
3372
3373 if (callingPkg == null) {
3374 throw new SecurityException("Calling package name is null.");
3375 }
3376
3377 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3378 final int uid = mDeps.getCallingUid();
3379 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3380 callingPkg, callingAttributionTag, null /* message */);
3381
3382 if (mode == AppOpsManager.MODE_ALLOWED) {
3383 return;
3384 }
3385
3386 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3387 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3388 return;
3389 }
3390
3391 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3392 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3393 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003394 }
3395
Charles He9369e612017-05-15 17:07:18 +01003396 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003397 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003398 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003399 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003400 }
3401
Quang Luong98858d62023-02-11 00:25:24 +00003402 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003403 enforceAnyPermissionOf(mContext,
3404 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003405 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003406 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3407 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3408 }
3409
paulhu8e96a752019-08-12 16:25:11 +08003410 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003411 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003412 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003413 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003414 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003415 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003416 }
3417
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003418 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003419 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003420 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003421 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003422 android.Manifest.permission.NETWORK_SETTINGS,
3423 android.Manifest.permission.NETWORK_FACTORY,
3424 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3425 }
3426
3427 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003428 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003429 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003430 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003431 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3432 android.Manifest.permission.NETWORK_FACTORY,
3433 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3434 }
3435
lucaslin69e1aa92022-03-22 18:15:09 +08003436 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3437 return PERMISSION_GRANTED == mContext.checkPermission(
3438 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3439 || PERMISSION_GRANTED == mContext.checkPermission(
3440 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3441 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003442 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003443 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003444 }
3445
Chalard Jean9a396cc2018-02-21 18:43:54 +09003446 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003447 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003448 android.Manifest.permission.NETWORK_SETTINGS,
3449 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003450 }
3451
3452 private boolean checkSettingsPermission(int pid, int uid) {
3453 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003454 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3455 || PERMISSION_GRANTED == mContext.checkPermission(
3456 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003457 }
3458
paulhu8e96a752019-08-12 16:25:11 +08003459 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003460 enforceNetworkStackPermissionOr(mContext,
3461 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003462 }
3463
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003464 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003465 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003466 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003467 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003468 }
3469
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003470 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003471 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003472 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3473 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003474 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003475 }
3476
James Mattis8378aec2021-01-26 14:05:36 -08003477 private void enforceOemNetworkPreferencesPermission() {
3478 mContext.enforceCallingOrSelfPermission(
3479 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3480 "ConnectivityService");
3481 }
3482
James Mattisfa270db2021-05-31 17:11:10 -07003483 private void enforceManageTestNetworksPermission() {
3484 mContext.enforceCallingOrSelfPermission(
3485 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3486 "ConnectivityService");
3487 }
3488
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003489 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003490 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003491 android.Manifest.permission.NETWORK_STACK,
3492 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003493 }
3494
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003495 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003496 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003497 android.Manifest.permission.NETWORK_STACK,
3498 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3499 }
3500
Chris Göllnercc962022023-12-26 09:55:32 +00003501 private boolean checkSystemBarServicePermission(int pid, int uid) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003502 return checkAnyPermissionOf(mContext, pid, uid,
3503 android.Manifest.permission.STATUS_BAR_SERVICE);
3504 }
3505
paulhu1a407652019-03-22 16:35:06 +08003506 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003507 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003508 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003509 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3510 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003511 }
3512
Paul Hu8fc2a552022-05-04 18:44:42 +08003513 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3514 boolean checkUidsAllowedList) {
3515 if (PermissionUtils.checkAnyPermissionOf(mContext,
3516 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3517 return true;
3518 }
3519
3520 // fallback to ConnectivityInternalPermission
3521 // TODO: Remove this fallback check after all apps have declared
3522 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3523 if (PermissionUtils.checkAnyPermissionOf(mContext,
3524 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3525 return true;
3526 }
3527
3528 // Check whether uid is in allowed on restricted networks list.
3529 if (checkUidsAllowedList
3530 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3531 return true;
3532 }
3533 return false;
3534 }
3535
3536 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3537 final int callingUid = mDeps.getCallingUid();
3538 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3539 throw new SecurityException("ConnectivityService: user " + callingUid
3540 + " has no permission to access restricted network.");
3541 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003542 }
3543
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003544 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003545 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003546 }
3547
Roshan Pius98f59ec2021-02-23 08:47:39 -08003548 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3549 return PERMISSION_GRANTED == mContext.checkPermission(
3550 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3551 }
3552
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003553 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003554 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003555 }
3556
3557 private void sendInetConditionBroadcast(NetworkInfo info) {
3558 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3559 }
3560
Wink Saville4f0de1e2011-08-04 15:01:58 -07003561 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003562 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003563 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003564 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003565 if (info.isFailover()) {
3566 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3567 info.setFailover(false);
3568 }
3569 if (info.getReason() != null) {
3570 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3571 }
3572 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003573 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3574 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003575 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003576 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003577 return intent;
3578 }
3579
3580 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3581 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3582 }
3583
Michael Groover73f69482023-01-27 11:01:25 -06003584 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3585 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003586 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3587 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003588 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003589 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003590 if (!mSystemReady
3591 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003592 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003593 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003594 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003595 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003596 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003597 }
3598
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003599 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003600 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003601 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003602 final NetworkInfo ni = intent.getParcelableExtra(
3603 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003604 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3605 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003606 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003607 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003608 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003609 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003610 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003611 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003612 } finally {
3613 Binder.restoreCallingIdentity(ident);
3614 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003615 }
3616 }
3617
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003618 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3619 NetworkInfo info) {
3620 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003621 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003622
3623 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3624 try {
3625 // This allows us to discard older broadcasts still waiting to be delivered
3626 // which have the same namespace and key.
3627 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3628 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3629 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003630 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003631 } catch (UnsupportedApiLevelException e) {
3632 Log.wtf(TAG, "Using unsupported API" + e);
3633 }
3634 }
3635
3636 @VisibleForTesting
3637 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3638 final StringBuilder sb = new StringBuilder();
3639 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3640 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3641 sb.append(info.getExtraInfo());
3642 return sb.toString();
3643 }
3644
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003645 /**
Aaron Huang96011892020-06-27 07:18:23 +08003646 * Called by SystemServer through ConnectivityManager when the system is ready.
3647 */
3648 @Override
3649 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003650 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003651 throw new SecurityException("Calling Uid is not system uid.");
3652 }
3653 systemReadyInternal();
3654 }
3655
3656 /**
3657 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003658 */
3659 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003660 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003661 // Load flags after PackageManager is ready to query module version
3662 mFlags.loadFlags(mDeps, mContext);
3663
Aaron Huang9a57acf2020-12-08 10:03:29 +08003664 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3665 // listening network request which is sent by MultipathPolicyTracker won't be added
3666 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3667 // be called after PermissionMonitor#startMonitoring().
3668 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3669 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3670 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003671 final ConditionVariable startMonitoringDone = new ConditionVariable();
3672 mHandler.post(() -> {
3673 mPermissionMonitor.startMonitoring();
3674 startMonitoringDone.open();
3675 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003676 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003677 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003678
Hugo Benichie5220992017-04-26 14:53:28 +09003679 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003680 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003681 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003682 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003683 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003684 }
3685 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003686
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003687 // Create network requests for always-on networks.
3688 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003689
3690 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003691 // Note that updating can be skipped here if the list is empty only because no uid
3692 // rules are applied before system ready. Normally, the empty uid list means to clear
3693 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003694 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3695 updateMobileDataPreferredUids();
3696 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003697
3698 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003699 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003700 mBpfNetMaps.setPullAtomCallback(mContext);
3701 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003702 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3703 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003704 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3705 // have permission problem. While CV#block() is unbounded in time and can in principle block
3706 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3707 // could have blocked forever too.
3708 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003709 }
3710
The Android Open Source Project28527d22009-03-03 19:31:44 -08003711 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003712 * Start listening for default data network activity state changes.
3713 */
3714 @Override
3715 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003716 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003717 }
3718
3719 /**
3720 * Stop listening for default data network activity state changes.
3721 */
3722 @Override
3723 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003724 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003725 }
3726
3727 /**
3728 * Check whether the default network radio is currently active.
3729 */
3730 @Override
3731 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003732 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003733 }
3734
3735 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003736 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003737 * and set it on it's iface.
3738 */
Junyu Lai970963e2022-10-25 15:46:47 +08003739 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003740 final String iface = newLp.getInterfaceName();
3741 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003742 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003743 // Silently ignore unset MTU value.
3744 return;
3745 }
Hansen Kurli04252032022-12-07 11:21:49 +00003746 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3747 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3748 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003749 return;
3750 }
Hansen Kurli04252032022-12-07 11:21:49 +00003751 // Cannot set MTU without interface name
3752 if (TextUtils.isEmpty(iface)) {
3753 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003754 return;
3755 }
sy.yun4aa73922013-09-02 05:24:09 +09003756
Hansen Kurli04252032022-12-07 11:21:49 +00003757 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3758 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003759 return;
3760 }
3761
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003762 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003763 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003764 mNetd.interfaceSetMtu(iface, mtu);
3765 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003766 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003767 }
3768 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003769
Chenbo Feng15416292018-11-08 17:36:21 -08003770 @VisibleForTesting
3771 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003772
Junyu Lai970963e2022-10-25 15:46:47 +08003773 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003774 String[] values = null;
3775 if (tcpBufferSizes != null) {
3776 values = tcpBufferSizes.split(",");
3777 }
3778
3779 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003780 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003781 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3782 values = tcpBufferSizes.split(",");
3783 }
3784
3785 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3786
3787 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003788 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003789
Chenbo Feng15416292018-11-08 17:36:21 -08003790 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3791 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3792 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003793 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003794 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003795 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003796 }
3797 }
3798
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003799 @Override
3800 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003801 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003802 NETWORK_RESTORE_DELAY_PROP_NAME);
3803 if(restoreDefaultNetworkDelayStr != null &&
3804 restoreDefaultNetworkDelayStr.length() != 0) {
3805 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003806 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003807 } catch (NumberFormatException e) {
3808 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003809 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003810 // if the system property isn't set, use the value for the apn type
3811 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3812
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003813 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3814 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003815 }
3816 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003817 }
3818
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003819 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003820 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003821 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003822 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003823 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003824 // Start gathering diagnostic information.
3825 netDiags.add(new NetworkDiagnostics(
3826 nai.network,
3827 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003828 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003829 DIAG_TIME_MS));
3830 }
3831
3832 for (NetworkDiagnostics netDiag : netDiags) {
3833 pw.println();
3834 netDiag.waitForMeasurements();
3835 netDiag.dump(pw);
3836 }
3837 }
3838
The Android Open Source Project28527d22009-03-03 19:31:44 -08003839 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003840 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3841 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003842 if (!checkDumpPermission(mContext, TAG, writer)) return;
3843
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003844 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003845 }
3846
lucaslin99473f62020-12-10 15:10:54 +08003847 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3848 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3849 != PackageManager.PERMISSION_GRANTED) {
3850 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003851 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003852 + " due to missing android.permission.DUMP permission");
3853 return false;
3854 } else {
3855 return true;
3856 }
3857 }
3858
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003859 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003860 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003861
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003862 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003863 dumpNetworkDiagnostics(pw);
3864 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003865 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003866 dumpNetworks(pw);
3867 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003868 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003869 dumpNetworkRequests(pw);
3870 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003871 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3872 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3873 dumpTrafficController(pw, fd, verbose);
3874 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003875 }
Erik Kline9647f382015-06-05 17:47:34 +09003876
Junyu Lai0da479b2022-04-20 15:06:29 +08003877 pw.println("NetworkProviders for:");
3878 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003879 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003880 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003881 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003882 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003883 pw.println();
3884
Chalard Jean5b409c72021-02-04 13:12:59 +09003885 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003886 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003887 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003888 pw.println("none");
3889 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003890 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003891 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003892 pw.println();
3893
James Mattis8b298a02021-06-01 22:34:04 -07003894 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003895 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003896 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003897 pw.decreaseIndent();
3898 pw.println();
3899
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003900 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003901 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003902 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003903 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003904 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003905
junyulaif2c67e42018-08-07 19:50:45 +08003906 pw.println("Status for known UIDs:");
3907 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003908 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003909 for (int i = 0; i < size; i++) {
3910 // Don't crash if the array is modified while dumping in bugreports.
3911 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003912 final int uid = mUidBlockedReasons.keyAt(i);
3913 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3914 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003915 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003916 } catch (ArrayIndexOutOfBoundsException e) {
3917 pw.println(" ArrayIndexOutOfBoundsException");
3918 } catch (ConcurrentModificationException e) {
3919 pw.println(" ConcurrentModificationException");
3920 }
3921 }
3922 pw.println();
3923 pw.decreaseIndent();
3924
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003925 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003926 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003927 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003928 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003929 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003930
Junyu Lai0da479b2022-04-20 15:06:29 +08003931 pw.println("Network Offers:");
3932 pw.increaseIndent();
3933 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3934 pw.println(offerInfo.offer);
3935 }
3936 pw.decreaseIndent();
3937 pw.println();
3938
Robert Greenwalt94e22142014-07-30 16:31:24 -07003939 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003940
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003941 pw.println();
markchien5e866652019-09-30 14:40:57 +08003942 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003943
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003944 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003945 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003946
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003947 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003948 dumpCloseFrozenAppSockets(pw);
3949
3950 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003951 dumpBpfProgramStatus(pw);
3952
Chalard Jean53017782022-11-24 17:13:44 +09003953 if (null != mCarrierPrivilegeAuthenticator) {
3954 pw.println();
3955 mCarrierPrivilegeAuthenticator.dump(pw);
3956 }
3957
Junyu Lai155760b2023-10-05 14:51:00 +08003958 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003959
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003960 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003961 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003962 pw.println("mNetworkRequestInfoLogs (most recent first):");
3963 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003964 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003965 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003966
3967 pw.println();
3968 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3969 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003970 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003971 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003972
3973 pw.println();
3974 pw.println("NetTransition WakeLock activity (most recent first):");
3975 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003976 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3977 pw.println("total releases: " + mTotalWakelockReleases);
3978 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3979 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3980 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3981 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3982 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3983 }
James Mattiscb1e0362021-04-06 17:07:42 -07003984 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003985
3986 pw.println();
3987 pw.println("bandwidth update requests (by uid):");
3988 pw.increaseIndent();
3989 synchronized (mBandwidthRequests) {
3990 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3991 pw.println("[" + mBandwidthRequests.keyAt(i)
3992 + "]: " + mBandwidthRequests.valueAt(i));
3993 }
3994 }
3995 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003996 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003997
James Mattiscb1e0362021-04-06 17:07:42 -07003998 pw.println();
3999 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4000 pw.increaseIndent();
4001 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004002 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004003 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004004
4005 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004006
4007 pw.println();
4008 pw.println("Permission Monitor:");
4009 pw.increaseIndent();
4010 mPermissionMonitor.dump(pw);
4011 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004012
4013 pw.println();
4014 pw.println("Legacy network activity:");
4015 pw.increaseIndent();
4016 mNetworkActivityTracker.dump(pw);
4017 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08004018 }
4019
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004020 private void dumpNetworks(IndentingPrintWriter pw) {
4021 for (NetworkAgentInfo nai : networksSortedById()) {
4022 pw.println(nai.toString());
4023 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004024 pw.println("Nat464Xlat:");
4025 pw.increaseIndent();
4026 nai.dumpNat464Xlat(pw);
4027 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004028 pw.println(String.format(
4029 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4030 nai.numForegroundNetworkRequests(),
4031 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4032 nai.numBackgroundNetworkRequests(),
4033 nai.numNetworkRequests()));
4034 pw.increaseIndent();
4035 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4036 pw.println(nai.requestAt(i).toString());
4037 }
4038 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004039 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004040 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004041 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004042 pw.decreaseIndent();
4043 pw.decreaseIndent();
4044 }
4045 }
4046
James Mattis8b298a02021-06-01 22:34:04 -07004047 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4048 if (!mProfileNetworkPreferences.isEmpty()) {
4049 pw.println("Profile preferences:");
4050 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004051 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004052 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004053 }
James Mattis8b298a02021-06-01 22:34:04 -07004054 if (!mOemNetworkPreferences.isEmpty()) {
4055 pw.println("OEM preferences:");
4056 pw.increaseIndent();
4057 pw.println(mOemNetworkPreferences);
4058 pw.decreaseIndent();
4059 }
4060 if (!mMobileDataPreferredUids.isEmpty()) {
4061 pw.println("Mobile data preferred UIDs:");
4062 pw.increaseIndent();
4063 pw.println(mMobileDataPreferredUids);
4064 pw.decreaseIndent();
4065 }
James Mattis45d81842021-01-10 14:24:24 -08004066
James Mattis8b298a02021-06-01 22:34:04 -07004067 pw.println("Default requests:");
4068 pw.increaseIndent();
4069 dumpPerAppDefaultRequests(pw);
4070 pw.decreaseIndent();
4071 }
4072
4073 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004074 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4075 if (mDefaultRequest == defaultRequest) {
4076 continue;
4077 }
4078
James Mattis8b298a02021-06-01 22:34:04 -07004079 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4080 final String networkOutput;
4081 if (null == satisfier) {
4082 networkOutput = "null";
4083 } else if (mNoServiceNetwork.equals(satisfier)) {
4084 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004085 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004086 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004087 }
James Mattis8b298a02021-06-01 22:34:04 -07004088 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4089 ? "" : " asUid: " + defaultRequest.mAsUid;
4090 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4091 + defaultRequest.mPid + asUidString + "]";
4092 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4093 + " Preference order: " + defaultRequest.mPreferenceOrder
4094 + " Tracked UIDs: " + defaultRequest.getUids();
4095 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004096 }
4097 }
4098
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004099 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004100 NetworkRequestInfo[] infos = null;
4101 while (infos == null) {
4102 try {
4103 infos = requestsSortedById();
4104 } catch (ConcurrentModificationException e) {
4105 // mNetworkRequests should only be accessed from handler thread, except dump().
4106 // As dump() is never called in normal usage, it would be needlessly expensive
4107 // to lock the collection only for its benefit. Instead, retry getting the
4108 // requests if ConcurrentModificationException is thrown during dump().
4109 }
4110 }
4111 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004112 pw.println(nri.toString());
4113 }
4114 }
4115
Ken Chene6d511f2022-01-25 11:10:42 +08004116 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4117 boolean verbose) {
4118 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004119 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004120 } catch (ServiceSpecificException e) {
4121 pw.println(e.getMessage());
4122 } catch (IOException e) {
4123 loge("Dump BPF maps failed, " + e);
4124 }
4125 }
4126
Chalard Jean524f0b12021-10-25 21:11:56 +09004127 private void dumpAllRequestInfoLogsToLogcat() {
4128 try (PrintWriter logPw = new PrintWriter(new Writer() {
4129 @Override
4130 public void write(final char[] cbuf, final int off, final int len) {
4131 // This method is called with 0-length and 1-length arrays for empty strings
4132 // or strings containing only the DEL character.
4133 if (len <= 1) return;
4134 Log.e(TAG, new String(cbuf, off, len));
4135 }
4136 @Override public void flush() {}
4137 @Override public void close() {}
4138 })) {
4139 mNetworkRequestInfoLogs.dump(logPw);
4140 }
4141 }
4142
Hugo Benichia480ba52018-09-03 08:19:02 +09004143 /**
4144 * Return an array of all current NetworkAgentInfos sorted by network id.
4145 */
4146 private NetworkAgentInfo[] networksSortedById() {
4147 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004148 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004149 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004150 return networks;
4151 }
4152
4153 /**
4154 * Return an array of all current NetworkRequest sorted by request id.
4155 */
James Mattis258ea3c2020-11-15 15:04:40 -08004156 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004157 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004158 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004159 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004160 // Sort the array based off the NRI containing the min requestId in its requests.
4161 Arrays.sort(requests,
4162 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4163 Comparator.comparingInt(req -> req.requestId)).requestId
4164 )
4165 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004166 return requests;
4167 }
4168
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004169 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004170 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004171 if (officialNai != null && officialNai.equals(nai)) return true;
4172 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004173 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004174 " - " + nai);
4175 }
4176 return false;
4177 }
4178
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004179 private boolean isDisconnectRequest(Message msg) {
4180 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4181 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4182 return info.getState() == NetworkInfo.State.DISCONNECTED;
4183 }
4184
Robert Greenwalt2034b912009-08-12 16:08:25 -07004185 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004186 private class NetworkStateTrackerHandler extends Handler {
4187 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004188 super(looper);
4189 }
4190
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004191 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004192 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4193 final NetworkAgentInfo nai = arg.first;
4194 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004195 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004196 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004197 }
4198 return;
4199 }
4200
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004201 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004202 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004203 return;
4204 }
4205
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004206 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004207 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004208 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4209 if (!nai.respectsNcStructuralConstraints(proposed)) {
4210 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4211 + nai.networkCapabilities + " -> " + proposed);
4212 disconnectAndDestroyNetwork(nai);
4213 return;
4214 }
4215 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004216 final NetworkCapabilities sanitized =
4217 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004218 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004219 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004220 break;
4221 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004222 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004223 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004224 processLinkPropertiesFromAgent(nai, newLp);
4225 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004226 break;
4227 }
4228 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004229 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004230 updateNetworkInfo(nai, info);
4231 break;
4232 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004233 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4234 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004235 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004236 break;
4237 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004238 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004239 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004240 break;
4241 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004242 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004243 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004244 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004245 // Note that if the NAI had been connected, this would affect the
4246 // score, and therefore would require re-mixing the score and performing
4247 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004248 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004249 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4250 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004251 // Mark the network as temporarily accepting partial connectivity so that it
4252 // will be validated (and possibly become default) even if it only provides
4253 // partial internet access. Note that if user connects to partial connectivity
4254 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4255 // out of wifi coverage) and if the same wifi is available again, the device
4256 // will auto connect to this wifi even though the wifi has "no internet".
4257 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004258 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004259 break;
4260 }
junyulai011b1f12019-01-03 18:50:15 +08004261 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004262 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004263 break;
4264 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004265 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004266 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004267 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004268
4269 if (isLegacyLockdownNai(nai)
4270 && (underlying == null || underlying.size() != 1)) {
4271 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4272 + " must have exactly one underlying network: " + underlying);
4273 }
4274
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004275 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4276 nai.declaredUnderlyingNetworks = (underlying != null)
4277 ? underlying.toArray(new Network[0]) : null;
4278
4279 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4280 if (DBG) {
4281 log(nai.toShortString() + " changed underlying networks to "
4282 + Arrays.toString(nai.declaredUnderlyingNetworks));
4283 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004284 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004285 notifyIfacesChangedForNetworkStats();
4286 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004287 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004288 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004289 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4290 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4291 nai.teardownDelayMs = msg.arg1;
4292 } else {
4293 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4294 }
Chalard Jean550b5212021-03-05 23:07:53 +09004295 break;
4296 }
4297 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4298 nai.setLingerDuration((int) arg.second);
4299 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004300 }
Tyler Wear72388212021-09-09 14:49:02 -07004301 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4302 DscpPolicy policy = (DscpPolicy) arg.second;
4303 if (mDscpPolicyTracker != null) {
4304 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4305 }
4306 break;
4307 }
4308 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4309 if (mDscpPolicyTracker != null) {
4310 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4311 }
4312 break;
4313 }
4314 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4315 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004316 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004317 }
4318 break;
4319 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004320 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004321 if (!nai.everConnected()) {
4322 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4323 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004324 teardownUnneededNetwork(nai);
4325 break;
4326 }
4327
4328 if (nai.isDestroyed()) {
4329 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4330 + ", ignoring");
4331 break;
4332 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004333
4334 final int timeoutMs = (int) arg.second;
4335 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4336 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4337 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4338 }
4339
4340 // Marking a network awaiting replacement is used to ensure that any requests
4341 // satisfied by the network do not switch to another network until a
4342 // replacement is available or the wait for a replacement times out.
4343 // If the network is inactive (i.e., nascent or lingering), then there are no
4344 // such requests, and there is no point keeping it. Just tear it down.
4345 // Note that setLingerDuration(0) cannot be used to do this because the network
4346 // could be nascent.
4347 nai.clearInactivityState();
4348 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4349 Log.d(TAG, nai.toShortString()
4350 + " marked awaiting replacement is unneeded, tearing down instead");
4351 teardownUnneededNetwork(nai);
4352 break;
4353 }
4354
4355 Log.d(TAG, "Marking " + nai.toShortString()
4356 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4357 destroyNativeNetwork(nai);
4358
4359 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4360 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4361 // consider the fact that the network could already have disconnected or been
4362 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4363 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4364 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4365 mKeepaliveTracker.handleStopAllKeepalives(nai,
4366 SocketKeepalive.ERROR_INVALID_NETWORK);
4367
4368 nai.updateScoreForNetworkAgentUpdate();
4369 // This rematch is almost certainly not going to result in any changes, because
4370 // the destroyed flag is only just above the "current satisfier wins"
4371 // tie-breaker. But technically anything that affects scoring should rematch.
4372 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004373 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004374 break;
4375 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004376 }
4377 }
4378
4379 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004380 final int netId = msg.arg2;
4381 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004382 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004383 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004384 switch (msg.what) {
4385 default:
4386 return false;
lucasline117e2e2019-10-22 18:27:33 +08004387 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004388 if (nai == null) {
4389 break;
4390 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004391 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4392 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004393 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004394 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004395 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004396 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004397 if (probePrivateDnsCompleted) {
4398 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4399 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004400 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004401 }
4402 // Only show the notification when the private DNS is broken and the
4403 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004404 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004405 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4406 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004407 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004408 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4409 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4410 // private DNS is broken, it means this network is being reevaluated.
4411 // Either probing private DNS is not necessary any more or it hasn't been
4412 // done yet. In either case, the networkCapabilities should be updated to
4413 // reflect the new status.
4414 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004415 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004416 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004417 }
4418 break;
4419 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004420 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004421 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4422
Erik Kline31b4a9e2018-01-11 21:07:29 +09004423 if (nai == null) break;
4424
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004425 handleNetworkTested(nai, results.mTestResult,
4426 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004427 break;
4428 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004429 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004430 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004431 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004432 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004433 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004434 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004435 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4436 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004437 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004438 if (nai == null) {
4439 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4440 break;
4441 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004442 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004443 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004444 (PendingIntent) msg.obj,
4445 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004446 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004447 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004448 break;
4449 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004450 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004451 if (nai == null) break;
4452
Erik Kline9a62f012018-03-21 07:18:33 -07004453 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004454 break;
4455 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004456 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004457 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004458 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004459 break;
4460 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004461 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004462 return true;
4463 }
4464
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004465 private void handleNetworkTested(
4466 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004467 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4468 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004469 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004470
4471 // If there is any kind of working networking, then the NAI has been evaluated
4472 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4473 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004474 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004475 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004476 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4477 // any callback that receives onAvailable for that rematch receives an extra caps
4478 // callback. To prevent that, update the score in the agent so the updates below won't
4479 // see an update to both caps and score at the same time.
4480 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004481 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4482
he_won.hwang881307a2022-03-15 21:23:52 +09004483 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4484 // Assume the validation failure is due to a temporary failure after roaming
4485 // and ignore it. NetworkMonitor will continue to retry validation. If it
4486 // continues to fail after the block timeout expires, the network will be
4487 // marked unvalidated. If it succeeds, then validation state will not change.
4488 return;
4489 }
4490
Chalard Jean254bd162022-08-25 13:04:51 +09004491 final boolean wasValidated = nai.isValidated();
4492 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004493 final boolean wasPortal = nai.captivePortalDetected();
4494 nai.setPartialConnectivity(partial);
4495 nai.setCaptivePortalDetected(portal);
4496 nai.updateScoreForNetworkAgentUpdate();
4497 final boolean partialConnectivityChanged = (wasPartial != partial);
4498 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004499
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004500 if (DBG) {
4501 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4502 ? " with redirect to " + redirectUrl
4503 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004504 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004505 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004506 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004507 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004508 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004509 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004510 if (valid) {
4511 handleFreshlyValidatedNetwork(nai);
4512 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4513 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004514 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004515 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004516 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004517 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004518 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004519 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004520 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004521 NotificationType.PRIVATE_DNS_BROKEN);
4522 // If network becomes valid, the hasShownBroken should be reset for
4523 // that network so that the notification will be fired when the private
4524 // DNS is broken again.
4525 nai.networkAgentConfig.hasShownBroken = false;
4526 }
4527 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004528 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004529 } else if (portalChanged) {
4530 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004531 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004532 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4533 nai.onPreventAutomaticReconnect();
4534 teardownUnneededNetwork(nai);
4535 return;
4536 } else {
4537 updateCapabilitiesForNetwork(nai);
4538 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004539 } else if (becameEvaluated) {
4540 // If valid or partial connectivity changed, updateCapabilities* has
4541 // done the rematch.
4542 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004543 }
4544 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004545
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004546 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004547 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004548 nai.onValidationStatusChanged(
4549 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4550 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004551
4552 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004553 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004554 // immediately. Re-notify partial connectivity silently if no internet
4555 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004556 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004557 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004558 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4559 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004560 }
4561
Chalard Jean254bd162022-08-25 13:04:51 +09004562 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004563 handleNetworkUnvalidated(nai);
4564 }
4565 }
4566
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004567 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4568 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4569 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4570 // Do not avoid captive portal when network is wear proxy.
4571 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4572 }
4573
Calvin Ondada1452016-10-11 15:10:46 -07004574 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004575 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4576 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004577 }
4578
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004579 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4580 switch (msg.what) {
4581 default:
4582 return false;
4583 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4584 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4585 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4586 handleLingerComplete(nai);
4587 }
4588 break;
4589 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004590 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4591 handleNetworkAgentRegistered(msg);
4592 break;
4593 }
4594 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4595 handleNetworkAgentDisconnected(msg);
4596 break;
4597 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004598 }
4599 return true;
4600 }
4601
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004602 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004603 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004604 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004605 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004606 maybeHandleNetworkAgentMessage(msg);
4607 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004608 }
4609 }
4610
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004611 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004612 private final int mNetId;
4613 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004614
4615 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004616 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004617 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004618 }
4619
4620 @Override
4621 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4622 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004623 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004624 }
4625
4626 @Override
4627 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004628 // Legacy version of notifyNetworkTestedWithExtras.
4629 // Would only be called if the system has a NetworkStack module older than the
4630 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004631 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004632 }
4633
4634 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004635 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004636 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4637 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004638 final Message msg = mTrackerHandler.obtainMessage(
4639 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004640 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004641 new NetworkTestedResults(
4642 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004643 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004644
4645 // Invoke ConnectivityReport generation for this Network test event.
4646 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4647 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004648
Cody Kestingf1120be2020-08-03 18:01:40 -07004649 // NetworkMonitor reports the network validation result as a bitmask while
4650 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4651 // logical value for ConnectivityDiagnostics.
4652 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4653 p.result);
4654
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004655 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004656 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004657 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4658 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4659
Aaron Huang959d3642021-01-21 15:47:41 +08004660 ConnectivityReportEvent reportEvent =
4661 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4662 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004663 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004664 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004665 }
4666
4667 @Override
4668 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4669 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4670 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004671 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004672 }
4673
4674 @Override
lucasline117e2e2019-10-22 18:27:33 +08004675 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4676 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4677 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004678 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004679 }
4680
4681 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004682 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4683 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4684 EVENT_CAPPORT_DATA_CHANGED,
4685 0, mNetId, data));
4686 }
4687
4688 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004689 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004690 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004691 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004692
4693 final PendingIntent pendingIntent;
4694 // Only the system server can register notifications with package "android"
4695 final long token = Binder.clearCallingIdentity();
4696 try {
paulhu7746e4e2020-06-09 19:07:03 +08004697 pendingIntent = PendingIntent.getBroadcast(
4698 mContext,
4699 0 /* requestCode */,
4700 intent,
4701 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004702 } finally {
4703 Binder.restoreCallingIdentity(token);
4704 }
4705 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4706 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004707 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004708 }
4709
4710 @Override
4711 public void hideProvisioningNotification() {
4712 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004713 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004714 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004715
4716 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004717 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004718 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004719 }
4720
4721 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004722 public int getInterfaceVersion() {
4723 return this.VERSION;
4724 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004725
4726 @Override
4727 public String getInterfaceHash() {
4728 return this.HASH;
4729 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004730 }
4731
Cody Kestingf1120be2020-08-03 18:01:40 -07004732 /**
4733 * Converts the given NetworkMonitor-specific validation result bitmask to a
4734 * ConnectivityDiagnostics-specific validation result int.
4735 */
4736 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4737 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4738 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4739 }
4740 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4741 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4742 }
4743 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4744 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4745 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4746 }
4747
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004748 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004749 log("Data stall detected with methods: " + p.detectionMethod);
4750
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004751 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004752 int detectionMethod = 0;
4753 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4754 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4755 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4756 }
4757 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4758 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4759 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4760 p.tcpMetricsCollectionPeriodMillis);
4761 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004762 }
4763
Cody Kestingf53a0752020-04-15 12:33:28 -07004764 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004765 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004766 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004767
4768 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4769 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4770 // the cost of going through two handlers.
4771 mConnectivityDiagnosticsHandler.sendMessage(msg);
4772 }
4773
Cody Kestingb37958e2020-05-15 10:36:01 -07004774 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4775 return (p.detectionMethod & detectionMethod) != 0;
4776 }
4777
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004778 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4779 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004780 }
4781
Erik Klinea73af002018-06-26 18:53:43 +09004782 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4783 if (nai == null) return;
4784 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4785 // in order to restart a validation pass from within netd.
4786 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00004787 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004788 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004789 }
4790 }
4791
Erik Kline31b4a9e2018-01-11 21:07:29 +09004792 private void handlePrivateDnsSettingsChanged() {
4793 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4794
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004795 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004796 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004797 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004798 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4799 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004800 }
4801 }
4802
Erik Kline9a62f012018-03-21 07:18:33 -07004803 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4804 // Private DNS only ever applies to networks that might provide
4805 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004806 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004807
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004808 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004809 // schedule DNS resolutions. If a DNS resolution is required the
4810 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004811 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004812
4813 // With Private DNS bypass support, we can proceed to update the
4814 // Private DNS config immediately, even if we're in strict mode
4815 // and have not yet resolved the provider name into a set of IPs.
4816 updatePrivateDns(nai, cfg);
4817 }
4818
4819 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4820 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004821 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004822 }
4823
dalyk1720e542018-03-05 12:42:22 -05004824 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4825 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4826 if (nai == null) {
4827 return;
4828 }
4829 mDnsManager.updatePrivateDnsValidation(update);
4830 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4831 }
4832
paulhu7c0a2e62021-01-08 00:51:49 +08004833 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004834 int prefixLength) {
4835 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4836 if (nai == null) return;
4837
paulhu7c0a2e62021-01-08 00:51:49 +08004838 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4839 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004840
4841 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004842 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004843 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004844 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004845 prefixLength);
4846 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004847 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004848 return;
4849 }
4850 }
4851
Lorenzo Colittid523d142020-04-01 20:16:30 +09004852 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004853 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4854 }
4855
Hai Shalome58bdc62021-01-11 18:45:34 -08004856 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004857 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004858 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004859 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4860 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4861 }
4862
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004863 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004864 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004865 * @param nai the agent info to update
4866 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004867 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004868 */
junyulai2b6f0c22021-02-03 20:15:30 +08004869 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4870 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4871 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004872 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004873 // one lingered request, set inactive.
4874 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004875 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004876 if (DBG) log("Unsetting inactive " + nai.toShortString());
4877 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004878 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004879 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004880 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004881 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4882 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004883 }
junyulai2b6f0c22021-02-03 20:15:30 +08004884 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004885 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004886 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004887 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004888 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004889 }
4890
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004891 private void handleNetworkAgentRegistered(Message msg) {
4892 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4893 if (!mNetworkAgentInfos.contains(nai)) {
4894 return;
4895 }
4896
4897 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4898 if (VDBG) log("NetworkAgent registered");
4899 } else {
4900 loge("Error connecting NetworkAgent");
4901 mNetworkAgentInfos.remove(nai);
4902 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004903 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004904 synchronized (mNetworkForNetId) {
4905 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004906 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004907 mNetIdManager.releaseNetId(nai.network.getNetId());
4908 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004909 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004910 }
4911 }
4912 }
Paul Jensend5f53392014-11-25 15:26:53 -05004913
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004914 @VisibleForTesting
4915 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004916 // The feature of creating the networks immediately was slated for U, but race conditions
4917 // detected late required this was flagged off.
4918 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4919 // in NetworkAgentTest.
4920 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004921 }
4922
4923 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4924 @NonNull NetworkInfo.State state) {
4925 if (nai.isCreated()) return false;
4926 if (state == NetworkInfo.State.CONNECTED) return true;
4927 if (state != NetworkInfo.State.CONNECTING) {
4928 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004929 if (shouldCreateNetworksImmediately()) {
4930 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4931 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004932 return false;
4933 }
4934 return nai.isVPN() || shouldCreateNetworksImmediately();
4935 }
4936
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004937 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004938 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004939 }
4940
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004941 @VisibleForTesting
4942 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004943 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004944 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004945
4946 // If the network never roamed, return false. The check below is not sufficient if time
4947 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4948 if (nai.lastRoamTime == 0) return false;
4949
he_won.hwang881307a2022-03-15 21:23:52 +09004950 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4951 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004952 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004953 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004954 final long currentTimeMs = SystemClock.elapsedRealtime();
4955 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004956 if (timeSinceLastRoam <= blockTimeOut) {
4957 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4958 return true;
4959 }
4960 }
4961 return false;
4962 }
4963
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004964 private void handleNetworkAgentDisconnected(Message msg) {
4965 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004966 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004967 }
4968
Chalard Jeand9fffc32018-05-11 20:19:20 +09004969 // Destroys a network, remove references to it from the internal state managed by
4970 // ConnectivityService, free its interfaces and clean up.
4971 // Must be called on the Handler thread.
4972 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004973 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004974
4975 if (!mNetworkAgentInfos.contains(nai)) return;
4976
Chalard Jeand9fffc32018-05-11 20:19:20 +09004977 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004978 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004979 }
lucaslinb25c9a62019-02-12 15:30:13 +08004980 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004981 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004982 // A network agent has disconnected.
4983 // TODO - if we move the logic to the network agent (have them disconnect
4984 // because they lost all their requests or because their score isn't good)
4985 // then they would disconnect organically, report their new state and then
4986 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004987 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004988 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4989 null, null);
4990 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004991 final boolean wasDefault = isDefaultNetwork(nai);
4992 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004993 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004994 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09004995 if (mTrackMultiNetworkActivities) {
4996 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
4997 // the network becomes no longer the default network.
4998 mNetworkActivityTracker.removeDataActivityTracking(nai);
4999 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005000 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005001 // If this was a local network forwarded to some upstream, or if some local network was
5002 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005003 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005004 // If this is a local network with an upstream selector, remove the associated network
5005 // request.
5006 if (nai.isLocalNetwork()) {
5007 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5008 if (null != selector) {
5009 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5010 }
5011 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005012 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5013 // by other networks that are already connected. Perhaps that can be done by
5014 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5015 // of rematchAllNetworksAndRequests
5016 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005017 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005018
5019 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005020 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5021 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005022 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005023 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005024 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005025 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005026 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005027 synchronized (mNetworkForNetId) {
5028 // Remove the NetworkAgent, but don't mark the netId as
5029 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005030 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005031 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005032 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005033 // Update allowed network lists in netd. This should be called after removing nai
5034 // from mNetworkAgentInfos.
5035 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005036 // Remove all previously satisfied requests.
5037 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005038 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005039 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005040 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005041 if (currentNetwork != null
5042 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005043 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005044 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5045 // rematch not to keep disconnected agents instead of setting it here ; this
5046 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005047 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005048 for (final NetworkOfferInfo noi : mNetworkOffers) {
5049 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005050 }
James Mattise3ef1912020-12-20 11:09:58 -08005051
Chalard Jean5b409c72021-02-04 13:12:59 +09005052 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005053 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005054 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005055 ensureNetworkTransitionWakelock(nai.toShortString());
5056 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005057 }
5058 }
junyulai2b6f0c22021-02-03 20:15:30 +08005059 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005060 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005061 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005062 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005063 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005064 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005065 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005066
Aaron Huang9fe47be2021-06-08 13:11:45 +08005067 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5068 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5069 // not called by the rematch in this case. This is because the code above unset
5070 // this network from the default request's satisfier, and that is what the rematch
5071 // is using as its source data to know what the old satisfier was. So as far as the
5072 // rematch above is concerned, the old default network was null.
5073 // Therefore if there is no new default, the default network was null and is still
5074 // null, thus there was no change so makeDefault() is not called. So if the old
5075 // network had a proxy and there is no new default, the proxy tracker should be told
5076 // that there is no longer a default proxy.
5077 // Strictly speaking this is not essential because having a proxy setting when
5078 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5079 mProxyTracker.setDefaultProxy(null);
5080 }
5081
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005082 // Immediate teardown.
5083 if (nai.teardownDelayMs == 0) {
5084 destroyNetwork(nai);
5085 return;
5086 }
5087
5088 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005089 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305090 try {
5091 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5092 } catch (RemoteException e) {
5093 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5094 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005095 }
5096 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5097 }
5098
5099 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005100 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005101 // Tell netd to clean up the configuration for this network
5102 // (routing rules, DNS, etc).
5103 // This may be slow as it requires a lot of netd shelling out to ip and
5104 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005105 // after we've rematched networks with requests (which might change the default
5106 // network or service a new request from an app), so network traffic isn't interrupted
5107 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005108 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005109 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005110 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005111 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5112 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5113 // false if the network was never created.
5114 // TODO: delete when S is no longer supported.
5115 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005116 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005117 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005118 }
5119
Chalard Jean1e4c2182023-10-06 18:45:53 +09005120 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005121 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005122 // Step 1 : maybe this network was the upstream for one or more local networks.
5123 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5124 if (!local.isLocalNetwork()) continue;
5125 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5126 if (null == selector) continue;
5127 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5128 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5129 // called after removing all associated NRIs from mNetworkRequests.
5130 if (null == nri) continue;
5131 final NetworkAgentInfo satisfier = nri.getSatisfier();
5132 if (disconnecting != satisfier) continue;
5133 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005134 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5135 // correctly contains null as an upstream.
5136 if (sendCallbacks) {
5137 nri.setSatisfier(null, null);
5138 notifyNetworkCallbacks(local,
5139 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5140 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005141 }
5142
5143 // Step 2 : maybe this is a local network that had an upstream.
5144 if (!disconnecting.isLocalNetwork()) return;
5145 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5146 if (null == selector) return;
5147 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5148 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5149 // is called after removing all associated NRIs from mNetworkRequests.
5150 if (null == nri) return;
5151 final NetworkAgentInfo satisfier = nri.getSatisfier();
5152 if (null == satisfier) return;
5153 removeLocalNetworkUpstream(disconnecting, satisfier);
5154 }
5155
5156 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5157 @NonNull final NetworkAgentInfo upstream) {
5158 try {
5159 mRoutingCoordinatorService.removeInterfaceForward(
5160 localAgent.linkProperties.getInterfaceName(),
5161 upstream.linkProperties.getInterfaceName());
5162 } catch (RemoteException e) {
5163 loge("Couldn't remove interface forward for "
5164 + localAgent.linkProperties.getInterfaceName() + " to "
5165 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5166 }
5167 }
5168
Ken Chen6df7a902021-04-09 15:08:42 +08005169 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005170 try {
5171 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005172 final NativeNetworkConfig config;
5173 if (nai.isVPN()) {
5174 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005175 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005176 return false;
5177 }
5178 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5179 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005180 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005181 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005182 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005183 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005184 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5185 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005186 getNetworkPermission(nai.networkCapabilities),
5187 false /* secure */,
5188 VpnManager.TYPE_VPN_NONE,
5189 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005190 }
Ken Chen6df7a902021-04-09 15:08:42 +08005191 mNetd.networkCreate(config);
5192 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005193 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5194 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005195 return true;
5196 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005197 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005198 return false;
5199 }
5200 }
5201
Ken Chen6df7a902021-04-09 15:08:42 +08005202 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005203 if (mDscpPolicyTracker != null) {
5204 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5205 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005206 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005207 // the interface is going to go away. Don't send the callbacks however ; if the network
5208 // was is being disconnected the callbacks have already been sent, and if it is being
5209 // destroyed pending replacement they will be sent when it is disconnected.
5210 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005211 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005212 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005213 } catch (RemoteException | ServiceSpecificException e) {
5214 loge("Exception destroying network(networkDestroy): " + e);
5215 }
5216 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005217 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005218 } catch (RemoteException | ServiceSpecificException e) {
5219 loge("Exception destroying network: " + e);
5220 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005221 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5222 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5223 // gets created, could add data to DnsManager data structures that will never get deleted.
5224 mDnsManager.removeNetwork(nai.network);
5225
5226 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005227 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005228 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5229 }
5230
Chalard Jean254bd162022-08-25 13:04:51 +09005231 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005232 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005233 }
5234
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005235 // If this method proves to be too slow then we can maintain a separate
5236 // pendingIntent => NetworkRequestInfo map.
5237 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5238 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005239 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5240 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5241 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005242 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005243 return entry.getValue();
5244 }
5245 }
5246 return null;
5247 }
5248
Chalard Jean524f0b12021-10-25 21:11:56 +09005249 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005250 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005251 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5252 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5253 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5254 // bug is fixed.
5255 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005256 throw new IllegalStateException("This NRI is already registered. New : " + nri
5257 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005258 }
5259 }
5260 }
5261 }
5262
Chalard Jeanac9ace02022-01-26 16:54:05 +09005263 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5264 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005265 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09005266 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09005267 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005268 }
5269 return false;
5270 }
5271
James Mattisf7027322020-12-13 16:28:14 -08005272 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005273 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005274 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5275 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5276 final NetworkRequestInfo existingRequest =
5277 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005278 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005279 if (DBG) {
5280 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5281 + nri.mRequests.get(0) + " because their intents matched.");
5282 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005283 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005284 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005285 }
Erik Kline05f2b402015-04-30 12:58:40 +09005286 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005287 }
5288
James Mattisf7027322020-12-13 16:28:14 -08005289 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005290 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005291 }
5292
James Mattis3ce3d3c2021-02-09 18:18:28 -08005293 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005294 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005295 for (final NetworkRequestInfo nri : nris) {
5296 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005297 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005298 for (final NetworkRequest req : nri.mRequests) {
5299 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005300 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005301 if (req.isListen()) {
5302 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5303 if (req.networkCapabilities.hasSignalStrength()
5304 && network.satisfiesImmutableCapabilitiesOf(req)) {
5305 updateSignalStrengthThresholds(network, "REGISTER", req);
5306 }
James Mattisf7027322020-12-13 16:28:14 -08005307 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005308 }
5309 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005310
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005311 // If this NRI has a satisfier already, it is replacing an older request that
5312 // has been removed. Track it.
5313 final NetworkRequest activeRequest = nri.getActiveRequest();
5314 if (null != activeRequest) {
5315 // If there is an active request, then for sure there is a satisfier.
5316 nri.getSatisfier().addRequest(activeRequest);
5317 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005318 }
James Mattisf7027322020-12-13 16:28:14 -08005319
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005320 if (mFlags.noRematchAllRequestsOnRegister()) {
5321 rematchNetworksAndRequests(nris);
5322 } else {
5323 rematchAllNetworksAndRequests();
5324 }
James Mattis45d81842021-01-10 14:24:24 -08005325
Chalard Jean0354d8c2021-01-12 10:58:56 +09005326 // Requests that have not been matched to a network will not have been sent to the
5327 // providers, because the old satisfier and the new satisfier are the same (null in this
5328 // case). Send these requests to the providers.
5329 for (final NetworkRequestInfo nri : nris) {
5330 for (final NetworkOfferInfo noi : mNetworkOffers) {
5331 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005332 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005333 }
5334 }
5335
James Mattisf7027322020-12-13 16:28:14 -08005336 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5337 final int callingUid) {
5338 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005339 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005340 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5341 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5342 handleReleaseNetworkRequest(
5343 nri.mRequests.get(0),
5344 callingUid,
5345 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005346 }
5347 }
5348
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005349 // Determines whether the network is the best (or could become the best, if it validated), for
5350 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5351 // on the value of reason:
5352 //
5353 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5354 // then it should be torn down.
5355 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5356 // then it should be lingered.
5357 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005358 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005359
Chalard Jean254bd162022-08-25 13:04:51 +09005360 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005361 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5362 return false;
5363 }
5364
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005365 final int numRequests;
5366 switch (reason) {
5367 case TEARDOWN:
5368 numRequests = nai.numRequestNetworkRequests();
5369 break;
5370 case LINGER:
5371 numRequests = nai.numForegroundNetworkRequests();
5372 break;
5373 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005374 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005375 return true;
5376 }
5377
Chalard Jean947acd42021-03-08 22:29:27 +09005378 if (numRequests > 0) return false;
5379
Paul Jensende49eb12015-06-25 15:30:08 -04005380 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005381 if (reason == UnneededFor.LINGER
5382 && !nri.isMultilayerRequest()
5383 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005384 // Background requests don't affect lingering.
5385 continue;
5386 }
5387
James Mattis3d229892020-11-16 16:46:28 -08005388 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005389 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005390 }
5391 }
Paul Jensende49eb12015-06-25 15:30:08 -04005392 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005393 }
5394
James Mattis3d229892020-11-16 16:46:28 -08005395 private boolean isNetworkPotentialSatisfier(
5396 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005397 // While destroyed network sometimes satisfy requests (including occasionally newly
5398 // satisfying requests), *potential* satisfiers are networks that might beat a current
5399 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5400 // because it's never a good idea to keep a destroyed network in case it validates.
5401 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5402 // candidate after it's been replaced by another unvalidated network.
5403 if (candidate.isDestroyed()) return false;
5404 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005405 // request, return immediately. For multilayer requests, check to see if any of the
5406 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005407 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5408 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005409 return false;
5410 }
5411 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005412 // This multilayer listen request is satisfied therefore no further requests need to be
5413 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005414 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005415 return false;
5416 }
James Mattis3d229892020-11-16 16:46:28 -08005417 // As non-multilayer listen requests have already returned, the below would only happen
5418 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005419 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005420 continue;
5421 }
Chalard Jean80685f42023-10-30 18:31:27 +09005422 // If there is hope for this network might validate and subsequently become the best
5423 // network for that request, then it is needed. Note that this network can't already
5424 // be the best for this request, or it would be the current satisfier, and therefore
5425 // there would be no need to call this method to find out if it is a *potential*
5426 // satisfier ("unneeded", the only caller, only calls this if this network currently
5427 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005428 if (candidate.satisfies(req)) {
5429 // As soon as a network is found that satisfies a request, return. Specifically for
5430 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5431 // is important so as to not evaluate lower priority requests further in
5432 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005433 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5434 ? nri.getSatisfier() : null;
5435 // Note that this catches two important cases:
5436 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5437 // is currently satisfying the request. This is desirable when
5438 // cellular ends up validating but WiFi does not.
5439 // 2. Unvalidated WiFi will not be reaped when validated cellular
5440 // is currently satisfying the request. This is desirable when
5441 // WiFi ends up validating and out scoring cellular.
5442 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005443 }
5444 }
5445
5446 return false;
5447 }
5448
Erik Kline0c04b742016-07-07 16:50:58 +09005449 private NetworkRequestInfo getNriForAppRequest(
5450 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005451 // Looking up the app passed param request in mRequests isn't possible since it may return
5452 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5453 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005454 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5455 // to avoid potential race conditions when validating a package->uid mapping when sending
5456 // the callback on the very low-chance that an application shuts down prior to the callback
5457 // being sent.
5458 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5459 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005460
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005461 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005462 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005463 log(String.format("UID %d attempted to %s for unowned request %s",
5464 callingUid, requestedOperation, nri));
5465 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005466 }
Erik Kline0c04b742016-07-07 16:50:58 +09005467 }
5468
5469 return nri;
5470 }
5471
James Mattisf7027322020-12-13 16:28:14 -08005472 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5473 final String callingMethod) {
5474 if (nri.isMultilayerRequest()) {
5475 throw new IllegalStateException(
5476 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005477 }
5478 }
5479
James Mattisf7027322020-12-13 16:28:14 -08005480 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005481 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005482 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5483 // single NetworkRequest and thus does not apply to multilayer requests.
5484 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5485 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005486 return;
5487 }
James Mattis2516da32021-01-31 17:06:19 -08005488 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005489 return;
5490 }
James Mattisf7027322020-12-13 16:28:14 -08005491 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5492 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005493 }
5494 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005495 callCallbackForRequest(
5496 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005497 }
5498
James Mattisf7027322020-12-13 16:28:14 -08005499 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5500 final int callingUid,
5501 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005502 final NetworkRequestInfo nri =
5503 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5504 if (nri == null) {
5505 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005506 }
James Mattisf7027322020-12-13 16:28:14 -08005507 if (VDBG || (DBG && request.isRequest())) {
5508 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005509 }
5510 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005511 if (callOnUnavailable) {
5512 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5513 }
Erik Kline155a59a2015-11-25 12:49:38 +09005514 }
Erik Kline0c04b742016-07-07 16:50:58 +09005515
James Mattisa076c532020-12-02 14:12:41 -08005516 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005517 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005518 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005519 if (null == mNetworkRequests.remove(req)) {
5520 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5521 continue;
5522 }
James Mattisa076c532020-12-02 14:12:41 -08005523 if (req.isListen()) {
5524 removeListenRequestFromNetworks(req);
5525 }
5526 }
James Mattis8f036802021-06-20 16:26:01 -07005527 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005528 if (mDefaultNetworkRequests.remove(nri)) {
5529 // If this request was one of the defaults, then the UID rules need to be updated
5530 // WARNING : if the app(s) for which this network request is the default are doing
5531 // traffic, this will kill their connected sockets, even if an equivalent request
5532 // is going to be reinstated right away ; unconnected traffic will go on the default
5533 // until the new default is set, which will happen very soon.
5534 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5535 // remove ranges for those requests that won't have a replacement
5536 final NetworkAgentInfo satisfier = nri.getSatisfier();
5537 if (null != satisfier) {
5538 try {
paulhu0e79d952021-06-09 16:11:35 +08005539 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5540 satisfier.network.getNetId(),
5541 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005542 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005543 } catch (RemoteException e) {
5544 loge("Exception setting network preference default network", e);
5545 }
5546 }
5547 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005548
Junyu Lai00d92df2022-07-05 11:01:52 +08005549 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005550 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005551 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005552
5553 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005554 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005555 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005556 }
5557 }
5558
Chalard Jean0354d8c2021-01-12 10:58:56 +09005559 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5560 // needed for this offer.
5561 for (final NetworkOfferInfo noi : mNetworkOffers) {
5562 for (final NetworkRequest req : nri.mRequests) {
5563 if (req.isRequest() && noi.offer.neededFor(req)) {
5564 noi.offer.onNetworkUnneeded(req);
5565 }
5566 }
5567 }
James Mattisa076c532020-12-02 14:12:41 -08005568 }
5569
James Mattis3ce3d3c2021-02-09 18:18:28 -08005570 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5571 for (final NetworkRequestInfo nri : nris) {
5572 if (mDefaultRequest == nri) {
5573 // Make sure we never remove the default request.
5574 continue;
5575 }
5576 handleRemoveNetworkRequest(nri);
5577 }
5578 }
5579
James Mattisa076c532020-12-02 14:12:41 -08005580 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5581 // listens don't have a singular affected Network. Check all networks to see
5582 // if this listen request applies and remove it.
5583 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5584 nai.removeRequest(req.requestId);
5585 if (req.networkCapabilities.hasSignalStrength()
5586 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5587 updateSignalStrengthThresholds(nai, "RELEASE", req);
5588 }
5589 }
5590 }
5591
5592 /**
5593 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5594 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5595 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5596 */
5597 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5598 boolean wasKept = false;
5599 final NetworkAgentInfo nai = nri.getSatisfier();
5600 if (nai != null) {
5601 final int requestLegacyType = nri.getActiveRequest().legacyType;
5602 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5603 nai.removeRequest(nri.getActiveRequest().requestId);
5604 if (VDBG || DDBG) {
5605 log(" Removing from current network " + nai.toShortString()
5606 + ", leaving " + nai.numNetworkRequests() + " requests.");
5607 }
5608 // If there are still lingered requests on this network, don't tear it down,
5609 // but resume lingering instead.
5610 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005611 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005612 notifyNetworkLosing(nai, now);
5613 }
5614 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5615 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5616 teardownUnneededNetwork(nai);
5617 } else {
5618 wasKept = true;
5619 }
James Mattisa076c532020-12-02 14:12:41 -08005620 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5621 // Went from foreground to background.
5622 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005623 }
5624
Erik Kline0c04b742016-07-07 16:50:58 +09005625 // Maintain the illusion. When this request arrived, we might have pretended
5626 // that a network connected to serve it, even though the network was already
5627 // connected. Now that this request has gone away, we might have to pretend
5628 // that the network disconnected. LegacyTypeTracker will generate that
5629 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005630 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005631 boolean doRemove = true;
5632 if (wasKept) {
5633 // check if any of the remaining requests for this network are for the
5634 // same legacy type - if so, don't remove the nai
5635 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5636 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005637 if (otherRequest.legacyType == requestLegacyType
5638 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005639 if (DBG) log(" still have other legacy request - leaving");
5640 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005641 }
5642 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005643 }
5644
Erik Kline0c04b742016-07-07 16:50:58 +09005645 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005646 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005647 }
5648 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005649 }
5650 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005651
Junyu Lai00d92df2022-07-05 11:01:52 +08005652 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005653 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005654 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5655 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5656 }
5657
Lorenzo Colittid6459092016-07-04 12:55:44 +09005658 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005659 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005660 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005661 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005662 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005663 }
5664
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005665 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005666 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5667 enforceNetworkStackSettingsOrSetup();
5668 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5669 encodeBool(accept), encodeBool(always), network));
5670 }
5671
5672 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005673 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005674 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005675 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5676 }
5677
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005678 @Override
5679 public void setTestAllowBadWifiUntil(long timeMs) {
5680 enforceSettingsPermission();
5681 if (!Build.isDebuggable()) {
5682 throw new IllegalStateException("Does not support in non-debuggable build");
5683 }
5684
5685 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5686 throw new IllegalArgumentException("It should not exceed "
5687 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5688 }
5689
5690 mHandler.sendMessage(
5691 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5692 }
5693
chiachangwange0192a72023-02-06 13:25:01 +00005694 @Override
5695 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5696 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005697
5698 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5699 throw new IllegalArgumentException("Argument should not exceed "
5700 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5701 }
5702
5703 mHandler.sendMessage(
5704 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5705 }
5706
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005707 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5708 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5709 " accept=" + accept + " always=" + always);
5710
5711 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5712 if (nai == null) {
5713 // Nothing to do.
5714 return;
5715 }
5716
Chalard Jean254bd162022-08-25 13:04:51 +09005717 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005718 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005719 return;
5720 }
5721
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005722 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005723 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005724 }
5725
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005726 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5727 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005728 // If network becomes partial connectivity and user already accepted to use this
5729 // network, we should respect the user's option and don't need to popup the
5730 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005731 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005732 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005733 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005734 }
5735
5736 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005737 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005738 }
5739
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005740 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005741 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005742 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005743 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005744 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005745 }
5746
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005747 }
5748
lucaslin2240ef62019-03-12 13:08:03 +08005749 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5750 boolean always) {
5751 if (DBG) {
5752 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5753 + " always=" + always);
5754 }
5755
5756 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5757 if (nai == null) {
5758 // Nothing to do.
5759 return;
5760 }
5761
Chalard Jean254bd162022-08-25 13:04:51 +09005762 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005763 // The network validated while the dialog box was up. Take no action.
5764 return;
5765 }
5766
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005767 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5768 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005769 }
5770
5771 // TODO: Use the current design or save the user choice into IpMemoryStore.
5772 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005773 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005774 }
5775
5776 if (!accept) {
5777 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005778 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005779 // Tear down the network.
5780 teardownUnneededNetwork(nai);
5781 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005782 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5783 // result in a partial connectivity result which will be processed by
5784 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005785 //
5786 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5787 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005788 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005789 }
5790 }
5791
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005792 private void handleSetAvoidUnvalidated(Network network) {
5793 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005794 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005795 // Nothing to do. The network either disconnected or revalidated.
5796 return;
5797 }
Chalard Jean254bd162022-08-25 13:04:51 +09005798 if (0L == nai.getAvoidUnvalidated()) {
5799 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005800 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005801 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005802 }
5803 }
5804
Chalard Jean5fb43c72022-09-08 19:03:14 +09005805 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005806 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005807 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005808 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005809 }
5810
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005811 @Override
5812 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005813 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005814 mHandler.post(() -> {
5815 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5816 if (nai == null) return;
5817 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005818 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005819 });
5820 }
5821
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005822 /**
5823 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5824 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005825 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005826 * @param appExtras Bundle to use as intent extras for the captive portal application.
5827 * Must be treated as opaque to avoid preventing the captive portal app to
5828 * update its arguments.
5829 */
5830 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005831 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005832 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5833 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005834
5835 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5836 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005837 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5838 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005839 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5840
lucaslin75ff7022020-12-17 04:14:35 +08005841 final long token = Binder.clearCallingIdentity();
5842 try {
5843 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5844 } finally {
5845 Binder.restoreCallingIdentity(token);
5846 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005847 }
5848
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005849 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5850 private final Network mNetwork;
5851
5852 private CaptivePortalImpl(Network network) {
5853 mNetwork = network;
5854 }
5855
5856 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005857 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005858 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5859 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005860 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5861 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5862 // Since the network will be disconnected, skip notifying NetworkMonitor
5863 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005864 }
5865
Chiachang Wang938bfba2020-01-09 13:50:55 +08005866 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005867 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005868 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005869 }
5870
5871 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005872 public void appRequest(final int request) {
5873 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5874 if (nm == null) return;
5875
5876 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005877 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005878 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005879 }
5880 }
5881
5882 @Nullable
5883 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5884 // getNetworkAgentInfoForNetwork is thread-safe
5885 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5886 if (nai == null) return null;
5887
5888 // nai.networkMonitor() is thread-safe
5889 return nai.networkMonitor();
5890 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005891 }
5892
Hugo Benichic9048bc2016-09-14 23:23:08 +00005893 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005894 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005895 }
5896
Chalard Jean020b93a2022-09-01 13:20:14 +09005897 private boolean activelyPreferBadWifi() {
5898 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5899 }
5900
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005901 /**
5902 * Return whether the device should maintain continuous, working connectivity by switching away
5903 * from WiFi networks having no connectivity.
5904 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5905 */
5906 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005907 if (!checkNetworkStackPermission()) {
5908 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5909 }
5910 return avoidBadWifi();
5911 }
5912
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005913 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005914 ensureRunningOnConnectivityServiceThread();
5915 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005916 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005917 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005918 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005919 if (avoidBadWifi) {
5920 // If the device is now avoiding bad wifi, remove notifications that might have
5921 // been put up when the device didn't.
5922 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5923 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005924 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005925 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5926 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5927 for (final NetworkOfferInfo noi : offersToUpdate) {
5928 updateOfferScore(noi.offer);
5929 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005930 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005931 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005932 }
5933
Erik Kline95ecfee2016-10-02 18:02:14 +09005934 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005935 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005936 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005937 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005938 if (!configRestrict) {
5939 pw.println("Bad Wi-Fi avoidance: unrestricted");
5940 return;
5941 }
5942
5943 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5944 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005945 pw.println("Config restrict: " + configRestrict);
5946 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005947
Chalard Jeane0fdea32022-09-14 21:44:22 +09005948 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005949 String description;
5950 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005951 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005952 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005953 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005954 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005955 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005956 description = "avoid";
5957 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005958 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005959 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005960 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005961
5962 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5963 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005964 if (null == configValue) {
5965 description = "unset";
5966 } else if (configValue) {
5967 description = "force true";
5968 } else {
5969 description = "force false";
5970 }
5971 pw.println("Actively prefer bad wifi conf: " + description);
5972 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005973 pw.println("Network overrides:");
5974 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005975 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005976 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005977 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005978 }
5979 }
5980 pw.decreaseIndent();
5981 pw.decreaseIndent();
5982 }
5983
paulhu7746e4e2020-06-09 19:07:03 +08005984 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5985 // unify the method.
5986 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5987 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5988 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5989 return settingsComponent != null
5990 ? settingsComponent.getPackageName() : "com.android.settings";
5991 }
5992
lucaslinb1e8e382019-01-24 15:55:30 +08005993 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005994 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005995 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005996 switch (type) {
5997 case NO_INTERNET:
5998 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005999 // High priority because it is only displayed for explicitly selected networks.
6000 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006001 break;
lucasline117e2e2019-10-22 18:27:33 +08006002 case PRIVATE_DNS_BROKEN:
6003 action = Settings.ACTION_WIRELESS_SETTINGS;
6004 // High priority because we should let user know why there is no internet.
6005 highPriority = true;
6006 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006007 case LOST_INTERNET:
6008 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006009 // High priority because it could help the user avoid unexpected data usage.
6010 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006011 break;
lucaslin2240ef62019-03-12 13:08:03 +08006012 case PARTIAL_CONNECTIVITY:
6013 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006014 // Don't bother the user with a high-priority notification if the network was not
6015 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006016 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006017 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006018 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006019 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006020 return;
6021 }
6022
6023 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006024 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006025 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006026 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006027 // Some OEMs have their own Settings package. Thus, need to get the current using
6028 // Settings package name instead of just use default name "com.android.settings".
6029 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6030 intent.setClassName(settingsPkgName,
6031 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006032 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006033
paulhu2af50222020-10-11 22:52:27 +08006034 PendingIntent pendingIntent = PendingIntent.getActivity(
6035 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006036 0 /* requestCode */,
6037 intent,
paulhu2af50222020-10-11 22:52:27 +08006038 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006039
Serik Beketayevec8ad212020-12-07 22:43:07 -08006040 mNotifier.showNotification(
6041 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006042 }
6043
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006044 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6045 // Don't prompt if the network is validated, and don't prompt on captive portals
6046 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006047 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006048 return false;
6049 }
6050
6051 // If a network has partial connectivity, always prompt unless the user has already accepted
6052 // partial connectivity and selected don't ask again. This ensures that if the device
6053 // automatically connects to a network that has partial Internet access, the user will
6054 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006055 // because we have prompted them.
6056 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006057 return true;
6058 }
6059
6060 // If a network has no Internet access, only prompt if the network was explicitly selected
6061 // and if the user has not already told us to use the network regardless of whether it
6062 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006063 if (nai.networkAgentConfig.explicitlySelected
6064 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006065 return true;
6066 }
6067
6068 return false;
6069 }
6070
Chalard Jean5fb43c72022-09-08 19:03:14 +09006071 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6072 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006073
Chalard Jean5fb43c72022-09-08 19:03:14 +09006074 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6075 if (null == nai) return;
6076
6077 if (nai.setEvaluated()) {
6078 // If setEvaluated() returned true, the network never had any form of connectivity.
6079 // This may have an impact on request matching if bad WiFi avoidance is off and the
6080 // network was found not to have Internet access.
6081 nai.updateScoreForNetworkAgentUpdate();
6082 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006083
6084 // Also, if this is WiFi and it should be preferred actively, now is the time to
6085 // prompt the user that they walked past and connected to a bad WiFi.
6086 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6087 && !avoidBadWifi()
6088 && activelyPreferBadWifi()) {
6089 // The notification will be removed if the network validates or disconnects.
6090 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6091 return;
6092 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006093 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006094
Chalard Jean5fb43c72022-09-08 19:03:14 +09006095 if (!shouldPromptUnvalidated(nai)) return;
6096
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006097 // Stop automatically reconnecting to this network in the future. Automatically connecting
6098 // to a network that provides no or limited connectivity is not useful, because the user
6099 // cannot use that network except through the notification shown by this method, and the
6100 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006101 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006102
Chalard Jean254bd162022-08-25 13:04:51 +09006103 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006104 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006105 } else {
6106 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6107 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006108 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006109
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006110 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6111 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006112 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006113
lucaslin2240ef62019-03-12 13:08:03 +08006114 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6115 return;
6116 }
6117
6118 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006119 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006120 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006121 }
6122
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006123 @Override
6124 public int getMultipathPreference(Network network) {
6125 enforceAccessPermission();
6126
6127 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006128 if (nai != null && nai.networkCapabilities
6129 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006130 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6131 }
6132
Aaron Huang9a57acf2020-12-08 10:03:29 +08006133 final NetworkPolicyManager netPolicyManager =
6134 mContext.getSystemService(NetworkPolicyManager.class);
6135
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006136 final long token = Binder.clearCallingIdentity();
6137 final int networkPreference;
6138 try {
6139 networkPreference = netPolicyManager.getMultipathPreference(network);
6140 } finally {
6141 Binder.restoreCallingIdentity(token);
6142 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006143 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006144 return networkPreference;
6145 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006146 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6147 }
6148
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006149 @Override
6150 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006151 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006152 }
6153
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006154 private class InternalHandler extends Handler {
6155 public InternalHandler(Looper looper) {
6156 super(looper);
6157 }
6158
6159 @Override
6160 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006161 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006162 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006163 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006164 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006165 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006166 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006167 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006168 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006169 break;
6170 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006171 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006172 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006173 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006174 break;
6175 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006176 case EVENT_REGISTER_NETWORK_PROVIDER: {
6177 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006178 break;
6179 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006180 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6181 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006182 break;
6183 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006184 case EVENT_REGISTER_NETWORK_OFFER: {
6185 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6186 break;
6187 }
6188 case EVENT_UNREGISTER_NETWORK_OFFER: {
6189 final NetworkOfferInfo offer =
6190 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6191 if (null != offer) {
6192 handleUnregisterNetworkOffer(offer);
6193 }
6194 break;
6195 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006196 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006197 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6198 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6199 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006200 break;
6201 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006202 case EVENT_REGISTER_NETWORK_REQUEST:
6203 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006204 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006205 break;
6206 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006207 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6208 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006209 handleRegisterNetworkRequestWithIntent(msg);
6210 break;
6211 }
Erik Kline155a59a2015-11-25 12:49:38 +09006212 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6213 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6214 handleTimedOutNetworkRequest(nri);
6215 break;
6216 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006217 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6218 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6219 break;
6220 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006221 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006222 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6223 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006224 break;
6225 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006226 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006227 Network network = (Network) msg.obj;
6228 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006229 break;
6230 }
lucaslin2240ef62019-03-12 13:08:03 +08006231 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6232 Network network = (Network) msg.obj;
6233 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6234 toBool(msg.arg2));
6235 break;
6236 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006237 case EVENT_SET_AVOID_UNVALIDATED: {
6238 handleSetAvoidUnvalidated((Network) msg.obj);
6239 break;
6240 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006241 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6242 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006243 break;
6244 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006245 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6246 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006247 break;
6248 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006249 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6250 // handler thread.
6251 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006252 mKeepaliveTracker.handleStartKeepalive(msg);
6253 break;
6254 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006255 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006256 final AutomaticOnOffKeepalive ki =
6257 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6258 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006259
chiachangwang676c84e2023-02-14 09:22:05 +00006260 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006261 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006262 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006263 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006264 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6265 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006266 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6267 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006268 }
6269 }
6270
6271 // If the network no longer exists, then the keepalive should have been
6272 // cleaned up already. There is no point trying to resume keepalives.
6273 if (!networkFound) return;
6274
chiachangwang676c84e2023-02-14 09:22:05 +00006275 if (underpinnedNetworkFound) {
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006276 final NetworkCapabilities underpinnedNc =
6277 getNetworkCapabilitiesInternal(underpinnedNetwork);
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006278 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wang59bcabe2023-11-15 07:28:01 +00006279 underpinnedNetwork.netId, underpinnedNc.getUids());
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006280 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006281 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006282 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006283 }
6284 break;
6285 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006286 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006287 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006288 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6289 (IBinder) msg.obj);
6290 if (ki == null) {
6291 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006292 return;
6293 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006294 final int reason = msg.arg2;
6295 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006296 break;
6297 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006298 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6299 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6300 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006301 break;
6302 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006303 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6304 handlePrivateDnsSettingsChanged();
6305 break;
dalyk1720e542018-03-05 12:42:22 -05006306 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6307 handlePrivateDnsValidationUpdate(
6308 (PrivateDnsValidationUpdate) msg.obj);
6309 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006310 case EVENT_UID_BLOCKED_REASON_CHANGED:
6311 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006312 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006313 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6314 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6315 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006316 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006317 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6318 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006319 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006320 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006321 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006322 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006323 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6324 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006325 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006326 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006327 }
lucaslin1193a5d2021-01-21 02:04:15 +08006328 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006329 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006330 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006331 break;
paulhu51f77dc2021-06-07 02:34:20 +00006332 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6333 handleMobileDataPreferredUidsChanged();
6334 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006335 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6336 final long timeMs = ((Long) msg.obj).longValue();
6337 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6338 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006339 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6340 handleIngressRateLimitChanged();
6341 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006342 case EVENT_USER_DOES_NOT_WANT:
6343 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6344 if (nai == null) break;
6345 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006346 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006347 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006348 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6349 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6350 break;
chiachangwange0192a72023-02-06 13:25:01 +00006351 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6352 final long time = ((Long) msg.obj).longValue();
6353 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6354 break;
6355 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006356 case EVENT_UID_FROZEN_STATE_CHANGED:
6357 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6358 handleFrozenUids(args.mUids, args.mFrozenStates);
6359 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006360 }
6361 }
6362 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006363
Lorenzo Colittid6459092016-07-04 12:55:44 +09006364 @Override
markchien5776f962019-12-16 20:15:20 +08006365 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006366 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006367 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006368 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6369 Context.TETHERING_SERVICE);
6370 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006371 }
6372
Lorenzo Colittid6459092016-07-04 12:55:44 +09006373 @Override
markchien5776f962019-12-16 20:15:20 +08006374 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006375 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006376 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006377 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6378 Context.TETHERING_SERVICE);
6379 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006380 }
6381
Lorenzo Colittid6459092016-07-04 12:55:44 +09006382 @Override
markchien5776f962019-12-16 20:15:20 +08006383 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006384 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006385 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006386 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6387 Context.TETHERING_SERVICE);
6388 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006389 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006390
markchien5776f962019-12-16 20:15:20 +08006391
Lorenzo Colittid6459092016-07-04 12:55:44 +09006392 @Override
markchien5776f962019-12-16 20:15:20 +08006393 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006394 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006395 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006396 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6397 Context.TETHERING_SERVICE);
6398
6399 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006400 }
6401
Lorenzo Colittid6459092016-07-04 12:55:44 +09006402 @Override
markchien5776f962019-12-16 20:15:20 +08006403 @Deprecated
6404 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006405 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006406 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6407 Context.TETHERING_SERVICE);
6408
6409 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006410 }
6411
Udam Saini8f7d6a72017-06-07 12:06:28 -07006412 @Override
markchien5776f962019-12-16 20:15:20 +08006413 @Deprecated
6414 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006415 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006416 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6417 Context.TETHERING_SERVICE);
6418 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006419 }
6420
Robert Greenwalte0b00512014-07-02 09:59:16 -07006421 // Called when we lose the default network and have no replacement yet.
6422 // This will automatically be cleared after X seconds or a new default network
6423 // becomes CONNECTED, whichever happens first. The timer is started by the
6424 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006425 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006426 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006427 if (mNetTransitionWakeLock.isHeld()) {
6428 return;
6429 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006430 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006431 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6432 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006433 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006434 mWakelockLogs.log("ACQUIRE for " + forWhom);
6435 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006436 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006437 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006438 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006439 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006440
Hugo Benichi471b62a2017-03-30 23:18:10 +09006441 // Called when we gain a new default network to release the network transition wakelock in a
6442 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6443 // message is cancelled.
6444 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006445 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006446 if (!mNetTransitionWakeLock.isHeld()) {
6447 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006448 }
6449 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006450 // Cancel self timeout on wakelock hold.
6451 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6452 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6453 mHandler.sendMessageDelayed(msg, 1000);
6454 }
6455
6456 // Called when either message of ensureNetworkTransitionWakelock or
6457 // scheduleReleaseNetworkTransitionWakelock is processed.
6458 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6459 String event = eventName(eventId);
6460 synchronized (this) {
6461 if (!mNetTransitionWakeLock.isHeld()) {
6462 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006463 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006464 return;
6465 }
6466 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006467 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6468 mTotalWakelockDurationMs += lockDuration;
6469 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6470 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006471 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006472 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006473 }
6474
Robert Greenwalt986c7412010-09-08 15:24:47 -07006475 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006476 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006477 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006478 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006479 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006480 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006481 }
6482
Lorenzo Colittid6459092016-07-04 12:55:44 +09006483 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006484 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006485 enforceAccessPermission();
6486 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006487 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006488 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006489
6490 final NetworkAgentInfo nai;
6491 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006492 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006493 } else {
6494 nai = getNetworkAgentInfoForNetwork(network);
6495 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006496
6497 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006498 mHandler.obtainMessage(
6499 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006500 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006501
Hugo Benichid6b510a2017-04-06 17:22:18 +09006502 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006503 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006504 if (nai == null
6505 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006506 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006507 return;
6508 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006509 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006510 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006511 mConnectivityDiagnosticsHandler.sendMessage(
6512 mConnectivityDiagnosticsHandler.obtainMessage(
6513 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6514 new ReportedNetworkConnectivityInfo(
6515 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006516 return;
6517 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006518 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006519 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006520 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006521 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006522 // Validating a network that has not yet connected could result in a call to
6523 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006524 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006525 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006526 }
paulhu7aeba372020-12-30 00:42:19 +08006527 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6528 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006529 return;
6530 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006531
6532 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6533 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6534 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6535 // completed.
6536 mConnectivityDiagnosticsHandler.sendMessage(
6537 mConnectivityDiagnosticsHandler.obtainMessage(
6538 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6539 new ReportedNetworkConnectivityInfo(
6540 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006541 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006542 }
6543
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006544 // TODO: call into netd.
6545 private boolean queryUserAccess(int uid, Network network) {
6546 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6547 if (nai == null) return false;
6548
6549 // Any UID can use its default network.
6550 if (nai == getDefaultNetworkForUid(uid)) return true;
6551
6552 // Privileged apps can use any network.
6553 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6554 return true;
6555 }
6556
6557 // An unprivileged UID can use a VPN iff the VPN applies to it.
6558 if (nai.isVPN()) {
6559 return nai.networkCapabilities.appliesToUid(uid);
6560 }
6561
6562 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6563 // sockets, i.e., if it is the owner.
6564 final NetworkAgentInfo vpn = getVpnForUid(uid);
6565 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6566 && uid != vpn.networkCapabilities.getOwnerUid()) {
6567 return false;
6568 }
6569
6570 // The UID's permission must be at least sufficient for the network. Since the restricted
6571 // permission was already checked above, that just leaves background networks.
6572 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6573 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6574 }
6575
6576 // Unrestricted network. Anyone gets to use it.
6577 return true;
6578 }
6579
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006580 /**
6581 * Returns information about the proxy a certain network is using. If given a null network, it
6582 * it will return the proxy for the bound network for the caller app or the default proxy if
6583 * none.
6584 *
6585 * @param network the network we want to get the proxy information for.
6586 * @return Proxy information if a network has a proxy configured, or otherwise null.
6587 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006588 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006589 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006590 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006591 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006592 if (network == null) {
6593 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006594 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006595 true);
6596 if (activeNetwork == null) {
6597 return null;
6598 }
6599 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006600 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006601 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6602 // caller may not have.
6603 return getLinkPropertiesProxyInfo(network);
6604 }
6605 // No proxy info available if the calling UID does not have network access.
6606 return null;
6607 }
6608
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006609
6610 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006611 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6612 if (nai == null) return null;
6613 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006614 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6615 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006616 }
6617 }
6618
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006619 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006620 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006621 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006622 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006623 }
6624
Chalard Jean777e2e52018-06-07 18:02:37 +09006625 @Override
6626 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006627 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006628 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006629 }
6630
Aaron Huang9fe47be2021-06-08 13:11:45 +08006631 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006632 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006633 final NetworkAgentInfo nai = getDefaultNetwork();
6634 // TODO : this method should check that net == nai.network, unfortunately at this point
6635 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6636 // is only ever installed on the default network so in practice this is okay.
6637 if (null == nai) return;
6638 // PAC proxies only work on the default network. Therefore, only the default network
6639 // should have its link properties fixed up for PAC proxies.
6640 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6641 if (nai.everConnected()) {
6642 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6643 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006644 }
6645
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006646 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6647 // when any network changes proxy.
6648 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6649 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006650 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6651 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006652 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6653
Chalard Jean7d97afc2018-06-07 17:41:29 +09006654 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006655 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006656 }
6657 }
6658
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006659 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006660 final private HashMap<Uri, Integer> mUriEventMap;
6661 final private Context mContext;
6662 final private Handler mHandler;
6663
6664 SettingsObserver(Context context, Handler handler) {
6665 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006666 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006667 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006668 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006669 }
6670
Erik Kline05f2b402015-04-30 12:58:40 +09006671 void observe(Uri uri, int what) {
6672 mUriEventMap.put(uri, what);
6673 final ContentResolver resolver = mContext.getContentResolver();
6674 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006675 }
6676
6677 @Override
6678 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006679 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006680 }
6681
6682 @Override
6683 public void onChange(boolean selfChange, Uri uri) {
6684 final Integer what = mUriEventMap.get(uri);
6685 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006686 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006687 } else {
6688 loge("No matching event to send for URI=" + uri);
6689 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006690 }
6691 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006692
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006693 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006694 Log.d(TAG, s);
6695 }
6696
6697 private static void logw(String s) {
6698 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006699 }
6700
Daniel Brightf9e945b2020-06-15 16:10:01 -07006701 private static void logwtf(String s) {
6702 Log.wtf(TAG, s);
6703 }
6704
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006705 private static void logwtf(String s, Throwable t) {
6706 Log.wtf(TAG, s, t);
6707 }
6708
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006709 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006710 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006711 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006712
Hugo Benichi39621362017-02-11 17:04:43 +09006713 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006714 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006715 }
6716
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006717 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006718 * Return the information of all ongoing VPNs.
6719 *
6720 * <p>This method is used to update NetworkStatsService.
6721 *
6722 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006723 */
junyulai2050bed2021-01-23 09:46:34 +08006724 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006725 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006726 if (mLockdownEnabled) {
6727 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006728 }
junyulai2050bed2021-01-23 09:46:34 +08006729 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006730 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006731 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006732 if (info != null) {
6733 infoList.add(info);
6734 }
6735 }
junyulai2050bed2021-01-23 09:46:34 +08006736 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006737 }
6738
6739 /**
6740 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006741 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006742 */
junyulai2050bed2021-01-23 09:46:34 +08006743 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006744 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006745 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6746 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006747 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6748 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6749 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006750 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6751 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006752 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006753 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006754 }
6755 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006756
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006757 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006758
6759 List<String> interfaces = new ArrayList<>();
6760 for (Network network : underlyingNetworks) {
6761 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6762 if (underlyingNai == null) continue;
6763 LinkProperties lp = underlyingNai.linkProperties;
6764 for (String iface : lp.getAllInterfaceNames()) {
6765 if (!TextUtils.isEmpty(iface)) {
6766 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006767 }
6768 }
Benedict Wong34857f82019-06-12 17:46:15 +00006769 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006770
6771 if (interfaces.isEmpty()) return null;
6772
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006773 // Must be non-null or NetworkStatsService will crash.
6774 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6775 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006776 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006777 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006778
junyulai2050bed2021-01-23 09:46:34 +08006779 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6780 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006781 }
6782
James Mattisd31bdfa2020-12-23 16:37:26 -08006783 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006784 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6785 Network[] underlyingNetworks) {
6786 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006787 if (underlyingNetworks == null && defaultNetwork != null) {
6788 // null underlying networks means to track the default.
6789 underlyingNetworks = new Network[] { defaultNetwork };
6790 }
6791 return underlyingNetworks;
6792 }
6793
6794 // Returns true iff |network| is an underlying network of |nai|.
6795 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6796 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6797 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006798 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006799 final Network[] underlying = underlyingNetworksOrDefault(
6800 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006801 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006802 }
6803
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006804 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006805 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006806 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006807 * When underlying networks change, such networks may have to update capabilities to reflect
6808 * things like the metered bit, their transports, and so on. The capabilities are calculated
6809 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006810 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006811 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006812 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006813 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006814 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006815 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006816 }
6817 }
6818 }
6819
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006820 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6821 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6822 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6823 // a VPN is not up.
6824 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6825 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6826 for (UidRange range : blockedUidRanges) {
6827 if (range.contains(uid)) return true;
6828 }
6829 return false;
6830 }
6831
6832 @Override
6833 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006834 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006835 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6836 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6837 }
6838
6839 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6840 if (DBG) {
6841 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6842 + Arrays.toString(ranges));
6843 }
6844 // Cannot use a Set since the list of UID ranges might contain duplicates.
6845 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6846 for (int i = 0; i < ranges.length; i++) {
6847 if (requireVpn) {
6848 newVpnBlockedUidRanges.add(ranges[i]);
6849 } else {
6850 newVpnBlockedUidRanges.remove(ranges[i]);
6851 }
6852 }
6853
6854 try {
6855 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6856 } catch (RemoteException | ServiceSpecificException e) {
6857 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6858 + Arrays.toString(ranges) + "): netd command failed: " + e);
6859 }
6860
Chalard Jeandf29a852023-05-29 17:02:43 +09006861 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006862 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6863 }
6864
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006865 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6866 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006867 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6868 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006869 }
6870
6871 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6872 }
6873
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006874 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006875 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006876 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006877 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006878 }
6879
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006880 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6881 return mLockdownEnabled
6882 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6883 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006884 }
6885
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006886 private NetworkAgentInfo getLegacyLockdownNai() {
6887 if (!mLockdownEnabled) {
6888 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006889 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006890 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006891 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6892 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006893
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006894 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006895 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6896 // a local variable. There is no need to make a copy because its contents cannot change.
6897 final Network[] underlying = nai.declaredUnderlyingNetworks;
6898 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006899 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006900 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006901
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006902 // The legacy lockdown VPN always uses the default network.
6903 // If the VPN's underlying network is no longer the current default network, it means that
6904 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006905 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6906 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006907 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006908 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006909 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006910 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006911
6912 return nai;
6913 };
6914
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006915 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6916 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6917 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006918 private DetailedState getLegacyLockdownState(DetailedState origState) {
6919 if (origState != DetailedState.CONNECTED) {
6920 return origState;
6921 }
6922 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6923 ? DetailedState.CONNECTING
6924 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006925 }
6926
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006927 private void filterForLegacyLockdown(NetworkInfo ni) {
6928 if (!mLockdownEnabled || !ni.isConnected()) return;
6929 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6930 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6931 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6932 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6933 // network, this time with a state of CONNECTED.
6934 //
6935 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6936 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6937 // is not too far off the truth, since an always-on VPN, when not connected, is always
6938 // trying to reconnect.
6939 if (getLegacyLockdownNai() == null) {
6940 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6941 }
6942 }
6943
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006944 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006945 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006946 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006947 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006948 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6949 return;
6950 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006951 final long ident = Binder.clearCallingIdentity();
6952 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006953 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006954 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006955 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006956 } finally {
6957 Binder.restoreCallingIdentity(ident);
6958 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006959 }
Wink Savillecb117d32013-08-29 14:57:08 -07006960
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006961 @Override
6962 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006963 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006964 final long ident = Binder.clearCallingIdentity();
6965 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006966 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006967 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006968 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6969 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006970 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006971 } finally {
6972 Binder.restoreCallingIdentity(ident);
6973 }
6974 }
6975
James Mattis02220e22021-03-13 19:27:21 -08006976 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006977 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6978 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6979 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006980 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006981 }
6982
James Mattis02220e22021-03-13 19:27:21 -08006983 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006984 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006985 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006986 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6987 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006988 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006989 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6990 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6991 }
junyulaid91e7052020-08-28 13:44:33 +08006992 }
6993
James Mattis02220e22021-03-13 19:27:21 -08006994 private void onPackageChanged(@NonNull final String packageName) {
6995 // This is necessary in case a package is added or removed, but also when it's replaced to
6996 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6997 // as one in the preferences, then it should follow the same routing as that other package,
6998 // which means updating the rules is never to be needed in this case (whether it joins or
6999 // leaves a UID with a preference).
7000 if (isMappedInOemNetworkPreference(packageName)) {
7001 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7002 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007003
7004 // Invalidates cache entry when the package is updated.
7005 synchronized (mSelfCertifiedCapabilityCache) {
7006 mSelfCertifiedCapabilityCache.remove(packageName);
7007 }
James Mattis02220e22021-03-13 19:27:21 -08007008 }
7009
7010 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007011 @Override
7012 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007013 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007014 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007015 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007016
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007017 // User should be filled for below intents, check the existence.
7018 if (user == null) {
7019 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7020 return;
7021 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007022
Lorenzo Colitticd675292021-02-04 17:32:07 +09007023 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007024 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007025 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007026 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007027 } else {
junyulaid91e7052020-08-28 13:44:33 +08007028 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007029 }
7030 }
7031 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007032
James Mattis02220e22021-03-13 19:27:21 -08007033 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7034 @Override
7035 public void onReceive(Context context, Intent intent) {
7036 ensureRunningOnConnectivityServiceThread();
7037 switch (intent.getAction()) {
7038 case Intent.ACTION_PACKAGE_ADDED:
7039 case Intent.ACTION_PACKAGE_REMOVED:
7040 case Intent.ACTION_PACKAGE_REPLACED:
7041 onPackageChanged(intent.getData().getSchemeSpecificPart());
7042 break;
7043 default:
7044 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7045 }
7046 }
7047 };
7048
Junyu Lai38c75032023-12-04 07:52:19 +00007049 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
7050 private final BroadcastReceiver mDataSaverReceiver = new BroadcastReceiver() {
7051 @Override
7052 public void onReceive(Context context, Intent intent) {
7053 if (mDeps.isAtLeastV()) {
7054 throw new IllegalStateException(
7055 "data saver status should be updated from platform");
7056 }
7057 ensureRunningOnConnectivityServiceThread();
7058 switch (intent.getAction()) {
7059 case ACTION_RESTRICT_BACKGROUND_CHANGED:
7060 // If the uid is present in the deny list, the API will consistently
7061 // return ENABLED. To retrieve the global switch status, the system
7062 // uid is chosen because it will never be included in the deny list.
7063 final int dataSaverForSystemUid =
7064 mPolicyManager.getRestrictBackgroundStatus(Process.SYSTEM_UID);
7065 final boolean isDataSaverEnabled = (dataSaverForSystemUid
7066 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
7067 mBpfNetMaps.setDataSaverEnabled(isDataSaverEnabled);
7068 break;
7069 default:
7070 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7071 }
7072 }
7073 };
7074
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007075 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007076 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007077
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007078 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007079 public final String name;
7080 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007081 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007082 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007083
lifraf3a3492021-03-10 13:58:14 +08007084 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7085 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007086 this.name = name;
7087 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007088 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007089 mDeathRecipient = deathRecipient;
7090
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007091 if (mDeathRecipient == null) {
7092 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007093 }
7094 }
7095
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007096 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007097 try {
7098 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7099 } catch (RemoteException e) {
7100 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007101 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007102 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007103 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007104
James Mattis4fce5d12020-11-12 15:53:42 -08007105 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7106 for (int i = 0; i < requests.size(); i++) {
7107 ensureNetworkRequestHasType(requests.get(i));
7108 }
7109 }
7110
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007111 private void ensureNetworkRequestHasType(NetworkRequest request) {
7112 if (request.type == NetworkRequest.Type.NONE) {
7113 throw new IllegalArgumentException(
7114 "All NetworkRequests in ConnectivityService must have a type");
7115 }
7116 }
7117
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007118 /**
7119 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007120 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007121 */
James Mattis258ea3c2020-11-15 15:04:40 -08007122 @VisibleForTesting
7123 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007124 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7125 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007126 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007127
James Mattisa076c532020-12-02 14:12:41 -08007128 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7129 void setSatisfier(
7130 @Nullable final NetworkAgentInfo satisfier,
7131 @Nullable final NetworkRequest activeRequest) {
7132 mSatisfier = satisfier;
7133 mActiveRequest = activeRequest;
7134 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007135
James Mattisd31bdfa2020-12-23 16:37:26 -08007136 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007137 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007138 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007139 private NetworkAgentInfo mSatisfier;
7140 NetworkAgentInfo getSatisfier() {
7141 return mSatisfier;
7142 }
7143
7144 // The request in mRequests assigned to a network agent. This is null if none of the
7145 // requests in mRequests can be satisfied. This member has the constraint of only being
7146 // accessible on the handler thread.
7147 @Nullable
7148 private NetworkRequest mActiveRequest;
7149 NetworkRequest getActiveRequest() {
7150 return mActiveRequest;
7151 }
7152
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007153 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007154 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007155 @Nullable
7156 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007157
7158 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007159 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007160 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007161 final int mPid;
7162 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007163 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007164 @Nullable
7165 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007166
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007167 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007168 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007169
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007170 // Effective UID of this request. This is different from mUid when a privileged process
7171 // files a request on behalf of another UID. This UID is used to determine blocked status,
7172 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7173 // maximum limit of registered callbacks per UID.
7174 final int mAsUid;
7175
paulhu48291862021-07-14 14:53:57 +08007176 // Preference order of this request.
7177 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007178
James Mattis3ce3d3c2021-02-09 18:18:28 -08007179 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7180 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7181 // maintained for keying off of. This is only a concern when the original nri
7182 // mNetworkRequests changes which happens currently for apps that register callbacks to
7183 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7184 // that match the per-app default nri that currently tracks the calling app's uid so that
7185 // callbacks are fired at the appropriate time. When the callbacks fire,
7186 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7187 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7188 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7189 @NonNull
7190 private final NetworkRequest mNetworkRequestForCallback;
7191 NetworkRequest getNetworkRequestForCallback() {
7192 return mNetworkRequestForCallback;
7193 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007194
James Mattisd31bdfa2020-12-23 16:37:26 -08007195 /**
7196 * Get the list of UIDs this nri applies to.
7197 */
7198 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007199 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007200 // networkCapabilities.getUids() returns a defensive copy.
7201 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007202 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7203 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007204 }
7205
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007206 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7207 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007208 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007209 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007210 }
7211
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007212 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007213 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007214 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007215 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007216 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007217 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007218 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007219 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007220 mBinder = null;
7221 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007222 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007223 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007224 mPerUidCounter = getRequestCounter(this);
7225 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007226 /**
7227 * Location sensitive data not included in pending intent. Only included in
7228 * {@link NetworkCallback}.
7229 */
7230 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007231 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007232 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007233 }
7234
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007235 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007236 @Nullable final IBinder binder,
7237 @NetworkCallback.Flag int callbackFlags,
7238 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007239 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7240 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007241 }
7242
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007243 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007244 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007245 @Nullable final IBinder binder,
7246 @NetworkCallback.Flag int callbackFlags,
7247 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007248 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007249 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007250 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007251 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007252 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007253 mBinder = binder;
7254 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007255 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007256 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007257 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007258 mPerUidCounter = getRequestCounter(this);
7259 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007260 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007261 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007262 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007263 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007264 }
7265
James Mattis3ce3d3c2021-02-09 18:18:28 -08007266 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7267 @NonNull final List<NetworkRequest> r) {
7268 super();
7269 ensureAllNetworkRequestsHaveType(r);
7270 mRequests = initializeRequests(r);
7271 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007272 final NetworkAgentInfo satisfier = nri.getSatisfier();
7273 if (null != satisfier) {
7274 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7275 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007276 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007277 // As this code creates a new NRI with a new set of requests, figure out which of
7278 // the list of requests should be the active request. It is always the first
7279 // request of the list that can be satisfied by the satisfier since the order of
7280 // requests is a priority order.
7281 // Note even in the presence of a satisfier there may not be an active request,
7282 // when the satisfier is the no-service network.
7283 NetworkRequest activeRequest = null;
7284 for (final NetworkRequest candidate : r) {
7285 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7286 activeRequest = candidate;
7287 break;
7288 }
7289 }
7290 setSatisfier(satisfier, activeRequest);
7291 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007292 mMessenger = nri.mMessenger;
7293 mBinder = nri.mBinder;
7294 mPid = nri.mPid;
7295 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007296 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007297 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007298 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007299 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007300 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007301 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007302 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007303 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007304 }
7305
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007306 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007307 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007308 }
7309
paulhue9913722021-05-26 15:19:20 +08007310 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007311 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007312 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007313 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007314 }
7315
James Mattis2516da32021-01-31 17:06:19 -08007316 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7317 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7318 // false.
7319 boolean isBeingSatisfied() {
7320 return (null != mSatisfier && null != mActiveRequest);
7321 }
7322
James Mattis3d229892020-11-16 16:46:28 -08007323 boolean isMultilayerRequest() {
7324 return mRequests.size() > 1;
7325 }
7326
James Mattis45d81842021-01-10 14:24:24 -08007327 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7328 // Creating a defensive copy to prevent the sender from modifying the list being
7329 // reflected in the return value of this method.
7330 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007331 return Collections.unmodifiableList(tempRequests);
7332 }
7333
James Mattisb1392002021-03-31 13:57:52 -07007334 void linkDeathRecipient() {
7335 if (null != mBinder) {
7336 try {
7337 mBinder.linkToDeath(this, 0);
7338 } catch (RemoteException e) {
7339 binderDied();
7340 }
7341 }
7342 }
7343
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007344 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007345 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007346 try {
7347 mBinder.unlinkToDeath(this, 0);
7348 } catch (NoSuchElementException e) {
7349 // Temporary workaround for b/194394697 pending analysis of additional logs
7350 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7351 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007352 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007353 }
7354
paulhu48291862021-07-14 14:53:57 +08007355 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7356 // Compare two preference orders.
7357 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007358 }
7359
paulhu48291862021-07-14 14:53:57 +08007360 int getPreferenceOrderForNetd() {
7361 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7362 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7363 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007364 }
paulhu48291862021-07-14 14:53:57 +08007365 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007366 }
7367
James Mattis4fce5d12020-11-12 15:53:42 -08007368 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007369 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007370 // As an immutable collection, mRequests cannot change by the time the
7371 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7372 // is acceptable. Use handleReleaseNetworkRequest and not directly
7373 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7374 // the app already unregistered the request.
7375 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7376 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007377 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007378
James Mattis4fce5d12020-11-12 15:53:42 -08007379 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007380 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007381 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7382 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007383 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007384 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007385 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007386 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007387 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007388 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007389 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007390 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007391 }
7392
Junyu Lai00d92df2022-07-05 11:01:52 +08007393 // Keep backward compatibility since the ServiceSpecificException is used by
7394 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7395 public static class RequestInfoPerUidCounter extends PerUidCounter {
7396 RequestInfoPerUidCounter(int maxCountPerUid) {
7397 super(maxCountPerUid);
7398 }
7399
7400 @Override
7401 public synchronized void incrementCountOrThrow(int uid) {
7402 try {
7403 super.incrementCountOrThrow(uid);
7404 } catch (IllegalStateException e) {
7405 throw new ServiceSpecificException(
7406 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7407 "Uid " + uid + " exceeded its allotted requests limit");
7408 }
7409 }
7410
7411 @Override
7412 public synchronized void decrementCountOrThrow(int uid) {
7413 throw new UnsupportedOperationException("Use decrementCount instead.");
7414 }
7415
7416 public synchronized void decrementCount(int uid) {
7417 try {
7418 super.decrementCountOrThrow(uid);
7419 } catch (IllegalStateException e) {
7420 logwtf("Exception when decrement per uid request count: ", e);
7421 }
7422 }
7423 }
7424
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007425 // This checks that the passed capabilities either do not request a
7426 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007427 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007428 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007429 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007430 throw new SecurityException("Insufficient permissions to request a specific SSID");
7431 }
paulhu1a407652019-03-22 16:35:06 +08007432
7433 if (nc.hasSignalStrength()
7434 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7435 throw new SecurityException(
7436 "Insufficient permissions to request a specific signal strength");
7437 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007438 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007439
junyulai2217bec2021-04-14 23:33:31 +08007440 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007441 enforceNetworkFactoryPermission();
7442 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007443 }
7444
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007445 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007446 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007447 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007448 // mNetworkRequests may contain the same value multiple times in case of
7449 // multilayer requests. It won't matter in this case because the thresholds
7450 // will then be the same and be deduplicated as they enter the `thresholds` set.
7451 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007452 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7453 for (final NetworkRequest req : nri.mRequests) {
7454 if (req.networkCapabilities.hasSignalStrength()
7455 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7456 thresholds.add(req.networkCapabilities.getSignalStrength());
7457 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007458 }
7459 }
7460 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007461 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007462 }
7463
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007464 private void updateSignalStrengthThresholds(
7465 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007466 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007467
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007468 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007469 String detail;
7470 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7471 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7472 } else {
7473 detail = reason;
7474 }
7475 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007476 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007477 }
7478
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007479 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007480 }
7481
Chalard Jeandd421992021-12-16 23:16:02 +09007482 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007483 if (nc == null) {
7484 return;
7485 }
7486 NetworkSpecifier ns = nc.getNetworkSpecifier();
7487 if (ns == null) {
7488 return;
7489 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007490 if (ns instanceof MatchAllNetworkSpecifier) {
7491 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7492 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007493 }
7494
Chalard Jeandd421992021-12-16 23:16:02 +09007495 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007496 ensureValidNetworkSpecifier(nc);
7497 if (nc.isPrivateDnsBroken()) {
7498 throw new IllegalArgumentException("Can't request broken private DNS");
7499 }
Chalard Jeande665262022-02-25 16:12:12 +09007500 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007501 throw new IllegalArgumentException("Can't request access UIDs");
7502 }
lucasline117e2e2019-10-22 18:27:33 +08007503 }
7504
Chalard Jeandd421992021-12-16 23:16:02 +09007505 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7506 ensureListenableCapabilities(nc);
7507 final String badCapability = nc.describeFirstNonRequestableCapability();
7508 if (badCapability != null) {
7509 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7510 }
7511 }
7512
Chiachang Wang3bc52762021-11-25 14:17:57 +08007513 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7514 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007515 private boolean isTargetSdkAtleast(int version, int callingUid,
7516 @NonNull String callingPackageName) {
7517 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007518 final PackageManager pm =
7519 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007520 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007521 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007522 if (callingVersion < version) return false;
7523 } catch (PackageManager.NameNotFoundException e) { }
7524 return true;
7525 }
7526
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007527 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007528 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007529 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007530 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007531 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007532 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007533 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7534 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007535 throw new SecurityException("Insufficient permissions to specify legacy type");
7536 }
markchienfac84a22020-03-18 21:16:15 +08007537 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007538 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007539 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007540 // Privileged callers can track the default network of another UID by passing in a UID.
7541 if (asUid != Process.INVALID_UID) {
7542 enforceSettingsPermission();
7543 } else {
7544 asUid = callingUid;
7545 }
junyulaiad010792021-01-11 16:53:38 +08007546 final NetworkRequest.Type reqType;
7547 try {
7548 reqType = NetworkRequest.Type.values()[reqTypeInt];
7549 } catch (ArrayIndexOutOfBoundsException e) {
7550 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7551 }
7552 switch (reqType) {
7553 case TRACK_DEFAULT:
7554 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007555 // is unused and will be replaced by ones appropriate for the UID (usually, the
7556 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007557 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007558 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007559 enforceAccessPermission();
7560 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007561 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007562 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007563 networkCapabilities = new NetworkCapabilities(defaultNc);
7564 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007565 case BACKGROUND_REQUEST:
7566 enforceNetworkStackOrSettingsPermission();
7567 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007568 case REQUEST:
7569 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7570 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007571 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007572 // TODO: this is incorrect. We mark the request as metered or not depending on
7573 // the state of the app when the request is filed, but we never change the
7574 // request if the app changes network state. http://b/29964605
7575 enforceMeteredApnPolicy(networkCapabilities);
7576 break;
junyulai1b1c8742021-03-12 20:05:08 +08007577 case LISTEN_FOR_BEST:
7578 enforceAccessPermission();
7579 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7580 break;
junyulaiad010792021-01-11 16:53:38 +08007581 default:
7582 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007583 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007584 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007585 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007586 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007587
junyulai1b1c8742021-03-12 20:05:08 +08007588 // Enforce FOREGROUND if the caller does not have permission to use background network.
7589 if (reqType == LISTEN_FOR_BEST) {
7590 restrictBackgroundRequestForCaller(networkCapabilities);
7591 }
7592
7593 // Set the UID range for this request to the single UID of the requester, unless the
7594 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007595 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7596 // are no visible methods to set the UIDs, an app could use reflection to try and get
7597 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007598 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007599 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7600 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007601
Etan Cohen85000162017-02-05 10:42:27 -08007602 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007603 throw new IllegalArgumentException("Bad timeout specified");
7604 }
Etan Cohen9786d922015-11-18 10:56:15 -08007605
James Mattis3ce3d3c2021-02-09 18:18:28 -08007606 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007607 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007608 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007609 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007610 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007611 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007612
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007613 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7614 // copied from the default request above. (This is necessary to ensure, for example, that
7615 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7616 // changes don't alter request matching.
7617 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7618 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007619 throw new IllegalStateException(
7620 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007621 + networkCapabilities + " vs. " + defaultNc);
7622 }
7623
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007624 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007625 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007626 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007627 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007628 }
7629 return networkRequest;
7630 }
7631
James Mattis3ce3d3c2021-02-09 18:18:28 -08007632 /**
7633 * Return the nri to be used when registering a network request. Specifically, this is used with
7634 * requests registered to track the default request. If there is currently a per-app default
7635 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7636 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007637 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7638 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007639 * @param nr the network request for the nri.
7640 * @param msgr the messenger for the nri.
7641 * @param binder the binder for the nri.
7642 * @param callingAttributionTag the calling attribution tag for the nri.
7643 * @return the nri to register.
7644 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007645 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007646 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007647 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007648 @Nullable String callingAttributionTag) {
7649 final List<NetworkRequest> requests;
7650 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7651 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007652 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007653 } else {
7654 requests = Collections.singletonList(nr);
7655 }
Roshan Pius951c0032020-12-22 15:10:42 -08007656 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007657 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007658 }
7659
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007660 private boolean shouldCheckCapabilitiesDeclaration(
7661 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7662 @NonNull final String callingPackageName) {
7663 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7664 // Only run the check if the change is enabled.
7665 if (!mDeps.isChangeEnabled(
7666 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7667 callingPackageName, user)) {
7668 return false;
7669 }
7670
7671 return networkCapabilities.hasCapability(
7672 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7673 || networkCapabilities.hasCapability(
7674 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7675 }
7676
7677 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007678 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007679 // This check is added to fix the linter error for "current min is 30", which is not going
7680 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007681 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007682 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7683 return;
7684 }
7685 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007686 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007687 try {
7688 synchronized (mSelfCertifiedCapabilityCache) {
7689 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7690 callerPackageName);
7691 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007692 final PackageManager packageManager =
7693 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
7694 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007695 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7696 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7697 callerPackageName
7698 );
7699 final XmlResourceParser parser = packageManager
7700 .getResourcesForApplication(callerPackageName)
7701 .getXml(networkSliceProperty.getResourceId());
7702 applicationNetworkCapabilities =
7703 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7704 mSelfCertifiedCapabilityCache.put(callerPackageName,
7705 applicationNetworkCapabilities);
7706 }
7707
7708 }
7709 } catch (PackageManager.NameNotFoundException ne) {
7710 throw new SecurityException(
7711 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7712 + " property");
7713 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7714 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007715 } finally {
7716 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007717 }
7718
7719 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7720 networkCapabilities);
7721 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007722 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007723 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007724 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7725 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007726 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
7727 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007728 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007729 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007730 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7731 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7732 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7733 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007734 }
junyulai96bd9fe2022-03-08 17:36:42 +08007735 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007736 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007737 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007738 }
7739 }
7740
fenglu3f357402015-03-20 11:29:56 -07007741 @Override
fenglub00f4882015-04-21 17:12:05 -07007742 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007743 enforceAccessPermission();
7744 NetworkAgentInfo nai = null;
7745 if (network == null) {
7746 return false;
7747 }
7748 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007749 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007750 }
7751 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007752 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007753 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007754 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007755 Integer uidReqs = mBandwidthRequests.get(uid);
7756 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007757 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007758 }
7759 mBandwidthRequests.put(uid, ++uidReqs);
7760 }
fenglu3f357402015-03-20 11:29:56 -07007761 return true;
7762 }
7763 return false;
7764 }
7765
Felipe Leme0a5ae422016-06-20 16:36:29 -07007766 private boolean isSystem(int uid) {
7767 return uid < Process.FIRST_APPLICATION_UID;
7768 }
fenglu3f357402015-03-20 11:29:56 -07007769
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007770 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007771 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007772 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007773 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007774 return;
7775 }
Hugo Benichi39621362017-02-11 17:04:43 +09007776 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7777 // Policy already enforced.
7778 return;
7779 }
paulhuaf50d7d2020-12-24 19:47:34 +08007780 final long ident = Binder.clearCallingIdentity();
7781 try {
7782 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7783 // If UID is restricted, don't allow them to bring up metered APNs.
7784 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7785 }
7786 } finally {
7787 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007788 }
7789 }
7790
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007791 @Override
7792 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007793 PendingIntent operation, @NonNull String callingPackageName,
7794 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007795 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007796 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007797 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007798 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007799 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007800 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007801 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007802 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007803 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007804 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7805 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007806
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007807 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007808 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007809 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7810 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007811 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007812 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7813 nri));
7814 return networkRequest;
7815 }
7816
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007817 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7818 mHandler.sendMessageDelayed(
7819 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007820 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007821 }
7822
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007823 @Override
7824 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007825 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007826 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007827 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007828 }
7829
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007830 // In order to implement the compatibility measure for pre-M apps that call
7831 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7832 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7833 // This ensures it has permission to do so.
7834 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7835 if (nc == null) {
7836 return false;
7837 }
7838 int[] transportTypes = nc.getTransportTypes();
7839 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7840 return false;
7841 }
7842 try {
7843 mContext.enforceCallingOrSelfPermission(
7844 android.Manifest.permission.ACCESS_WIFI_STATE,
7845 "ConnectivityService");
7846 } catch (SecurityException e) {
7847 return false;
7848 }
7849 return true;
7850 }
7851
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007852 @Override
7853 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007854 Messenger messenger, IBinder binder,
7855 @NetworkCallback.Flag int callbackFlags,
7856 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007857 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007858 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7859 enforceAccessPermission();
7860 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007861
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007862 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007863 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007864 Binder.getCallingPid(), callingUid, callingPackageName);
7865 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007866 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7867 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7868 // onLost and onAvailable callbacks when networks move in and out of the background.
7869 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7870 // can't request networks.
7871 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007872 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007873
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007874 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007875 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007876 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007877 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007878 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007879 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007880
7881 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7882 return networkRequest;
7883 }
7884
7885 @Override
7886 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007887 PendingIntent operation, @NonNull String callingPackageName,
7888 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007889 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007890 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007891 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7892 enforceAccessPermission();
7893 }
Chalard Jeandd421992021-12-16 23:16:02 +09007894 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007895 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007896 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007897 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007898 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007899
7900 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007901 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007902 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7903 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007904 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007905
WeiZhang1cc3f172021-06-03 19:02:04 -05007906 mHandler.sendMessage(mHandler.obtainMessage(
7907 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007908 }
7909
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007910 /** Returns the next Network provider ID. */
7911 public final int nextNetworkProviderId() {
7912 return mNextNetworkProviderId.getAndIncrement();
7913 }
7914
Erik Kline0c04b742016-07-07 16:50:58 +09007915 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007916 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007917 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007918 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007919 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007920 }
7921
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007922 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7923 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007924 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7925 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7926 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007927 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007928 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007929 return;
7930 }
7931
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007932 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7933 mNetworkProviderInfos.put(npi.messenger, npi);
7934 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007935 }
7936
7937 @Override
7938 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007939 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007940 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007941 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007942 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007943 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7944 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007945 }
7946
7947 @Override
7948 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007949 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007950 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007951 }
7952
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007953 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007954 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007955 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7956 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007957 Objects.requireNonNull(score);
7958 Objects.requireNonNull(caps);
7959 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007960 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007961 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007962 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7963 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007964 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7965 }
7966
Chalard Jeanbb902a52021-08-18 01:35:19 +09007967 private void updateOfferScore(final NetworkOffer offer) {
7968 final boolean yieldToBadWiFi =
7969 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7970 final NetworkOffer newOffer = new NetworkOffer(
7971 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7972 offer.caps, offer.callback, offer.providerId);
7973 if (offer.equals(newOffer)) return;
7974 handleRegisterNetworkOffer(newOffer);
7975 }
7976
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007977 @Override
7978 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007979 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007980 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7981 }
7982
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007983 private void handleUnregisterNetworkProvider(Messenger messenger) {
7984 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7985 if (npi == null) {
7986 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007987 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007988 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007989 // Unregister all the offers from this provider
7990 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7991 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007992 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007993 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7994 toRemove.add(noi);
7995 }
7996 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007997 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007998 handleUnregisterNetworkOffer(noi);
7999 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008000 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07008001 }
8002
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008003 @Override
James Mattisf7027322020-12-13 16:28:14 -08008004 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008005 if (request.hasTransport(TRANSPORT_TEST)) {
8006 enforceNetworkFactoryOrTestNetworksPermission();
8007 } else {
8008 enforceNetworkFactoryPermission();
8009 }
James Mattisf7027322020-12-13 16:28:14 -08008010 final NetworkRequestInfo nri = mNetworkRequests.get(request);
8011 if (nri != null) {
8012 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
8013 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
8014 mHandler.post(() -> handleReleaseNetworkRequest(
8015 nri.mRequests.get(0), mDeps.getCallingUid(), true));
8016 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008017 }
8018
Paul Jensen1f567382015-02-13 14:18:39 -05008019 // NOTE: Accessed on multiple threads, must be synchronized on itself.
8020 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008021 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05008022 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008023 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05008024 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008025 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008026
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008027 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05008028 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008029 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008030
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008031 // UID ranges for users that are currently blocked by VPNs.
8032 // This array is accessed and iterated on multiple threads without holding locks, so its
8033 // contents must never be mutated. When the ranges change, the array is replaced with a new one
8034 // (on the handler thread).
8035 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
8036
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008037 // Must only be accessed on the handler thread
8038 @NonNull
8039 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8040
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008041 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008042 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008043
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008044 // Current OEM network preferences. This object must only be written to on the handler thread.
8045 // Since it is immutable and always non-null, other threads may read it if they only care
8046 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008047 @NonNull
8048 private OemNetworkPreferences mOemNetworkPreferences =
8049 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008050 // Current per-profile network preferences. This object follows the same threading rules as
8051 // the OEM network preferences above.
8052 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008053 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8054 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008055
lucaslin3ba7cc22022-12-19 02:35:33 +00008056 // Current VPN network preferences. This object follows the same threading rules as the OEM
8057 // network preferences above.
8058 @NonNull
8059 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8060 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8061
paulhu51f77dc2021-06-07 02:34:20 +00008062 // A set of UIDs that should use mobile data preferentially if available. This object follows
8063 // the same threading rules as the OEM network preferences above.
8064 @NonNull
8065 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8066
James Mattiscb1e0362021-04-06 17:07:42 -07008067 // OemNetworkPreferences activity String log entries.
8068 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8069 @NonNull
8070 private final LocalLog mOemNetworkPreferencesLogs =
8071 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8072
James Mattis02220e22021-03-13 19:27:21 -08008073 /**
8074 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8075 * @param packageName the package name to check existence of a mapping for.
8076 * @return true if a mapping exists, false otherwise
8077 */
8078 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8079 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8080 }
8081
James Mattise3ef1912020-12-20 11:09:58 -08008082 // The always-on request for an Internet-capable network that apps without a specific default
8083 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008084 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008085 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008086 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008087 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008088 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008089 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008090 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008091
James Mattisd31bdfa2020-12-23 16:37:26 -08008092 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8093 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8094 }
8095
8096 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008097 * Return the default network request currently tracking the given uid.
8098 * @param uid the uid to check.
8099 * @return the NetworkRequestInfo tracking the given uid.
8100 */
8101 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008102 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008103 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008104 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008105 // Checking the first request is sufficient as only multilayer requests will have more
8106 // than one request and for multilayer, all requests will track the same uids.
8107 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008108 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008109 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008110 highestPriorityNri = nri;
8111 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008112 }
8113 }
paulhuaa0743d2021-05-26 21:56:03 +08008114 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008115 }
8116
8117 /**
8118 * Get a copy of the network requests of the default request that is currently tracking the
8119 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008120 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8121 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008122 * @param requestorUid the uid to check the default for.
8123 * @param requestorPackageName the requestor's package name.
8124 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8125 */
8126 @NonNull
8127 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008128 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008129 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008130 getDefaultRequestTrackingUid(asUid).mRequests,
8131 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008132 }
8133
8134 /**
8135 * Copy the given nri's NetworkRequest collection.
8136 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008137 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8138 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008139 * @param requestorUid the uid to set on the copied collection.
8140 * @param requestorPackageName the package name to set on the copied collection.
8141 * @return the copied NetworkRequest collection.
8142 */
8143 @NonNull
8144 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008145 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8146 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008147 final List<NetworkRequest> requests = new ArrayList<>();
8148 for (final NetworkRequest nr : requestsToCopy) {
8149 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008150 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008151 nr.legacyType, nextNetworkRequestId(), nr.type));
8152 }
8153 return requests;
8154 }
8155
8156 @NonNull
8157 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008158 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8159 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008160 // These capabilities are for a TRACK_DEFAULT callback, so:
8161 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8162 // mDefaultRequest and a per-UID default request.
8163 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008164 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008165 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008166 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8167 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008168 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008169 restrictRequestUidsForCallerAndSetRequestorInfo(
8170 netCap, requestorUid, requestorPackageName);
8171 return netCap;
8172 }
8173
8174 /**
8175 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8176 * @param nr the network request to check for equality against.
8177 * @return the nri if one exists, null otherwise.
8178 */
8179 @Nullable
8180 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8181 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8182 if (nri.getNetworkRequestForCallback().equals(nr)) {
8183 return nri;
8184 }
8185 }
8186 return null;
8187 }
8188
8189 /**
8190 * Check if an nri is currently being managed by per-app default networking.
8191 * @param nri the nri to check.
8192 * @return true if this nri is currently being managed by per-app default networking.
8193 */
8194 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8195 // nri.mRequests.get(0) is only different from the original request filed in
8196 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8197 // functionality therefore if these two don't match, it means this particular nri is
8198 // currently being managed by a per-app default.
8199 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8200 }
8201
8202 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008203 * Determine if an nri is a managed default request that disallows default networking.
8204 * @param nri the request to evaluate
8205 * @return true if device-default networking is disallowed
8206 */
8207 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8208 // Check if this nri is a managed default that supports the default network at its
8209 // lowest priority request.
8210 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8211 final NetworkCapabilities lowestPriorityNetCap =
8212 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8213 return isPerAppDefaultRequest(nri)
8214 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8215 lowestPriorityNetCap));
8216 }
8217
Erik Kline05f2b402015-04-30 12:58:40 +09008218 // Request used to optionally keep mobile data active even when higher
8219 // priority networks like Wi-Fi are active.
8220 private final NetworkRequest mDefaultMobileDataRequest;
8221
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008222 // Request used to optionally keep wifi data active even when higher
8223 // priority networks like ethernet are active.
8224 private final NetworkRequest mDefaultWifiRequest;
8225
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008226 // Request used to optionally keep vehicle internal network always active
8227 private final NetworkRequest mDefaultVehicleRequest;
8228
James Mattisd31bdfa2020-12-23 16:37:26 -08008229 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8230 // network with no service. This NAI should never be matched against, nor should any public API
8231 // ever return the associated network. For this reason, this NAI is not in the list of available
8232 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8233 // default requests that don't support using the device default network which will ultimately
8234 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8235 @VisibleForTesting
8236 final NetworkAgentInfo mNoServiceNetwork;
8237
Chalard Jean5b409c72021-02-04 13:12:59 +09008238 // The NetworkAgentInfo currently satisfying the default request, if any.
8239 private NetworkAgentInfo getDefaultNetwork() {
8240 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008241 }
8242
James Mattis2516da32021-01-31 17:06:19 -08008243 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008244 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008245 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8246 // Currently, all network requests will have the same uids therefore checking the first
8247 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008248 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008249 if (null == uids) {
8250 continue;
8251 }
8252 for (final UidRange range : uids) {
8253 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008254 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008255 highestPriorityNri = nri;
8256 }
James Mattis2516da32021-01-31 17:06:19 -08008257 }
8258 }
8259 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008260 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008261 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008262 }
8263
Varun Ananddf569952019-02-06 10:13:38 -08008264 @Nullable
8265 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8266 return nai != null ? nai.network : null;
8267 }
8268
8269 private void ensureRunningOnConnectivityServiceThread() {
8270 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8271 throw new IllegalStateException(
8272 "Not running on ConnectivityService thread: "
8273 + Thread.currentThread().getName());
8274 }
8275 }
8276
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008277 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008278 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8279 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008280 }
8281
Chalard Jean29d06db2018-05-02 21:14:54 +09008282 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008283 * Returns whether local agents are supported on this device.
8284 *
8285 * Local agents are supported from U on TVs, and from V on all devices.
8286 */
8287 @VisibleForTesting
8288 public boolean areLocalAgentsSupported() {
8289 final PackageManager pm = mContext.getPackageManager();
8290 // Local agents are supported starting on U on TVs and on V on everything else.
8291 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8292 }
8293
8294 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008295 * Register a new agent with ConnectivityService to handle a network.
8296 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008297 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008298 * @param networkInfo the initial info associated with this network. It can be updated later :
8299 * see {@link #updateNetworkInfo}.
8300 * @param linkProperties the initial link properties of this network. They can be updated
8301 * later : see {@link #updateLinkProperties}.
8302 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008303 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008304 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008305 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008306 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008307 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008308 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008309 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008310 public Network registerNetworkAgent(INetworkAgent na,
8311 NetworkInfo networkInfo,
8312 LinkProperties linkProperties,
8313 NetworkCapabilities networkCapabilities,
8314 @NonNull NetworkScore initialScore,
8315 @Nullable LocalNetworkConfig localNetworkConfig,
8316 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008317 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008318 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8319 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8320 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008321 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008322 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008323 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008324 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008325 } else {
8326 enforceNetworkFactoryPermission();
8327 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008328 final boolean hasLocalCap =
8329 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8330 if (hasLocalCap && !areLocalAgentsSupported()) {
8331 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8332 throw new IllegalArgumentException("Local agents are not supported in this version");
8333 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008334 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8335 if (hasLocalCap != hasLocalNetworkConfig) {
8336 throw new IllegalArgumentException(null != localNetworkConfig
8337 ? "Only local network agents can have a LocalNetworkConfig"
8338 : "Local network agents must have a LocalNetworkConfig"
8339 );
8340 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008341
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008342 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008343 final long token = Binder.clearCallingIdentity();
8344 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008345 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008346 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8347 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008348 } finally {
8349 Binder.restoreCallingIdentity(token);
8350 }
8351 }
8352
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008353 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008354 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008355 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8356 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008357 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008358
Chalard Jeandbc46952022-02-02 00:14:18 +09008359 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8360 // and mutate them at any time.
8361 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8362 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8363 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008364 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008365
Chalard Jean366c5252022-01-25 18:27:53 +09008366 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008367 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008368 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8369 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008370 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008371 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008372 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8373 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8374 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008375
Chalard Jeandbc46952022-02-02 00:14:18 +09008376 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008377 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008378 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008379 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008380 mDeps.getNetworkStack().makeNetworkMonitor(
8381 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008382 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8383 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008384 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008385 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008386 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008387 }
8388
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008389 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008390 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008391 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008392 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008393 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008394 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8395 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8396 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008397
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008398 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008399
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008400 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008401 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008402 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008403 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008404
8405 try {
8406 networkMonitor.start();
8407 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008408 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008409 }
Chalard Jean366c5252022-01-25 18:27:53 +09008410
Chalard Jean1e4c2182023-10-06 18:45:53 +09008411 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008412 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008413 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008414 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008415 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008416 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008417 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008418 }
8419
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008420 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8421 @NonNull public final NetworkOffer offer;
8422
8423 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8424 this.offer = offer;
8425 }
8426
8427 @Override
8428 public void binderDied() {
8429 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8430 }
8431 }
8432
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008433 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8434 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8435 if (npi.providerId == providerId) return true;
8436 }
8437 return false;
8438 }
8439
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008440 /**
8441 * Register or update a network offer.
8442 * @param newOffer The new offer. If the callback member is the same as an existing
8443 * offer, it is an update of that offer.
8444 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008445 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008446 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8447 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008448 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008449 // This may actually happen if a provider updates its score or registers and then
8450 // immediately unregisters. The offer would still be in the handler queue, but the
8451 // provider would have been removed.
8452 if (DBG) log("Received offer from an unregistered provider");
8453 return;
8454 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008455 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8456 if (null != existingOffer) {
8457 handleUnregisterNetworkOffer(existingOffer);
8458 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008459 if (DBG) {
8460 // handleUnregisterNetworkOffer has already logged the old offer
8461 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8462 }
8463 } else {
8464 if (DBG) {
8465 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8466 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008467 }
8468 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8469 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008470 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008471 } catch (RemoteException e) {
8472 noi.binderDied();
8473 return;
8474 }
8475 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008476 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008477 }
8478
8479 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8480 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008481 if (DBG) {
8482 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8483 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008484
8485 // If the provider removes the offer and dies immediately afterwards this
8486 // function may be called twice in a row, but the array will no longer contain
8487 // the offer.
8488 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008489 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008490 }
8491
8492 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8493 @NonNull final INetworkOfferCallback callback) {
8494 ensureRunningOnConnectivityServiceThread();
8495 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008496 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008497 }
8498 return null;
8499 }
8500
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008501 /**
8502 * Called when receiving LinkProperties directly from a NetworkAgent.
8503 * Stores into |nai| any data coming from the agent that might also be written to the network's
8504 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8505 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008506 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008507 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008508 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8509 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008510 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008511 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008512 }
8513
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008514 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008515 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008516 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008517
Lorenzo Colittid523d142020-04-01 20:16:30 +09008518 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8519 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8520 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008521 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008522
Suprabh Shukla1e312032023-01-24 03:36:37 -08008523 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008524
8525 // update filtering rules, need to happen after the interface update so netd knows about the
8526 // new interface (the interface name -> index map becomes initialized)
8527 updateVpnFiltering(newLp, oldLp, networkAgent);
8528
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008529 updateMtu(newLp, oldLp);
8530 // TODO - figure out what to do for clat
8531// for (LinkProperties lp : newLp.getStackedLinks()) {
8532// updateMtu(lp, null);
8533// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008534 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008535 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008536 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8537 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008538
Erik Klineb9888902016-04-05 13:30:49 +09008539 updateRoutes(newLp, oldLp, netId);
8540 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008541 // Make sure LinkProperties represents the latest private DNS status.
8542 // This does not need to be done before updateDnses because the
8543 // LinkProperties are not the source of the private DNS configuration.
8544 // updateDnses will fetch the private DNS configuration from DnsManager.
8545 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008546
Chalard Jean5b409c72021-02-04 13:12:59 +09008547 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008548 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008549 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008550 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008551 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008552
8553 updateWakeOnLan(newLp);
8554
Hai Shalome58bdc62021-01-11 18:45:34 -08008555 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8556 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8557 // does, it needs to be merged here.
8558 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8559 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008560
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008561 // TODO - move this check to cover the whole function
8562 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008563 synchronized (networkAgent) {
8564 networkAgent.linkProperties = newLp;
8565 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008566 // Start or stop DNS64 detection and 464xlat according to network state.
8567 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008568 // Notify NSS when relevant events happened. Currently, NSS only cares about
8569 // interface changed to update clat interfaces accounting.
8570 final boolean interfacesChanged = oldLp == null
8571 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8572 if (interfacesChanged) {
8573 notifyIfacesChangedForNetworkStats();
8574 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008575 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8576 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008577 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008578 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008579
8580 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008581 }
8582
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008583 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8584 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8585 }
8586
Hai Shalome58bdc62021-01-11 18:45:34 -08008587 /**
8588 * @param naData captive portal data from NetworkAgent
8589 * @param apiData captive portal data from capport API
8590 */
8591 @Nullable
8592 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8593 CaptivePortalData apiData) {
8594 if (naData == null || apiData == null) {
8595 return naData == null ? apiData : naData;
8596 }
8597 final CaptivePortalData.Builder captivePortalBuilder =
8598 new CaptivePortalData.Builder(naData);
8599
8600 if (apiData.isCaptive()) {
8601 captivePortalBuilder.setCaptive(true);
8602 }
8603 if (apiData.isSessionExtendable()) {
8604 captivePortalBuilder.setSessionExtendable(true);
8605 }
8606 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8607 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8608 // otherwise data would be inconsistent. Prefer the capport API info if present,
8609 // as it can generally be refreshed more often.
8610 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8611 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8612 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8613 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8614 // No source has time / bytes remaining information: surface the newest refresh time
8615 // for other fields
8616 captivePortalBuilder.setRefreshTime(
8617 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8618 }
8619
Hai Shalom7c6ab402021-02-04 19:34:06 -08008620 // Prioritize the user portal URL from the network agent if the source is authenticated.
8621 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8622 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8623 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8624 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008625 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008626 // Prioritize the venue information URL from the network agent if the source is
8627 // authenticated.
8628 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8629 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8630 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8631 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008632 }
8633 return captivePortalBuilder.build();
8634 }
8635
Suprabh Shukla53e16392023-04-26 18:47:36 -07008636 @VisibleForTesting
8637 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008638 // This needs to be kept in sync and backwards compatible with the decoding logic in
8639 // NetdEventListenerService, which is non-mainline code.
8640 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8641 }
8642
Suprabh Shukla75642282023-04-25 23:15:43 -07008643 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8644 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8645 return true;
8646 }
8647 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8648 return true;
8649 }
8650 return false;
8651 }
8652
Suprabh Shukla1e312032023-01-24 03:36:37 -08008653 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008654 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008655 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008656 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008657 return;
8658 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008659
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008660 // Mask/mark of zero will not detect anything interesting.
8661 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008662 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008663 return;
8664 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008665
Suprabh Shukla1e312032023-01-24 03:36:37 -08008666 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008667 try {
8668 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008669 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008670 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008671 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008672 }
8673 } catch (Exception e) {
8674 loge("Exception modifying wakeup packet monitoring: " + e);
8675 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008676 }
8677
Junyu Lai970963e2022-10-25 15:46:47 +08008678 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008679 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008680 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008681 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008682 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008683 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008684 for (final String iface : interfaceDiff.added) {
8685 try {
8686 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008687 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008688 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008689 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008690 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008691 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008692 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008693 }
Paul Jensenbff73492014-04-28 10:33:11 -04008694 }
8695 }
Chalard Jean9589e722019-11-19 19:03:53 +09008696 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008697 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008698 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008699 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008700 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008701 } catch (Exception e) {
8702 loge("Exception removing interface: " + e);
8703 }
8704 }
8705 }
8706
Paul Jensene0fd4a82014-08-06 15:51:33 -04008707 /**
8708 * Have netd update routes from oldLp to newLp.
8709 * @return true if routes changed between oldLp and newLp
8710 */
Junyu Lai970963e2022-10-25 15:46:47 +08008711 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8712 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008713 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008714 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8715 new CompareOrUpdateResult<>(
8716 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008717 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008718 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008719
8720 // add routes before removing old in case it helps with continuous connectivity
8721
Chalard Jean9dd11612018-06-04 16:52:49 +09008722 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008723 for (RouteInfo route : routeDiff.added) {
8724 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008725 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008726 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008727 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008728 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008729 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008730 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008731 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008732 }
8733 }
8734 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008735 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008736 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008737 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008738 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008739 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008740 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008741 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008742 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008743 }
8744 }
8745
8746 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008747 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008748 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008749 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008750 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008751 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008752 }
8753 }
Tyler Weare4314862019-12-05 14:55:30 -08008754
8755 for (RouteInfo route : routeDiff.updated) {
8756 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8757 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008758 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008759 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008760 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008761 }
8762 }
8763 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8764 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008765 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008766
Junyu Lai970963e2022-10-25 15:46:47 +08008767 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8768 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008769 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8770 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008771 }
Erik Klineb9888902016-04-05 13:30:49 +09008772
Erik Kline31b4a9e2018-01-11 21:07:29 +09008773 if (DBG) {
8774 final Collection<InetAddress> dnses = newLp.getDnsServers();
8775 log("Setting DNS servers for network " + netId + " to " + dnses);
8776 }
Erik Klineb9888902016-04-05 13:30:49 +09008777 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008778 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008779 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008780 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008781 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008782 }
Erik Kline54e35c02017-04-07 15:29:29 +09008783 }
8784
Junyu Lai970963e2022-10-25 15:46:47 +08008785 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8786 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008787 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8788 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008789 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8790 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008791
8792 if (!wasFiltering && !needsFiltering) {
8793 // Nothing to do.
8794 return;
8795 }
8796
8797 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8798 // Nothing changed.
8799 return;
8800 }
8801
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008802 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008803 if (ranges == null || ranges.isEmpty()) {
8804 return;
8805 }
8806
Qingxi Libb8da982020-01-17 17:54:27 -08008807 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008808 // TODO: this create a window of opportunity for apps to receive traffic between the time
8809 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008810 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008811 // old rules are being removed.
8812 if (wasFiltering) {
8813 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8814 }
8815 if (needsFiltering) {
8816 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8817 }
8818 }
8819
Valentin Iftime9fa35092019-09-24 13:32:13 +02008820 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008821 if (mWolSupportedInterfaces == null) {
8822 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008823 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008824 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008825 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8826 }
8827
Luke Huangb913c812018-08-24 20:33:16 +08008828 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008829 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008830 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008831 }
8832 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008833 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008834 }
Luke Huangb913c812018-08-24 20:33:16 +08008835 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008836 }
8837
Chalard Jean62edfd82019-12-02 18:39:29 +09008838 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8839 @NonNull final NetworkCapabilities newNc) {
8840 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8841 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008842 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008843 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008844 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008845 } catch (RemoteException | ServiceSpecificException e) {
8846 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008847 }
8848 }
8849 }
8850
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008851 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008852 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008853 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008854 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008855 underlyingNetworks = underlyingNetworksOrDefault(
8856 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008857 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008858 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8859 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008860 // metered if any underlying is metered, or originally declared metered by the agent.
8861 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008862 boolean roaming = false; // roaming if any underlying is roaming
8863 boolean congested = false; // congested if any underlying is congested
8864 boolean suspended = true; // suspended if all underlying are suspended
8865
8866 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008867 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008868 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008869 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008870 for (Network underlyingNetwork : underlyingNetworks) {
8871 final NetworkAgentInfo underlying =
8872 getNetworkAgentInfoForNetwork(underlyingNetwork);
8873 if (underlying == null) continue;
8874
8875 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8876 hadUnderlyingNetworks = true;
8877 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008878 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008879 }
8880
8881 // Merge capabilities of this underlying network. For bandwidth, assume the
8882 // worst case.
8883 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8884 underlyingCaps.getLinkDownstreamBandwidthKbps());
8885 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8886 underlyingCaps.getLinkUpstreamBandwidthKbps());
8887 // If this underlying network is metered, the VPN is metered (it may cost money
8888 // to send packets on this network).
8889 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8890 // If this underlying network is roaming, the VPN is roaming (the billing structure
8891 // is different than the usual, local one).
8892 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8893 // If this underlying network is congested, the VPN is congested (the current
8894 // condition of the network affects the performance of this network).
8895 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8896 // If this network is not suspended, the VPN is not suspended (the VPN
8897 // is able to transfer some data).
8898 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008899 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008900 }
8901 }
8902 if (!hadUnderlyingNetworks) {
8903 // No idea what the underlying networks are; assume reasonable defaults
8904 metered = true;
8905 roaming = false;
8906 congested = false;
8907 suspended = false;
8908 }
8909
Chalard Jean1d420b32022-10-12 16:39:37 +09008910 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008911 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8912 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8913 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8914 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8915 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8916 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008917 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008918 }
8919
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008920 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008921 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8922 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8923 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008924 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008925 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008926 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008927 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008928 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8929 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008930 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008931 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008932 if (nai.everConnected()
8933 && !nai.isVPN()
8934 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008935 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008936 // does not cause any request (that is not a listen) currently matching that agent to
8937 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008938 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008939 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008940 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008941 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008942 }
8943
Paul Jensen53f08952015-06-16 14:27:36 -04008944 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008945 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008946 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008947 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008948 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008949 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008950 }
Chalard Jean254bd162022-08-25 13:04:51 +09008951 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008952 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008953 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008954 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008955 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008956 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008957 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008958 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008959 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008960 }
Chalard Jean254bd162022-08-25 13:04:51 +09008961 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008962 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8963 } else {
8964 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8965 }
lucasline117e2e2019-10-22 18:27:33 +08008966 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008967
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008968 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008969 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8970 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008971 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008972 }
8973
Lorenzo Colittibd079452021-07-02 11:47:57 +09008974 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008975 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008976 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008977 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008978 }
8979
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008980 return newNc;
8981 }
8982
Lorenzo Colitti44840702021-01-11 22:27:57 +09008983 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8984 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8985 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8986 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8987 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8988 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8989 if (prevSuspended != suspended) {
8990 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8991 // onResumed have been removed.
8992 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8993 : ConnectivityManager.CALLBACK_RESUMED);
8994 }
8995 if (prevSuspended != suspended || prevRoaming != roaming) {
8996 // updateNetworkInfo will mix in the suspended info from the capabilities and
8997 // take appropriate action for the network having possibly changed state.
8998 updateNetworkInfo(nai, nai.networkInfo);
8999 }
9000 }
9001
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009002 /**
9003 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
9004 *
9005 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
9006 * capabilities we manage and store in {@code nai}, such as validated status and captive
9007 * portal status)
9008 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
9009 * potentially triggers rematches.
9010 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
9011 * change.)
9012 *
9013 * @param oldScore score of the network before any of the changes that prompted us
9014 * to call this function.
9015 * @param nai the network having its capabilities updated.
9016 * @param nc the new network capabilities.
9017 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009018 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09009019 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009020 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009021 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09009022 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
9023 if (null != differences) {
9024 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
9025 }
Chalard Jean62edfd82019-12-02 18:39:29 +09009026 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09009027 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009028
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009029 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09009030 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09009031 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009032
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009033 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009034 // If the requestable capabilities haven't changed, and the score hasn't changed, then
9035 // the change we're processing can't affect any requests, it can only affect the listens
9036 // on this network. We might have been called by rematchNetworkAndRequests when a
9037 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09009038 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009039 } else {
9040 // If the requestable capabilities have changed or the score changed, we can't have been
9041 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009042 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009043 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009044 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009045 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009046
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009047 final boolean oldMetered = prevNc.isMetered();
9048 final boolean newMetered = newNc.isMetered();
9049 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009050
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009051 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009052 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9053 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009054 }
junyulaif2c67e42018-08-07 19:50:45 +08009055
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009056 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9057 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009058
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009059 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009060 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009061 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009062 }
9063
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009064 // This network might have been underlying another network. Propagate its capabilities.
9065 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009066
Ken Chen5a35cf92023-10-07 07:54:22 +08009067 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009068 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009069 }
lucaslin53e8a262021-06-08 01:43:59 +08009070
9071 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009072 }
9073
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009074 /** Convenience method to update the capabilities for a given network. */
9075 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009076 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009077 }
9078
Chalard Jean1e4c2182023-10-06 18:45:53 +09009079 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009080 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009081 @Nullable final LocalNetworkConfig oldConfig,
9082 @NonNull final LocalNetworkConfig newConfig) {
9083 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009084 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9085 return;
9086 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009087
Chalard Jean4fe23392023-10-17 23:02:27 +09009088 if (VDBG) {
9089 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9090 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009091 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
9092 // TODO : apply the diff for multicast routing.
9093 configBuilder.setUpstreamMulticastRoutingConfig(
9094 newConfig.getUpstreamMulticastRoutingConfig());
9095 configBuilder.setDownstreamMulticastRoutingConfig(
9096 newConfig.getDownstreamMulticastRoutingConfig());
9097
9098 final NetworkRequest oldRequest =
9099 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9100 final NetworkCapabilities oldCaps =
9101 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9102 final NetworkRequestInfo oldNri =
9103 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9104 final NetworkAgentInfo oldSatisfier =
9105 null == oldNri ? null : oldNri.getSatisfier();
9106 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9107 final NetworkCapabilities newCaps =
9108 (null == newRequest) ? null : newRequest.networkCapabilities;
9109 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9110 if (null != oldRequest && requestUpdated) {
9111 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9112 if (null == newRequest && null != oldSatisfier) {
9113 // If there is an old satisfier, but no new request, then remove the old upstream.
9114 removeLocalNetworkUpstream(nai, oldSatisfier);
9115 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009116 // When there is a new request, the rematch sees the new request and sends the
9117 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9118 // But here there is no new request, so the rematch won't see anything. Send
9119 // callbacks to apps now to tell them about the loss of upstream.
9120 notifyNetworkCallbacks(nai,
9121 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009122 return;
9123 }
9124 }
9125 if (null != newRequest && requestUpdated) {
9126 // File the new request if :
9127 // - it has changed (requestUpdated), or
9128 // - it's the first time this local info (null == oldConfig)
9129 // is updated and the request has not been filed yet.
9130 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9131 // upstream (the best) but never request it to be brought up.
9132 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9133 nextNetworkRequestId(), LISTEN_FOR_BEST);
9134 configBuilder.setUpstreamSelector(nr);
9135 final NetworkRequestInfo nri = new NetworkRequestInfo(
9136 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9137 0 /* callbackFlags */, null /* attributionTag */);
9138 if (null != oldSatisfier) {
9139 // Set the old satisfier in the new NRI so that the rematch will see any changes
9140 nri.setSatisfier(oldSatisfier, nr);
9141 }
9142 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009143 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9144 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9145 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009146 handleRegisterNetworkRequest(nri);
9147 } else {
9148 configBuilder.setUpstreamSelector(oldRequest);
9149 nai.localNetworkConfig = configBuilder.build();
9150 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009151 }
9152
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009153 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009154 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009155 *
9156 * Ingress interface filtering enforces that all apps under the given network can only receive
9157 * packets from the network's interface (and loopback). This is important for VPNs because
9158 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9159 * non-VPN interfaces.
9160 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009161 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009162 * 1. the network is an app VPN (not legacy VPN)
9163 * 2. the VPN does not allow bypass
9164 * 3. the VPN is fully-routed
9165 * 4. the VPN interface is non-null
9166 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009167 * @see INetd#firewallAddUidInterfaceRules
9168 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009169 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009170 @Nullable
9171 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009172 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009173 if (nc == null || lp == null) return null;
9174 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009175 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009176 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009177 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009178 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009179 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009180 && !lp.hasExcludeRoute()) {
9181 return lp.getInterfaceName();
9182 }
9183 return null;
9184 }
9185
9186 /**
9187 * Returns whether we need to set interface filtering rule or not
9188 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009189 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009190 String isolationIface) {
9191 // Allow rules are always needed if VPN isolation is enabled.
9192 if (isolationIface != null) return true;
9193
9194 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9195 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9196 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009197 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009198 }
9199
Chiachang Wang28afaff2020-12-10 22:24:47 +08009200 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9201 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9202 int index = 0;
9203 for (UidRange range : ranges) {
9204 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9205 index++;
9206 }
9207 return stableRanges;
9208 }
9209
Chalard Jeane6c95272022-01-25 21:04:21 +09009210 private static UidRangeParcel[] intsToUidRangeStableParcels(
9211 final @NonNull ArraySet<Integer> uids) {
9212 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9213 int index = 0;
9214 for (int uid : uids) {
9215 stableRanges[index] = new UidRangeParcel(uid, uid);
9216 index++;
9217 }
9218 return stableRanges;
9219 }
9220
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009221 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9222 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9223 for (int i = 0; i < ranges.length; i++) {
9224 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9225 }
9226 return stableRanges;
9227 }
9228
Motomu Utsumi93a22182023-03-16 17:04:21 +09009229 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009230 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009231 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9232 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009233 if (mDeps.isAtLeastU()) {
9234 final Set<Integer> exemptUidSet = new ArraySet<>();
9235 for (final int uid: exemptUids) {
9236 exemptUidSet.add(uid);
9237 }
9238 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9239 } else {
9240 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9241 }
Ken Chen5e65a852020-12-24 12:59:10 +08009242 } catch (Exception e) {
9243 loge("Exception in socket destroy: ", e);
9244 }
9245 }
9246 }
9247
paulhuaa0743d2021-05-26 21:56:03 +08009248 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009249 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009250 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9251 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9252 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009253 exemptUids[0] = VPN_UID;
9254 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009255 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9256
Motomu Utsumi6345e462023-03-13 13:24:50 +09009257 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009258 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009259 try {
9260 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009261 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009262 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009263 } else {
paulhu0e79d952021-06-09 16:11:35 +08009264 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009265 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009266 }
9267 } catch (Exception e) {
9268 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9269 " on netId " + nai.network.netId + ". " + e);
9270 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009271 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009272 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009273 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009274
lucaslin53e8a262021-06-08 01:43:59 +08009275 private boolean isProxySetOnAnyDefaultNetwork() {
9276 ensureRunningOnConnectivityServiceThread();
9277 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9278 final NetworkAgentInfo nai = nri.getSatisfier();
9279 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9280 return true;
9281 }
9282 }
9283 return false;
9284 }
9285
9286 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9287 NetworkCapabilities newNc) {
9288 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9289 // the proxy might be changed since the default network satisfied by the apps might also
9290 // changed.
9291 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9292 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009293 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9294 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009295 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009296 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9297 mProxyTracker.sendProxyBroadcast();
9298 }
9299 }
9300
Chalard Jeane6c95272022-01-25 21:04:21 +09009301 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9302 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009303 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9304 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009305 if (null == prevRanges) prevRanges = new ArraySet<>();
9306 if (null == newRanges) newRanges = new ArraySet<>();
9307 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9308
9309 prevRanges.removeAll(newRanges);
9310 newRanges.removeAll(prevRangesCopy);
9311
9312 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009313 // When updating the VPN uid routing rules, add the new range first then remove the old
9314 // range. If old range were removed first, there would be a window between the old
9315 // range being removed and the new range being added, during which UIDs contained
9316 // in both ranges are not subject to any VPN routing rules. Adding new range before
9317 // removing old range works because, unlike the filtering rules below, it's possible to
9318 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009319 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9320 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9321 // [1-5] & [1-2],[4-5] == [3]
9322 // Then we can do:
9323 // maybeCloseSockets([3])
9324 // mNetd.networkAddUidRanges([1-2],[4-5])
9325 // mNetd.networkRemoveUidRanges([1-5])
9326 // maybeCloseSockets([3])
9327 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9328 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009329 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009330 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009331 }
9332 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009333 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009334 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009335 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9336 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009337 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9338 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009339 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009340 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009341 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9342 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9343 // were added first and then newRanges got removed later, there would be only one uid
9344 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9345 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9346 // Note that this is in contrast with the (more robust) update of VPN routing rules
9347 // above, where the addition of new ranges happens before the removal of old ranges.
9348 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9349 // to be removed will never overlap with the new range to be added.
9350 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009351 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9352 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009353 }
9354 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009355 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009356 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009357 } catch (Exception e) {
9358 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009359 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009360 }
9361 }
9362
Chalard Jeande665262022-02-25 16:12:12 +09009363 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009364 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9365 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009366 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9367 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009368 if (prevEmpty && newEmpty) return;
9369
9370 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009371 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009372 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009373 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009374
9375 if (prevUids.equals(newUids)) return;
9376
9377 // This implementation is very simple and vastly faster for sets of Integers than
9378 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9379 // a key computed from the value and has storage for that.
9380 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9381 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9382 toRemove.removeAll(newUids);
9383 toAdd.removeAll(prevUids);
9384
9385 try {
9386 if (!toAdd.isEmpty()) {
9387 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9388 nai.network.netId,
9389 intsToUidRangeStableParcels(toAdd),
9390 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9391 }
9392 if (!toRemove.isEmpty()) {
9393 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9394 nai.network.netId,
9395 intsToUidRangeStableParcels(toRemove),
9396 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9397 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009398 } catch (ServiceSpecificException e) {
9399 // Has the interface disappeared since the network was built ?
9400 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009401 } catch (RemoteException e) {
9402 // Netd died. This usually causes a runtime restart anyway.
9403 }
9404 }
9405
Junyu Lai2ed7d412022-10-07 16:52:21 +08009406 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9407 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009408 ensureRunningOnConnectivityServiceThread();
9409
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009410 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009411 // Ignore updates for disconnected networks
9412 return;
9413 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009414 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009415 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009416 + "; created=" + nai.getCreatedTime()
9417 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009418 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009419 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9420 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009421 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009422 }
9423
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009424 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9425 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009426 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009427 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009428 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009429 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9430 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9431 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009432 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9433 // need to be sent as a separate extra.
9434 final NetworkRequest req = nri.isMultilayerRequest()
9435 ? nri.getActiveRequest()
9436 // Non-multilayer listen requests do not have an active request
9437 : nri.mRequests.get(0);
9438 if (req == null) {
9439 Log.wtf(TAG, "No request in NRI " + nri);
9440 }
9441 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009442 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009443 sendIntent(nri.mPendingIntent, intent);
9444 }
9445 // else not handled
9446 }
9447
Michael Groover73f69482023-01-27 11:01:25 -06009448 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9449 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009450 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9451 mPendingIntentWakeLock.acquire();
9452 try {
9453 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009454 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009455 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009456 // Explicitly disallow the receiver from starting activities, to prevent apps from
9457 // utilizing the PendingIntent as a backdoor to do this.
9458 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9459 }
9460 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9461 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009462 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009463 } catch (PendingIntent.CanceledException e) {
9464 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9465 mPendingIntentWakeLock.release();
9466 releasePendingNetworkRequest(pendingIntent);
9467 }
9468 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9469 }
9470
9471 @Override
9472 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9473 String resultData, Bundle resultExtras) {
9474 if (DBG) log("Finished sending " + pendingIntent);
9475 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009476 // Release with a delay so the receiving client has an opportunity to put in its
9477 // own request.
9478 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009479 }
9480
Chalard Jean22350c92023-10-07 19:21:45 +09009481 @Nullable
9482 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9483 if (!nai.isLocalNetwork()) return null;
9484 final Network upstream;
9485 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9486 if (null == selector) {
9487 upstream = null;
9488 } else {
9489 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9490 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9491 upstream = (null == satisfier) ? null : satisfier.network;
9492 }
9493 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9494 }
9495
Chalard Jean46bfbf02022-02-02 00:56:25 +09009496 // networkAgent is only allowed to be null if notificationType is
9497 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9498 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009499 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009500 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009501 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009502 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009503 // Default request has no msgr. Also prevents callbacks from being invoked for
9504 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9505 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9506 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009507 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009508 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009509 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009510 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009511 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009512 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009513 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009514 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9515 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009516 }
Roshan Pius951c0032020-12-22 15:10:42 -08009517 final boolean includeLocationSensitiveInfo =
9518 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009519 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009520 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009521 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009522 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009523 networkCapabilitiesRestrictedForCallerPermissions(
9524 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9525 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009526 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009527 nri.mCallingAttributionTag);
9528 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009529 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9530 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009531 // The local network info is often null, so can't use the static putParcelable
9532 // method here.
9533 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9534 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009535 // For this notification, arg1 contains the blocked status.
9536 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009537 break;
9538 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009539 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009540 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009541 break;
9542 }
9543 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009544 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009545 final NetworkCapabilities netCap =
9546 networkCapabilitiesRestrictedForCallerPermissions(
9547 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9548 putParcelable(
9549 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009550 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009551 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009552 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009553 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009554 break;
9555 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009556 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009557 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9558 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009559 break;
9560 }
junyulaif2c67e42018-08-07 19:50:45 +08009561 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009562 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009563 msg.arg1 = arg1;
9564 break;
9565 }
Chalard Jean22350c92023-10-07 19:21:45 +09009566 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9567 if (!networkAgent.isLocalNetwork()) {
9568 Log.wtf(TAG, "Callback for local info for a non-local network");
9569 return;
9570 }
9571 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9572 break;
9573 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009574 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009575 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009576 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009577 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009578 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009579 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009580 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009581 }
James Mattis45d81842021-01-10 14:24:24 -08009582 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009583 } catch (RemoteException e) {
9584 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009585 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009586 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009587 }
9588
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009589 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9590 bundle.putParcelable(t.getClass().getSimpleName(), t);
9591 }
9592
Chalard Jean0702f982021-09-16 21:50:07 +09009593 /**
9594 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9595 *
9596 * When a request should be assigned to a new network, it is normally lingered to give
9597 * time for apps to gracefully migrate their connections. When both networks are on the same
9598 * radio, but that radio can't do time-sharing efficiently, this may end up being
9599 * counter-productive because any traffic on the old network may drastically reduce the
9600 * performance of the new network.
9601 * The stack supports a configuration to let modem vendors state that their radio can't
9602 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9603 * from one cell network to another can't be done gracefully.
9604 *
9605 * @param oldNai the old network serving the request
9606 * @param newNai the new network serving the request
9607 * @return whether the switch can be graceful
9608 */
9609 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9610 @NonNull final NetworkAgentInfo newSatisfier) {
9611 if (mCellularRadioTimesharingCapable) return true;
9612 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9613 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9614 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9615 }
9616
Paul Jensenaf94b982014-09-30 15:37:41 -04009617 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009618 if (nai.numRequestNetworkRequests() != 0) {
9619 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9620 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009621 // Ignore listening and track default requests.
9622 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009623 loge("Dead network still had at least " + nr);
9624 break;
9625 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009626 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009627 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009628 }
9629
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009630 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9631 if (oldNetwork == null) {
9632 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9633 return;
9634 }
Chalard Jean49707572019-12-10 21:07:02 +09009635 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009636
9637 // If we get here it means that the last linger timeout for this network expired. So there
9638 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009639 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009640
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009641 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009642 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009643 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009644 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009645 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009646 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009647 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009648 }
9649
James Mattise3ef1912020-12-20 11:09:58 -08009650 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9651 boolean isDefaultChanged = false;
9652 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9653 final NetworkReassignment.RequestReassignment reassignment =
9654 changes.getReassignment(defaultRequestInfo);
9655 if (null == reassignment) {
9656 continue;
9657 }
9658 // reassignment only contains those instances where the satisfying network changed.
9659 isDefaultChanged = true;
9660 // Notify system services of the new default.
9661 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9662 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009663
James Mattise3ef1912020-12-20 11:09:58 -08009664 if (isDefaultChanged) {
9665 // Hold a wakelock for a short time to help apps in migrating to a new default.
9666 scheduleReleaseNetworkTransitionWakelock();
9667 }
9668 }
9669
Aaron Huang9fe47be2021-06-08 13:11:45 +08009670 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9671 if (null == oldDefaultNetwork) return;
9672 // The network stopped being the default. If it was using a PAC proxy, then the
9673 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9674 // to the local proxy server, which would forward them over the newly default network.
9675 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9676 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9677 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9678 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9679 }
9680
James Mattise3ef1912020-12-20 11:09:58 -08009681 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9682 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9683 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9684 if (DBG) {
9685 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9686 }
Chalard Jean8e382112019-12-03 20:45:30 +09009687
James Mattisd31bdfa2020-12-23 16:37:26 -08009688 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9689 if (newDefaultNetwork != null) {
9690 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009691 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009692
James Mattisd31bdfa2020-12-23 16:37:26 -08009693 // Set an app level managed default and return since further processing only applies to the
9694 // default network.
9695 if (mDefaultRequest != nri) {
9696 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9697 return;
9698 }
9699
9700 makeDefaultNetwork(newDefaultNetwork);
9701
James Mattise3ef1912020-12-20 11:09:58 -08009702 if (oldDefaultNetwork != null) {
9703 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9704 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09009705 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009706 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009707 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009708 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009709 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009710 updateTcpBufferSizes(null != newDefaultNetwork
9711 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009712 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009713 }
9714
James Mattisd31bdfa2020-12-23 16:37:26 -08009715 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9716 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9717 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9718 try {
9719 if (VDBG) {
9720 log("Setting default network for " + nri
9721 + " using UIDs " + nri.getUids()
9722 + " with old network " + (oldDefaultNetwork != null
9723 ? oldDefaultNetwork.network().getNetId() : "null")
9724 + " and new network " + (newDefaultNetwork != null
9725 ? newDefaultNetwork.network().getNetId() : "null"));
9726 }
9727 if (nri.getUids().isEmpty()) {
9728 throw new IllegalStateException("makeDefaultForApps called without specifying"
9729 + " any applications to set as the default." + nri);
9730 }
9731 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009732 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009733 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009734 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009735 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009736 }
9737 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009738 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009739 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009740 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009741 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009742 }
9743 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009744 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009745 }
9746 }
9747
Junyu Lai35665cc2022-12-19 17:37:48 +08009748 /**
9749 * Collect restricted uid ranges for the given network and UserHandle, these uids
9750 * are not restricted for matched enterprise networks but being restricted for non-matched
9751 * enterprise networks and non-enterprise networks.
9752 */
9753 @NonNull
9754 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9755 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9756 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9757 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9758 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9759
9760 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9761 // The NC is built from a `ProfileNetworkPreference` which has only one
9762 // enterprise ID, so it's guaranteed to have exactly one.
9763 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9764 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9765 continue;
9766 }
9767 }
9768
9769 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9770 pref.capabilities.getUidRanges())) {
9771 throw new IllegalArgumentException(
9772 "Overlapping uid range in preference: " + pref);
9773 }
9774 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9775 }
9776 return restrictedUidRanges;
9777 }
9778
9779 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009780 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009781 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009782
Junyu Lai35665cc2022-12-19 17:37:48 +08009783 ensureRunningOnConnectivityServiceThread();
9784 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9785 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9786 .getUserHandles(true /* excludeDying */);
9787 if (users.isEmpty()) {
9788 throw new IllegalStateException("No user is available");
9789 }
9790
9791 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9792 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9793 for (final UserHandle user : users) {
9794 final ArraySet<UidRange> restrictedUidRanges =
9795 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9796 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9797 UidRange.createForUser(user), restrictedUidRanges));
9798 }
9799
9800 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9801 configs.add(new NativeUidRangeConfig(
9802 nai.network.netId, rangesParcel, 0 /* subPriority */));
9803 }
9804
9805 // The netd API replaces the previous configs with the current configs.
9806 // Thus, for network disconnection or preference removal, no need to
9807 // unset previous config. Instead, collecting all currently needed
9808 // configs and issue to netd.
9809 try {
9810 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9811 } catch (ServiceSpecificException e) {
9812 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009813 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009814 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009815 // Netd died. This will cause a runtime restart anyway.
9816 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009817 }
9818 }
9819
James Mattisd31bdfa2020-12-23 16:37:26 -08009820 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9821 try {
9822 if (null != newDefaultNetwork) {
9823 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9824 } else {
9825 mNetd.networkClearDefault();
9826 }
9827 } catch (RemoteException | ServiceSpecificException e) {
9828 loge("Exception setting default network :" + e);
9829 }
9830 }
9831
Chalard Jean05cbe972019-12-09 11:50:38 +09009832 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009833 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009834 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009835 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009836 processNewlySatisfiedListenRequests(nai);
9837 }
9838
9839 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009840 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9841 if (nri.isMultilayerRequest()) {
9842 continue;
9843 }
9844 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009845 if (!nr.isListen()) continue;
9846 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009847 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009848 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9849 }
9850 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009851 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009852
Chalard Jeancd397a22019-11-22 22:33:33 +09009853 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009854 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9855 if (nri.isMultilayerRequest()) {
9856 continue;
9857 }
9858 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009859 if (!nr.isListen()) continue;
9860 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9861 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009862 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009863 }
9864 }
9865 }
9866
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009867 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009868 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009869 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009870 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009871 @Nullable public final NetworkRequest mOldNetworkRequest;
9872 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009873 @Nullable public final NetworkAgentInfo mOldNetwork;
9874 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009875 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009876 @Nullable final NetworkRequest oldNetworkRequest,
9877 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009878 @Nullable final NetworkAgentInfo oldNetwork,
9879 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009880 mNetworkRequestInfo = networkRequestInfo;
9881 mOldNetworkRequest = oldNetworkRequest;
9882 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009883 mOldNetwork = oldNetwork;
9884 mNewNetwork = newNetwork;
9885 }
Chalard Jean49707572019-12-10 21:07:02 +09009886
9887 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009888 final NetworkRequest requestToShow = null != mNewNetworkRequest
9889 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9890 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009891 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9892 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009893 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009894 }
9895
Chalard Jean46a62372019-12-10 21:25:24 +09009896 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009897
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009898 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009899 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009900 }
9901
9902 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009903 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009904 // The code is never supposed to add two reassignments of the same request. Make
9905 // sure this stays true, but without imposing this expensive check on all
9906 // reassignments on all user devices.
9907 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009908 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009909 throw new IllegalStateException("Trying to reassign ["
9910 + reassignment + "] but already have ["
9911 + existing + "]");
9912 }
9913 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009914 }
Chalard Jean46a62372019-12-10 21:25:24 +09009915 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009916 }
9917
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009918 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009919 // the passed request.
9920 @Nullable
9921 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009922 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009923 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009924 }
9925 return null;
9926 }
Chalard Jean49707572019-12-10 21:07:02 +09009927
9928 public String toString() {
9929 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9930 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009931 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009932 for (final RequestReassignment rr : getRequestReassignments()) {
9933 sj.add(rr.toString());
9934 }
9935 return sj.toString();
9936 }
9937
9938 public String debugString() {
9939 final StringBuilder sb = new StringBuilder();
9940 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009941 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009942 for (final RequestReassignment rr : getRequestReassignments()) {
9943 sb.append("\n ").append(rr);
9944 }
9945 return sb.append("\n").toString();
9946 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009947 }
9948
Chalard Jean24344d72019-12-04 13:32:31 +09009949 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009950 @Nullable final NetworkRequest previousRequest,
9951 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009952 @Nullable final NetworkAgentInfo previousSatisfier,
9953 @Nullable final NetworkAgentInfo newSatisfier,
9954 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009955 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009956 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009957 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009958 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009959 log(" accepting network in place of " + previousSatisfier.toShortString()
9960 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009961 }
James Mattisa076c532020-12-02 14:12:41 -08009962 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009963 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009964 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009965 // If this network switch can't be supported gracefully, the request is not
9966 // lingered. This allows letting go of the network sooner to reclaim some
9967 // performance on the new network, since the radio can't do both at the same
9968 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009969 //
9970 // Also don't linger the request if the old network has been destroyed.
9971 // A destroyed network does not provide actual network connectivity, so
9972 // lingering it is not useful. In particular this ensures that a destroyed
9973 // network is outscored by its replacement,
9974 // then it is torn down immediately instead of being lingered, and any apps that
9975 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009976 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9977 }
Chalard Jean24344d72019-12-04 13:32:31 +09009978 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009979 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009980 }
junyulai0ac374f2020-12-14 18:41:52 +08009981
9982 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9983 // and immediately satisfies a request then remove the timer. This will happen for
9984 // all networks except in the case of an underlying network for a VCN.
9985 if (newSatisfier.isNascent()) {
9986 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009987 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009988 }
9989
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009990 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009991 newSatisfier.unlingerRequest(newRequest.requestId);
9992 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009993 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009994 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009995 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009996 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009997 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009998 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009999 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010000 }
James Mattisa076c532020-12-02 14:12:41 -080010001 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010002 }
James Mattisa076c532020-12-02 14:12:41 -080010003 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010004 }
10005
James Mattisa076c532020-12-02 14:12:41 -080010006 /**
10007 * This function is triggered when something can affect what network should satisfy what
10008 * request, and it computes the network reassignment from the passed collection of requests to
10009 * network match to the one that the system should now have. That data is encoded in an
10010 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
10011 * satisfier.
10012 *
10013 * After the reassignment is computed, it is applied to the state objects.
10014 *
10015 * @param networkRequests the nri objects to evaluate for possible network reassignment
10016 * @return NetworkReassignment listing of proposed network assignment changes
10017 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010018 @NonNull
James Mattisa076c532020-12-02 14:12:41 -080010019 private NetworkReassignment computeNetworkReassignment(
10020 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090010021 final NetworkReassignment changes = new NetworkReassignment();
10022
Chalard Jeanc81d4c32021-04-07 17:06:19 +090010023 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090010024 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010025 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +090010026 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +090010027 }
Chalard Jean857a1712019-12-10 21:08:07 +090010028
James Mattisa076c532020-12-02 14:12:41 -080010029 for (final NetworkRequestInfo nri : networkRequests) {
10030 // Non-multilayer listen requests can be ignored.
10031 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
10032 continue;
10033 }
10034 NetworkAgentInfo bestNetwork = null;
10035 NetworkRequest bestRequest = null;
10036 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090010037 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080010038 // Stop evaluating as the highest possible priority request is satisfied.
10039 if (null != bestNetwork) {
10040 bestRequest = req;
10041 break;
10042 }
10043 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010044 if (null == bestNetwork && isDefaultBlocked(nri)) {
10045 // Remove default networking if disallowed for managed default requests.
10046 bestNetwork = mNoServiceNetwork;
10047 }
10048 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010049 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010050 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010051 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010052 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010053 }
10054 return changes;
10055 }
10056
James Mattisa076c532020-12-02 14:12:41 -080010057 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10058 return new HashSet<>(mNetworkRequests.values());
10059 }
10060
Paul Jensenc88b39b2015-06-16 14:27:36 -040010061 /**
James Mattisa076c532020-12-02 14:12:41 -080010062 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010063 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010064 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010065 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010066 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10067 }
10068
10069 /**
10070 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10071 * being disconnected.
10072 */
10073 private void rematchNetworksAndRequests(
10074 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10075 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010076 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010077 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010078 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010079 final long computed = SystemClock.elapsedRealtime();
10080 applyNetworkReassignment(changes, start);
10081 final long applied = SystemClock.elapsedRealtime();
10082 issueNetworkNeeds();
10083 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010084 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010085 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10086 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010087 log(changes.debugString());
10088 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010089 // Shorter form, only one line of log
10090 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10091 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010092 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010093 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010094
Chalard Jean1e4c2182023-10-06 18:45:53 +090010095 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10096 @Nullable final NetworkAgentInfo nai2) {
10097 if (null == nai1) return null == nai2;
10098 if (null == nai2) return false;
10099 return nai1.linkProperties.getInterfaceName()
10100 .equals(nai2.linkProperties.getInterfaceName());
10101 }
10102
Chalard Jeand7f762d2019-12-10 19:01:29 +090010103 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010104 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010105 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010106
10107 // Since most of the time there are only 0 or 1 background networks, it would probably
10108 // be more efficient to just use an ArrayList here. TODO : measure performance
10109 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10110 for (final NetworkAgentInfo nai : nais) {
10111 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10112 }
10113
Chalard Jeand7f762d2019-12-10 19:01:29 +090010114 // First, update the lists of satisfied requests in the network agents. This is necessary
10115 // because some code later depends on this state to be correct, most prominently computing
10116 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010117 for (final NetworkReassignment.RequestReassignment event :
10118 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010119 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10120 event.mOldNetworkRequest, event.mNewNetworkRequest,
10121 event.mOldNetwork, event.mNewNetwork,
10122 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010123 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010124
James Mattise3ef1912020-12-20 11:09:58 -080010125 // Process default network changes if applicable.
10126 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010127
Chalard Jean68eab722023-11-16 17:00:04 +090010128 // Update forwarding rules for the upstreams of local networks. Do this before sending
10129 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10130 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10131 // onAvailable so clients know what network the change is about. Store such changes in
10132 // an array that's only allocated if necessary (because it's almost never necessary).
10133 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10134 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10135 if (!nai.isLocalNetwork()) continue;
10136 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10137 if (null == nr) continue; // No upstream for this local network
10138 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10139 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10140 if (null == change) continue; // No change in upstreams for this network
10141 final String fromIface = nai.linkProperties.getInterfaceName();
10142 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10143 || change.mOldNetwork.isDestroyed()) {
10144 // There can be a change with the same interface name if the new network is the
10145 // replacement for the old network that was unregisteredAfterReplacement.
10146 try {
10147 if (null != change.mOldNetwork) {
10148 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10149 change.mOldNetwork.linkProperties.getInterfaceName());
10150 }
10151 // If the new upstream is already destroyed, there is no point in setting up
10152 // a forward (in fact, it might forward to the interface for some new network !)
10153 // Later when the upstream disconnects CS will try to remove the forward, which
10154 // is ignored with a benign log by RoutingCoordinatorService.
10155 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10156 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10157 change.mNewNetwork.linkProperties.getInterfaceName());
10158 }
10159 } catch (final RemoteException e) {
10160 loge("Can't update forwarding rules", e);
10161 }
10162 }
10163 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10164 localInfoChangedAgents.add(nai);
10165 }
10166
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010167 // Notify requested networks are available after the default net is switched, but
10168 // before LegacyTypeTracker sends legacy broadcasts
10169 for (final NetworkReassignment.RequestReassignment event :
10170 changes.getRequestReassignments()) {
10171 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010172 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010173 } else {
James Mattisa076c532020-12-02 14:12:41 -080010174 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010175 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010176 }
10177 }
10178
junyulai0ac374f2020-12-14 18:41:52 +080010179 // Update the inactivity state before processing listen callbacks, because the background
10180 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010181 // just yet though, because they have to be sent after the listens are processed to keep
10182 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010183 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010184 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010185 // Rematching may have altered the inactivity state of some networks, so update all
10186 // inactivity timers. updateInactivityState reads the state from the network agent
10187 // and does nothing if the state has not changed : the source of truth is controlled
10188 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10189 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010190 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010191 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010192 }
10193 }
10194
Chalard Jeanb10ab412019-12-11 14:12:30 +090010195 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010196 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010197 // Process listen requests and update capabilities if the background state has
10198 // changed for this network. For consistency with previous behavior, send onLost
10199 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010200 processNewlyLostListenRequests(nai);
10201 if (oldBackground != nai.isBackgroundNetwork()) {
10202 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010203 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010204 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010205 }
10206
junyulai0ac374f2020-12-14 18:41:52 +080010207 for (final NetworkAgentInfo nai : inactiveNetworks) {
10208 // For nascent networks, if connecting with no foreground request, skip broadcasting
10209 // LOSING for backward compatibility. This is typical when mobile data connected while
10210 // wifi connected with mobile data always-on enabled.
10211 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010212 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010213 }
10214
Chalard Jean68eab722023-11-16 17:00:04 +090010215 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10216 if (null != localInfoChangedAgents) {
10217 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10218 notifyNetworkCallbacks(nai,
10219 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010220 }
10221 }
10222
James Mattise3ef1912020-12-20 11:09:58 -080010223 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010224
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010225 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010226 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010227 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010228 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010229 // This network has active linger timers and no requests, but is not
10230 // lingering. Linger it.
10231 //
10232 // One way (the only way?) this can happen if this network is unvalidated
10233 // and became unneeded due to another network improving its score to the
10234 // point where this network will no longer be able to satisfy any requests
10235 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010236 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010237 notifyNetworkLosing(nai, now);
10238 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010239 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010240 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010241 teardownUnneededNetwork(nai);
10242 }
10243 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010244 }
10245 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010246
Chalard Jean62edfd82019-12-02 18:39:29 +090010247 /**
10248 * Apply a change in background state resulting from rematching networks with requests.
10249 *
10250 * During rematch, a network may change background states by starting to satisfy or stopping
10251 * to satisfy a foreground request. Listens don't count for this. When a network changes
10252 * background states, its capabilities need to be updated and callbacks fired for the
10253 * capability change.
10254 *
10255 * @param nai The network that changed background states
10256 */
10257 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10258 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10259 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10260 updateNetworkPermissions(nai, newNc);
10261 nai.getAndSetNetworkCapabilities(newNc);
10262 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10263 }
10264
Chalard Jeanf0344532019-11-19 19:23:38 +090010265 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010266 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010267 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010268 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10269 changes.getReassignment(mDefaultRequest);
10270 final NetworkAgentInfo oldDefaultNetwork =
10271 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10272 final NetworkAgentInfo newDefaultNetwork =
10273 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010274
Chalard Jean5b409c72021-02-04 13:12:59 +090010275 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010276 // Maintain the illusion : since the legacy API only understands one network at a time,
10277 // if the default network changed, apps should see a disconnected broadcast for the
10278 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010279 if (oldDefaultNetwork != null) {
10280 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10281 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010282 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010283 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010284 // The new default network can be newly null if and only if the old default
10285 // network doesn't satisfy the default request any more because it lost a
10286 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010287 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010288 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010289 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010290 }
10291 }
10292
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010293 // Now that all the callbacks have been sent, send the legacy network broadcasts
10294 // as needed. This is necessary so that legacy requests correctly bind dns
10295 // requests to this network. The legacy users are listening for this broadcast
10296 // and will generally do a dns request so they can ensureRouteToHost and if
10297 // they do that before the callbacks happen they'll use the default network.
10298 //
10299 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10300 // callbacks, but if apps can receive the broadcast before the callback, they still might
10301 // have an inconsistent view of networking.
10302 //
10303 // This *does* introduce a race where if the user uses the new api
10304 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10305 // they may get old info. Reverse this after the old startUsing api is removed.
10306 // This is on top of the multiple intent sequencing referenced in the todo above.
10307 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010308 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010309 addNetworkToLegacyTypeTracker(nai);
10310 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010311 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010312 }
10313
Chalard Jean0354d8c2021-01-12 10:58:56 +090010314 private void issueNetworkNeeds() {
10315 ensureRunningOnConnectivityServiceThread();
10316 for (final NetworkOfferInfo noi : mNetworkOffers) {
10317 issueNetworkNeeds(noi);
10318 }
10319 }
10320
10321 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10322 ensureRunningOnConnectivityServiceThread();
10323 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10324 informOffer(nri, noi.offer, mNetworkRanker);
10325 }
10326 }
10327
10328 /**
10329 * Inform a NetworkOffer about any new situation of a request.
10330 *
10331 * This function handles updates to offers. A number of events may happen that require
10332 * updating the registrant for this offer about the situation :
10333 * • The offer itself was updated. This may lead the offer to no longer being able
10334 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10335 * or conversely being strengthened enough to beat the satisfier (and therefore
10336 * start being needed)
10337 * • The network satisfying a request changed (including cases where the request
10338 * starts or stops being satisfied). The new network may be a stronger or weaker
10339 * match than the old one, possibly affecting whether the offer is needed.
10340 * • The network satisfying a request updated their score. This may lead the offer
10341 * to no longer be able to beat it if the current satisfier got better, or
10342 * conversely start being a good choice if the current satisfier got weaker.
10343 *
10344 * @param nri The request
10345 * @param offer The offer. This may be an updated offer.
10346 */
10347 private static void informOffer(@NonNull NetworkRequestInfo nri,
10348 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10349 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10350 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010351
10352 // Multi-layer requests have a currently active request, the one being satisfied.
10353 // Since the system will try to bring up a better network than is currently satisfying
10354 // the request, NetworkProviders need to be told the offers matching the requests *above*
10355 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10356 // not needed, and the offer is needed for the active request iff the offer can beat
10357 // the satisfier.
10358 // For non-multilayer requests, the logic above gracefully degenerates to only the
10359 // last case.
10360 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10361 // providers that the offer is needed for this request, until the active request is found.
10362 // In a second phase, deal with the currently active request. In a third phase, inform
10363 // the providers that offer is unneeded for the remaining requests.
10364
10365 // First phase : inform providers of all requests above the active request.
10366 int i;
10367 for (i = 0; nri.mRequests.size() > i; ++i) {
10368 final NetworkRequest request = nri.mRequests.get(i);
10369 if (activeRequest == request) break; // Found the active request : go to phase 2
10370 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10371 // Since this request is higher-priority than the one currently satisfied, if the
10372 // offer can satisfy it, the provider should try and bring up the network for sure ;
10373 // no need to even ask the ranker – an offer that can satisfy is always better than
10374 // no network. Hence tell the provider so unless it already knew.
10375 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10376 offer.onNetworkNeeded(request);
10377 }
10378 }
10379
10380 // Second phase : deal with the active request (if any)
10381 if (null != activeRequest && activeRequest.isRequest()) {
10382 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010383 // If an offer can satisfy the request, it is considered needed if it is currently
10384 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010385 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010386 && satisfier.factorySerialNumber == offer.providerId
10387 && activeRequest.canBeSatisfiedBy(offer.caps);
10388 final boolean newNeeded = currentlyServing
10389 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010390 if (newNeeded != oldNeeded) {
10391 if (newNeeded) {
10392 offer.onNetworkNeeded(activeRequest);
10393 } else {
10394 // The offer used to be able to beat the satisfier. Now it can't.
10395 offer.onNetworkUnneeded(activeRequest);
10396 }
10397 }
10398 }
10399
10400 // Third phase : inform the providers that the offer isn't needed for any request
10401 // below the active one.
10402 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10403 final NetworkRequest request = nri.mRequests.get(i);
10404 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10405 // Since this request is lower-priority than the one currently satisfied, if the
10406 // offer can satisfy it, the provider should not try and bring up the network.
10407 // Hence tell the provider so unless it already knew.
10408 if (offer.neededFor(request)) {
10409 offer.onNetworkUnneeded(request);
10410 }
10411 }
10412 }
10413
Chalard Jean61c79252019-11-07 23:07:32 +090010414 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10415 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10416 NetworkRequest nr = nai.requestAt(i);
10417 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10418 // legacy type tracker filters out repeat adds
10419 mLegacyTypeTracker.add(nr.legacyType, nai);
10420 }
10421 }
10422
10423 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010424 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010425 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10426 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10427 if (nai.isVPN()) {
10428 mLegacyTypeTracker.add(TYPE_VPN, nai);
10429 }
10430 }
10431
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010432 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010433 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010434 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010435 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010436 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010437 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010438
Chalard Jean254bd162022-08-25 13:04:51 +090010439 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010440 // Don't repeat publish.
10441 if (newInetCondition == mDefaultInetConditionPublished) return;
10442
10443 mDefaultInetConditionPublished = newInetCondition;
10444 sendInetConditionBroadcast(nai.networkInfo);
10445 }
10446
Chalard Jeand61375d2020-01-14 22:46:36 +090010447 @NonNull
10448 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10449 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010450 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010451 final boolean suspended =
10452 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10453 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10454 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10455 // state. This is because the network could have been suspended before connecting,
10456 // or it could be disconnecting while being suspended, and in both these cases
10457 // the state should not be overridden. Note that the only detailed state that
10458 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10459 // worry about multiple different substates of CONNECTED.
10460 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10461 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010462 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10463 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10464 // network agent is created, then goes to suspended, then goes out of suspended without
10465 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010466 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010467 ? NetworkInfo.DetailedState.CONNECTED
10468 : NetworkInfo.DetailedState.CONNECTING,
10469 info.getReason(),
10470 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010471 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010472 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010473 return newInfo;
10474 }
10475
10476 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10477 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10478
Erik Kline99f301b2017-02-15 19:59:17 +090010479 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010480 NetworkInfo oldInfo = null;
10481 synchronized (networkAgent) {
10482 oldInfo = networkAgent.networkInfo;
10483 networkAgent.networkInfo = newInfo;
10484 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010485
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010486 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010487 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10488 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010489 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010490
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010491 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010492 // A network that has just connected has zero requests and is thus a foreground network.
10493 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10494
Luke Huangfdd11f82019-04-09 18:41:49 +080010495 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010496
10497 networkAgent.setCreated();
10498
10499 // If the network is created immediately on register, then apply the LinkProperties now.
10500 // Otherwise, this is done further down when the network goes into connected state.
10501 // Applying the LinkProperties means that the network is ready to carry traffic -
10502 // interfaces and routing rules have been added, DNS servers programmed, etc.
10503 // For VPNs, this must be done before the capabilities are updated, because as soon as
10504 // that happens, UIDs are routed to the network.
10505 if (shouldCreateNetworksImmediately()) {
10506 applyInitialLinkProperties(networkAgent);
10507 }
10508
10509 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10510 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010511 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010512 // Initialize the network's capabilities to their starting values according to the
10513 // underlying networks. This ensures that the capabilities are correct before
10514 // anything happens to the network.
10515 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010516 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010517 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010518 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010519 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010520 }
10521
Chalard Jean254bd162022-08-25 13:04:51 +090010522 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10523 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010524
lucaslin45e639b2019-04-03 17:09:28 +080010525 // NetworkCapabilities need to be set before sending the private DNS config to
10526 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010527 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10528
Erik Kline9a62f012018-03-21 07:18:33 -070010529 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010530 if (!shouldCreateNetworksImmediately()) {
10531 applyInitialLinkProperties(networkAgent);
10532 } else {
10533 // The network was created when the agent registered, and the LinkProperties are
10534 // already up-to-date. However, updateLinkProperties also makes some changes only
10535 // when the network connects. Apply those changes here. On T and below these are
10536 // handled by the applyInitialLinkProperties call just above.
10537 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10538 // If something depends on both LinkProperties and connected state, it should be in
10539 // this method as well.
10540 networkAgent.clatd.update();
10541 updateProxy(networkAgent.linkProperties, null);
10542 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010543
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010544 // If a rate limit has been configured and is applicable to this network (network
10545 // provides internet connectivity), apply it. The tc police filter cannot be attached
10546 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010547 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010548 // Note: in case of a system server crash, the NetworkController constructor in netd
10549 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10550 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10551 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10552 mIngressRateLimit);
10553 }
10554
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010555 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10556 // command must be sent after updating LinkProperties to maximize chances of
10557 // NetworkMonitor seeing the correct LinkProperties when starting.
10558 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010559 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010560 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010561 }
Chalard Jeand4900722022-02-06 12:25:38 +090010562 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10563 params.networkAgentConfig = networkAgent.networkAgentConfig;
10564 params.networkCapabilities = networkAgent.networkCapabilities;
10565 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10566 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010567 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10568 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10569 // call that would cause a Log.wtf to be emitted from the system_server process, and
10570 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10571 // process to check the interface version, just use an SDK check. NetworkStack will
10572 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010573 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010574 networkAgent.networkMonitor().notifyNetworkConnected(params);
10575 } else {
10576 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10577 params.networkCapabilities);
10578 }
Chalard Jean0f141332023-06-05 19:26:17 +090010579 final long evaluationDelay;
10580 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10581 // If the network is anything other than pure wifi, use the default timeout.
10582 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10583 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10584 // If the network is explicitly selected, use the default timeout because it's
10585 // shorter and the user is likely staring at the screen expecting it to validate
10586 // right away.
10587 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10588 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10589 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10590 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10591 } else {
10592 // It's wifi, automatically connected, and bad wifi is preferred : use the
10593 // longer timeout to avoid the device switching to captive portals with bad
10594 // signal or very slow response.
10595 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10596 }
10597 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010598
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010599 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10600 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10601 // capabilities, so it only needs to be done once on initial connect, not every time the
10602 // network's capabilities change. Note that we do this before rematching the network,
10603 // so we could decide to tear it down immediately afterwards. That's fine though - on
10604 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10605 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010606 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010607
junyulai0ac374f2020-12-14 18:41:52 +080010608 // Before first rematching networks, put an inactivity timer without any request, this
10609 // allows {@code updateInactivityState} to update the state accordingly and prevent
10610 // tearing down for any {@code unneeded} evaluation in this period.
10611 // Note that the timer will not be rescheduled since the expiry time is
10612 // fixed after connection regardless of the network satisfying other requests or not.
10613 // But it will be removed as soon as the network satisfies a request for the first time.
10614 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10615 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010616 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010617
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010618 if (mTrackMultiNetworkActivities) {
10619 // Start tracking activity of this network.
10620 // This must be called before rematchAllNetworksAndRequests since the network
10621 // should be tracked when the network becomes the default network.
10622 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
10623 // can be triggered later if this network becomes the default network.
10624 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
10625 }
10626
Paul Jensen05e85ee2014-09-11 11:00:39 -040010627 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010628 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010629
10630 // This has to happen after matching the requests, because callbacks are just requests.
10631 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010632 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010633 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010634 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010635 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010636 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010637 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010638 if (networkAgent.isVPN()) {
10639 // As the active or bound network changes for apps, broadcast the default proxy, as
10640 // apps may need to update their proxy data. This is called after disconnecting from
10641 // VPN to make sure we do not broadcast the old proxy data.
10642 // TODO(b/122649188): send the broadcast only to VPN users.
10643 mProxyTracker.sendProxyBroadcast();
10644 }
Chalard Jean254bd162022-08-25 13:04:51 +090010645 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10646 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010647 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010648 }
10649 }
10650
Chalard Jean28018572020-12-21 18:36:52 +090010651 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010652 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10653 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010654 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010655 }
10656
Erik Kline99f301b2017-02-15 19:59:17 +090010657 // Notify only this one new request of the current state. Transfer all the
10658 // current state by calling NetworkCapabilities and LinkProperties callbacks
10659 // so that callers can be guaranteed to have as close to atomicity in state
10660 // transfer as can be supported by this current API.
10661 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010662 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010663 if (nri.mPendingIntent != null) {
10664 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10665 // Attempt no subsequent state pushes where intents are involved.
10666 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010667 }
Erik Kline99f301b2017-02-15 19:59:17 +090010668
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010669 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010670 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010671 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10672 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10673 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010674 }
10675
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010676 // Notify the requests on this NAI that the network is now lingered.
10677 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010678 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010679 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10680 }
10681
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010682 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10683 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10684 return vpnBlocked
10685 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10686 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10687 }
10688
10689 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10690 if (blockedReasons == BLOCKED_REASON_NONE) {
10691 mUidBlockedReasons.delete(uid);
10692 } else {
10693 mUidBlockedReasons.put(uid, blockedReasons);
10694 }
10695 }
10696
junyulaif2c67e42018-08-07 19:50:45 +080010697 /**
10698 * Notify of the blocked state apps with a registered callback matching a given NAI.
10699 *
10700 * Unlike other callbacks, blocked status is different between each individual uid. So for
10701 * any given nai, all requests need to be considered according to the uid who filed it.
10702 *
10703 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010704 * @param oldMetered True if the previous network capabilities were metered.
10705 * @param newMetered True if the current network capabilities are metered.
10706 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10707 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010708 */
10709 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010710 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10711 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010712
10713 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10714 NetworkRequest nr = nai.requestAt(i);
10715 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010716
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010717 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10718 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10719 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010720 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010721 : oldVpnBlocked;
10722
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010723 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10724 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10725 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010726 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010727 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010728 }
10729 }
10730 }
10731
10732 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010733 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010734 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010735 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010736 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010737 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010738 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010739 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010740 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010741
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010742 final int oldBlockedState = getBlockedState(
10743 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10744 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10745 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010746 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010747 }
junyulaif2c67e42018-08-07 19:50:45 +080010748 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10749 NetworkRequest nr = nai.requestAt(i);
10750 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010751 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010752 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10753 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010754 }
10755 }
10756 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010757 }
10758
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010759 @VisibleForTesting
10760 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010761 // The NetworkInfo we actually send out has no bearing on the real
10762 // state of affairs. For example, if the default connection is mobile,
10763 // and a request for HIPRI has just gone away, we need to pretend that
10764 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10765 // the state to DISCONNECTED, even though the network is of type MOBILE
10766 // and is still connected.
10767 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10768 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010769 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010770 if (state != DetailedState.DISCONNECTED) {
10771 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010772 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010773 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010774 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010775 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10776 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10777 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10778 if (info.isFailover()) {
10779 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10780 nai.networkInfo.setFailover(false);
10781 }
10782 if (info.getReason() != null) {
10783 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10784 }
10785 if (info.getExtraInfo() != null) {
10786 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10787 }
10788 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010789 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010790 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010791 if (newDefaultAgent != null) {
10792 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10793 newDefaultAgent.networkInfo);
10794 } else {
10795 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10796 }
10797 }
10798 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10799 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010800 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010801 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010802 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010803 }
10804 }
10805 }
10806
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010807 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010808 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010809 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010810 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010811 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010812 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10813 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010814 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10815 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010816 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010817 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010818 } else {
10819 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10820 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010821 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010822 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010823
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010824 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10825 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10826 }
10827
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010828 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010829 * Returns the list of all interfaces that could be used by network traffic that does not
10830 * explicitly specify a network. This includes the default network, but also all VPNs that are
10831 * currently connected.
10832 *
10833 * Must be called on the handler thread.
10834 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010835 @NonNull
10836 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010837 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010838 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010839 final Set<Integer> activeNetIds = new ArraySet<>();
10840 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10841 if (nri.isBeingSatisfied()) {
10842 activeNetIds.add(nri.getSatisfier().network().netId);
10843 }
10844 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010845 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010846 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010847 defaultNetworks.add(nai.network);
10848 }
10849 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010850 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010851 }
10852
10853 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010854 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10855 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010856 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010857 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010858 ensureRunningOnConnectivityServiceThread();
10859 String activeIface = null;
10860 LinkProperties activeLinkProperties = getActiveLinkProperties();
10861 if (activeLinkProperties != null) {
10862 activeIface = activeLinkProperties.getInterfaceName();
10863 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010864
junyulai2050bed2021-01-23 09:46:34 +080010865 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010866 try {
junyulaide41fc22021-01-22 22:46:01 +080010867 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010868 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010869 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10870 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010871 } catch (Exception ignored) {
10872 }
10873 }
10874
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010875 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010876 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010877 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010878 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010879 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010880
10881 if (!TextUtils.isEmpty(settingUrl)) {
10882 return settingUrl;
10883 }
10884
10885 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010886 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010887 if (!TextUtils.isEmpty(settingUrl)) {
10888 return settingUrl;
10889 }
10890
10891 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010892 }
10893
10894 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010895 public void startNattKeepalive(Network network, int intervalSeconds,
10896 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010897 enforceKeepalivePermission();
10898 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010899 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010900 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10901 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010902 // false and set the underpinned network to null because there is no way and no
10903 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10904 // deprecated method.
10905 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010906 }
10907
10908 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010909 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010910 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010911 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010912 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010913 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010914 mKeepaliveTracker.startNattKeepalive(
10915 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010916 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10917 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010918 } finally {
10919 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10920 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010921 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10922 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010923 }
10924 }
junyulaid05a1922019-01-15 11:32:44 +080010925 }
10926
10927 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010928 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010929 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010930 try {
10931 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010932 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010933 mKeepaliveTracker.startTcpKeepalive(
10934 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10935 } finally {
10936 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10937 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010938 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10939 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010940 }
10941 }
junyulai0835a1e2019-01-08 20:04:33 +080010942 }
10943
10944 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010945 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010946 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010947 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10948 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010949 }
10950
10951 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010952 public int[] getSupportedKeepalives() {
10953 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10954 // Backwards compatibility with CTS 13
10955 android.Manifest.permission.QUERY_ALL_PACKAGES);
10956
10957 return BinderUtils.withCleanCallingIdentity(() ->
10958 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10959 }
10960
10961 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010962 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010963 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010964
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010965 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010966 final long token = Binder.clearCallingIdentity();
10967 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010968 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10969 UserHandle.getUserHandleForUid(uid))) {
10970 return;
10971 }
10972
Heemin Seogdb8489d2019-06-12 09:21:44 -070010973 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10974 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010975
10976 // Turn airplane mode off
10977 setAirplaneMode(false);
10978
10979 // restore private DNS settings to default mode (opportunistic)
10980 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10981 UserHandle.getUserHandleForUid(uid))) {
10982 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10983 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10984 }
10985
10986 Settings.Global.putString(mContext.getContentResolver(),
10987 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010988 } finally {
10989 Binder.restoreCallingIdentity(token);
10990 }
Stuart Scottd5463642015-04-02 18:00:02 -070010991 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010992
Ricky Wai7097cc92018-01-23 04:09:45 +000010993 @Override
10994 public byte[] getNetworkWatchlistConfigHash() {
10995 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10996 if (nwm == null) {
10997 loge("Unable to get NetworkWatchlistManager");
10998 return null;
10999 }
11000 // Redirect it to network watchlist service to access watchlist file and calculate hash.
11001 return nwm.getWatchlistConfigHash();
11002 }
11003
Hugo Benichibe0c7652016-05-31 16:28:06 +090011004 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090011005 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080011006 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090011007 }
Hugo Benichif4210292017-04-21 15:07:12 +090011008
11009 private static boolean toBool(int encodedBoolean) {
11010 return encodedBoolean != 0; // Only 0 means false.
11011 }
11012
11013 private static int encodeBool(boolean b) {
11014 return b ? 1 : 0;
11015 }
mswest4632928412018-03-12 10:34:34 -070011016
11017 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011018 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
11019 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
11020 @NonNull String[] args) {
11021 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
11022 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070011023 }
11024
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011025 private Boolean parseBooleanArgument(final String arg) {
11026 if ("true".equals(arg)) {
11027 return true;
11028 } else if ("false".equals(arg)) {
11029 return false;
11030 } else {
11031 return null;
11032 }
11033 }
11034
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011035 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070011036 @Override
11037 public int onCommand(String cmd) {
11038 if (cmd == null) {
11039 return handleDefaultCommands(cmd);
11040 }
11041 final PrintWriter pw = getOutPrintWriter();
11042 try {
11043 switch (cmd) {
11044 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011045 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11046 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011047 final String action = getNextArg();
11048 if ("enable".equals(action)) {
11049 setAirplaneMode(true);
11050 return 0;
11051 } else if ("disable".equals(action)) {
11052 setAirplaneMode(false);
11053 return 0;
11054 } else if (action == null) {
11055 final ContentResolver cr = mContext.getContentResolver();
11056 final int enabled = Settings.Global.getInt(cr,
11057 Settings.Global.AIRPLANE_MODE_ON);
11058 pw.println(enabled == 0 ? "disabled" : "enabled");
11059 return 0;
11060 } else {
11061 onHelp();
11062 return -1;
11063 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011064 case "set-chain3-enabled": {
11065 final Boolean enabled = parseBooleanArgument(getNextArg());
11066 if (null == enabled) {
11067 onHelp();
11068 return -1;
11069 }
11070 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11071 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11072 enabled);
11073 return 0;
11074 }
11075 case "get-chain3-enabled": {
11076 final boolean chainEnabled = getFirewallChainEnabled(
11077 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11078 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11079 return 0;
11080 }
11081 case "set-package-networking-enabled": {
11082 final Boolean enabled = parseBooleanArgument(getNextArg());
11083 final String packageName = getNextArg();
11084 if (null == enabled || null == packageName) {
11085 onHelp();
11086 return -1;
11087 }
11088 // Throws NameNotFound if the package doesn't exist.
11089 final int appId = setPackageFirewallRule(
11090 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11091 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11092 final String msg = (enabled ? "Enabled" : "Disabled")
11093 + " networking for " + packageName + ", appId " + appId;
11094 Log.i(TAG, msg);
11095 pw.println(msg);
11096 return 0;
11097 }
11098 case "get-package-networking-enabled": {
11099 final String packageName = getNextArg();
11100 final int rule = getPackageFirewallRule(
11101 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11102 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11103 pw.println(packageName + ":" + "allow");
11104 } else if (FIREWALL_RULE_DENY == rule) {
11105 pw.println(packageName + ":" + "deny");
11106 } else {
11107 throw new IllegalStateException("Unknown rule " + rule + " for package "
11108 + packageName);
11109 }
11110 return 0;
11111 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011112 case "reevaluate":
11113 // Usage : adb shell cmd connectivity reevaluate <netId>
11114 // If netId is omitted, then reevaluate the default network
11115 final String netId = getNextArg();
11116 final NetworkAgentInfo nai;
11117 if (null == netId) {
11118 // Note that the command is running on the wrong thread to call this,
11119 // so this could in principle return stale data. But it can't crash.
11120 nai = getDefaultNetwork();
11121 } else {
11122 // If netId can't be parsed, this throws NumberFormatException, which
11123 // is passed back to adb who prints it.
11124 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11125 }
11126 if (null == nai) {
11127 pw.println("Unknown network (net ID not found or no default network)");
11128 return 0;
11129 }
11130 Log.d(TAG, "Reevaluating network " + nai.network);
11131 reportNetworkConnectivity(nai.network, !nai.isValidated());
11132 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011133 case "bpf-get-cgroup-program-id": {
11134 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11135 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11136 // for more detail.
11137 // If type can't be parsed, this throws NumberFormatException, which
11138 // is passed back to adb who prints it.
11139 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011140 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011141 pw.println(ret);
11142 return 0;
11143 }
mswest4632928412018-03-12 10:34:34 -070011144 default:
11145 return handleDefaultCommands(cmd);
11146 }
11147 } catch (Exception e) {
11148 pw.println(e);
11149 }
11150 return -1;
11151 }
11152
11153 @Override
11154 public void onHelp() {
11155 PrintWriter pw = getOutPrintWriter();
11156 pw.println("Connectivity service commands:");
11157 pw.println(" help");
11158 pw.println(" Print this help text.");
11159 pw.println(" airplane-mode [enable|disable]");
11160 pw.println(" Turn airplane mode on or off.");
11161 pw.println(" airplane-mode");
11162 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011163 pw.println(" set-chain3-enabled [true|false]");
11164 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11165 pw.println(" get-chain3-enabled");
11166 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11167 pw.println(" set-package-networking-enabled [true|false] [package name]");
11168 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11169 + " no effect if the chain is disabled.");
11170 pw.println(" get-package-networking-enabled [package name]");
11171 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011172 }
11173 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011174
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011175 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011176 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11177 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11178 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011179 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011180 }
11181
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011182 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11183 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011184 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11185 final TransportInfo newInfo = nc.getTransportInfo();
11186 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11187 return;
11188 }
11189 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011190 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011191 }
11192 }
11193
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011194 /**
11195 * @param connectionInfo the connection to resolve.
11196 * @return {@code uid} if the connection is found and the app has permission to observe it
11197 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11198 * connection is not found.
11199 */
11200 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011201 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11202 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11203 }
11204
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011205 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011206 connectionInfo.local, connectionInfo.remote);
11207
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011208 if (uid == INVALID_UID) return uid; // Not found.
11209
11210 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11211 // VPN, if any, that applies to the UID that owns the connection.
11212 if (checkNetworkStackPermission()) return uid;
11213
11214 final NetworkAgentInfo vpn = getVpnForUid(uid);
11215 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011216 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011217 return INVALID_UID;
11218 }
11219
11220 return uid;
11221 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011222
Benedict Wong493e04b2018-11-09 14:45:34 -080011223 /**
11224 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11225 *
11226 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11227 */
11228 @Override
11229 public IBinder startOrGetTestNetworkService() {
11230 synchronized (mTNSLock) {
11231 TestNetworkService.enforceTestNetworkPermissions(mContext);
11232
11233 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011234 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011235 }
11236
11237 return mTNS;
11238 }
11239 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011240
Cody Kesting73708bf2019-12-18 10:57:50 -080011241 /**
11242 * Handler used for managing all Connectivity Diagnostics related functions.
11243 *
11244 * @see android.net.ConnectivityDiagnosticsManager
11245 *
11246 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11247 */
11248 @VisibleForTesting
11249 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011250 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11251
Cody Kesting73708bf2019-12-18 10:57:50 -080011252 /**
11253 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11254 * android.net.ConnectivityDiagnosticsManager}.
11255 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11256 * NetworkRequestInfo to be registered
11257 */
11258 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11259
11260 /**
11261 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11262 * android.net.ConnectivityDiagnosticsManager}.
11263 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11264 * arg1 = the uid of the caller
11265 */
11266 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11267
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011268 /**
11269 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011270 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011271 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11272 * NetworkMonitor.
11273 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011274 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011275 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011276
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011277 /**
11278 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11279 * been detected on the network.
11280 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11281 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11282 * arg2 = NetID.
11283 * data = PersistableBundle of extras passed from NetworkMonitor.
11284 */
11285 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11286
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011287 /**
11288 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11289 * the platform. This event will invoke {@link
11290 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11291 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011292 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011293 */
11294 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11295
Cody Kesting73708bf2019-12-18 10:57:50 -080011296 private ConnectivityDiagnosticsHandler(Looper looper) {
11297 super(looper);
11298 }
11299
11300 @Override
11301 public void handleMessage(Message msg) {
11302 switch (msg.what) {
11303 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11304 handleRegisterConnectivityDiagnosticsCallback(
11305 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11306 break;
11307 }
11308 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11309 handleUnregisterConnectivityDiagnosticsCallback(
11310 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11311 break;
11312 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011313 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011314 final ConnectivityReportEvent reportEvent =
11315 (ConnectivityReportEvent) msg.obj;
11316
Aaron Huang959d3642021-01-21 15:47:41 +080011317 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011318 break;
11319 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011320 case EVENT_DATA_STALL_SUSPECTED: {
11321 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011322 final Pair<Long, PersistableBundle> arg =
11323 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011324 if (nai == null) break;
11325
Aaron Huang959d3642021-01-21 15:47:41 +080011326 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011327 break;
11328 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011329 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011330 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011331 break;
11332 }
11333 default: {
11334 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11335 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011336 }
11337 }
11338 }
11339
11340 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11341 @VisibleForTesting
11342 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11343 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11344 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011345 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011346
11347 @VisibleForTesting
11348 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011349 @NonNull IConnectivityDiagnosticsCallback cb,
11350 @NonNull NetworkRequestInfo nri,
11351 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011352 mCb = cb;
11353 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011354 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011355 }
11356
11357 @Override
11358 public void binderDied() {
11359 log("ConnectivityDiagnosticsCallback IBinder died.");
11360 unregisterConnectivityDiagnosticsCallback(mCb);
11361 }
11362 }
11363
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011364 /**
11365 * Class used for sending information from {@link
11366 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11367 */
11368 private static class NetworkTestedResults {
11369 private final int mNetId;
11370 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011371 @Nullable private final String mRedirectUrl;
11372
11373 private NetworkTestedResults(
11374 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11375 mNetId = netId;
11376 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011377 mRedirectUrl = redirectUrl;
11378 }
11379 }
11380
11381 /**
11382 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11383 * ConnectivityDiagnosticsHandler}.
11384 */
11385 private static class ConnectivityReportEvent {
11386 private final long mTimestampMillis;
11387 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011388 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011389
Aaron Huang959d3642021-01-21 15:47:41 +080011390 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11391 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011392 mTimestampMillis = timestampMillis;
11393 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011394 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011395 }
11396 }
11397
Cody Kestingf1120be2020-08-03 18:01:40 -070011398 /**
11399 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11400 * ConnectivityDiagnosticsHandler}.
11401 */
11402 private static class ReportedNetworkConnectivityInfo {
11403 public final boolean hasConnectivity;
11404 public final boolean isNetworkRevalidating;
11405 public final int reporterUid;
11406 @NonNull public final NetworkAgentInfo nai;
11407
11408 private ReportedNetworkConnectivityInfo(
11409 boolean hasConnectivity,
11410 boolean isNetworkRevalidating,
11411 int reporterUid,
11412 @NonNull NetworkAgentInfo nai) {
11413 this.hasConnectivity = hasConnectivity;
11414 this.isNetworkRevalidating = isNetworkRevalidating;
11415 this.reporterUid = reporterUid;
11416 this.nai = nai;
11417 }
11418 }
11419
Cody Kesting73708bf2019-12-18 10:57:50 -080011420 private void handleRegisterConnectivityDiagnosticsCallback(
11421 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11422 ensureRunningOnConnectivityServiceThread();
11423
11424 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011425 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011426 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11427
James Mattis64b8b0f2020-11-24 17:40:49 -080011428 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11429 // confusing for these networks to change when an NRI is satisfied in another layer.
11430 if (nri.isMultilayerRequest()) {
11431 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11432 + "network requests.");
11433 }
11434
Cody Kesting73708bf2019-12-18 10:57:50 -080011435 // This means that the client registered the same callback multiple times. Do
11436 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011437 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011438 if (VDBG) log("Diagnostics callback is already registered");
11439
11440 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11441 // incremented when the NetworkRequestInfo is created as part of
11442 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011443 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011444 return;
11445 }
11446
Cody Kesting31f1ff62020-03-05 10:46:02 -080011447 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011448
11449 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011450 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011451 } catch (RemoteException e) {
11452 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011453 return;
11454 }
11455
11456 // Once registered, provide ConnectivityReports for matching Networks
11457 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11458 synchronized (mNetworkForNetId) {
11459 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11460 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011461 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11462 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011463 matchingNetworks.add(nai);
11464 }
11465 }
11466 }
11467 for (final NetworkAgentInfo nai : matchingNetworks) {
11468 final ConnectivityReport report = nai.getConnectivityReport();
11469 if (report == null) {
11470 continue;
11471 }
11472 if (!checkConnectivityDiagnosticsPermissions(
11473 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11474 continue;
11475 }
11476
11477 try {
11478 cb.onConnectivityReportAvailable(report);
11479 } catch (RemoteException e) {
11480 // Exception while sending the ConnectivityReport. Move on to the next network.
11481 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011482 }
11483 }
11484
11485 private void handleUnregisterConnectivityDiagnosticsCallback(
11486 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11487 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011488 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011489
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011490 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11491 mConnectivityDiagnosticsCallbacks.remove(iCb);
11492 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011493 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11494 return;
11495 }
11496
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011497 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011498
Cody Kesting70fa2b22020-12-02 12:16:56 -080011499 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11500 // (if the Binder died)
11501 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11502 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011503 return;
11504 }
11505
Cody Kesting46cb1672020-03-04 13:35:20 -080011506 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11507 // incremented when the NetworkRequestInfo is created as part of
11508 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011509 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011510
Cody Kesting31f1ff62020-03-05 10:46:02 -080011511 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011512 }
11513
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011514 private void handleNetworkTestedWithExtras(
11515 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11516 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011517 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011518 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011519 final ConnectivityReport report =
11520 new ConnectivityReport(
11521 reportEvent.mNai.network,
11522 reportEvent.mTimestampMillis,
11523 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011524 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011525 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011526 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011527
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011528 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011529 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011530 for (final IConnectivityDiagnosticsCallback cb : results) {
11531 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011532 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011533 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011534 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011535 }
11536 }
11537 }
11538
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011539 private void handleDataStallSuspected(
11540 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11541 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011542 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011543 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011544 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011545 new DataStallReport(
11546 nai.network,
11547 timestampMillis,
11548 detectionMethod,
11549 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011550 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011551 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011552 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011553 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011554 for (final IConnectivityDiagnosticsCallback cb : results) {
11555 try {
11556 cb.onDataStallSuspected(report);
11557 } catch (RemoteException ex) {
11558 loge("Error invoking onDataStallSuspected", ex);
11559 }
11560 }
11561 }
11562
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011563 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011564 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11565 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11566 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11567
11568 // If the Network is being re-validated as a result of this call to
11569 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11570 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011571 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011572 getMatchingPermissionedCallbacks(
11573 nai,
11574 reportedNetworkConnectivityInfo.isNetworkRevalidating
11575 ? Process.INVALID_UID
11576 : reportedNetworkConnectivityInfo.reporterUid);
11577
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011578 for (final IConnectivityDiagnosticsCallback cb : results) {
11579 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011580 cb.onNetworkConnectivityReported(
11581 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011582 } catch (RemoteException ex) {
11583 loge("Error invoking onNetworkConnectivityReported", ex);
11584 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011585
11586 // If the Network isn't re-validating, also provide the cached report. If there is no
11587 // cached report, the Network is still being validated and a report will be sent once
11588 // validation is complete. Note that networks which never undergo validation will still
11589 // have a cached ConnectivityReport with RESULT_SKIPPED.
11590 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11591 try {
11592 cb.onConnectivityReportAvailable(cachedReport);
11593 } catch (RemoteException ex) {
11594 loge("Error invoking onConnectivityReportAvailable", ex);
11595 }
11596 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011597 }
11598 }
11599
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011600 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011601 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11602 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011603 sanitized.setUids(null);
11604 sanitized.setAdministratorUids(new int[0]);
11605 sanitized.setOwnerUid(Process.INVALID_UID);
11606 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011607 }
11608
Cody Kestingf1120be2020-08-03 18:01:40 -070011609 /**
11610 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11611 *
11612 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11613 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011614 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011615 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011616 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011617 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011618 mConnectivityDiagnosticsCallbacks.entrySet()) {
11619 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11620 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011621
James Mattis64b8b0f2020-11-24 17:40:49 -080011622 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011623 if (!nai.satisfies(nri.mRequests.get(0))) {
11624 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011625 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011626
11627 // UID for this callback must either be:
11628 // - INVALID_UID (which sends callbacks to all UIDs), or
11629 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11630 // notified as a result)
11631 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11632 continue;
11633 }
11634
11635 if (!checkConnectivityDiagnosticsPermissions(
11636 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11637 continue;
11638 }
11639
11640 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011641 }
11642 return results;
11643 }
11644
Cody Kesting7474f672021-05-11 14:22:40 -070011645 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11646 @NonNull NetworkAgentInfo nai) {
11647 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11648 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11649 }
11650
Cody Kesting160ef392021-05-05 13:17:22 -070011651 private boolean hasLocationPermission(String packageName, int uid) {
11652 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11653 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11654 // call in a try-catch.
11655 try {
11656 if (!mLocationPermissionChecker.checkLocationPermission(
11657 packageName, null /* featureId */, uid, null /* message */)) {
11658 return false;
11659 }
11660 } catch (SecurityException e) {
11661 return false;
11662 }
11663
11664 return true;
11665 }
11666
11667 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11668 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011669 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011670 && virtual.networkCapabilities.getOwnerUid() == uid
11671 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11672 return true;
11673 }
11674 }
11675
11676 return false;
11677 }
11678
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011679 @VisibleForTesting
11680 boolean checkConnectivityDiagnosticsPermissions(
11681 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11682 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11683 return true;
11684 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011685 if (mAllowSysUiConnectivityReports
Chris Göllnercc962022023-12-26 09:55:32 +000011686 && checkSystemBarServicePermission(callbackPid, callbackUid)) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011687 return true;
11688 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011689
Cody Kesting160ef392021-05-05 13:17:22 -070011690 // Administrator UIDs also contains the Owner UID
11691 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11692 if (!CollectionUtils.contains(administratorUids, callbackUid)
11693 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011694 return false;
11695 }
11696
Cody Kesting7474f672021-05-11 14:22:40 -070011697 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11698 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011699 }
11700
Cody Kestingd199a9d2019-12-17 12:55:28 -080011701 @Override
11702 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011703 @NonNull IConnectivityDiagnosticsCallback callback,
11704 @NonNull NetworkRequest request,
11705 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011706 Objects.requireNonNull(callback, "callback must not be null");
11707 Objects.requireNonNull(request, "request must not be null");
11708 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11709
Cody Kesting73708bf2019-12-18 10:57:50 -080011710 if (request.legacyType != TYPE_NONE) {
11711 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11712 + " Please use NetworkCapabilities instead.");
11713 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011714 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011715 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011716
11717 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11718 // and administrator uids to be safe.
11719 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011720 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011721
11722 final NetworkRequest requestWithId =
11723 new NetworkRequest(
11724 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11725
11726 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11727 //
11728 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11729 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11730 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011731 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011732 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011733 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011734
11735 mConnectivityDiagnosticsHandler.sendMessage(
11736 mConnectivityDiagnosticsHandler.obtainMessage(
11737 ConnectivityDiagnosticsHandler
11738 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11739 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011740 }
11741
11742 @Override
11743 public void unregisterConnectivityDiagnosticsCallback(
11744 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011745 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011746 mConnectivityDiagnosticsHandler.sendMessage(
11747 mConnectivityDiagnosticsHandler.obtainMessage(
11748 ConnectivityDiagnosticsHandler
11749 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011750 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011751 0,
11752 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011753 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011754
Yan Yanfe96dde2022-12-05 23:00:01 +000011755 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11756 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11757 if (underlyingNetworks == null) return false;
11758
11759 for (Network network : underlyingNetworks) {
11760 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11761 return true;
11762 }
11763 }
11764 return false;
11765 }
11766
Cody Kestingf53a0752020-04-15 12:33:28 -070011767 @Override
11768 public void simulateDataStall(int detectionMethod, long timestampMillis,
11769 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011770 Objects.requireNonNull(network, "network must not be null");
11771 Objects.requireNonNull(extras, "extras must not be null");
11772
paulhu3ffffe72021-09-16 10:15:22 +080011773 enforceAnyPermissionOf(mContext,
11774 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011775 android.Manifest.permission.NETWORK_STACK);
11776 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011777 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11778 throw new SecurityException(
11779 "Data Stall simulation is only possible for test networks or networks built on"
11780 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011781 }
11782
11783 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011784 if (nai == null
11785 || (nai.creatorUid != mDeps.getCallingUid()
11786 && nai.creatorUid != Process.SYSTEM_UID)) {
11787 throw new SecurityException(
11788 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011789 }
11790
Cody Kesting652e3ec2020-05-21 12:08:21 -070011791 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11792 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11793 // Data Stall information as a DataStallReportParcelable and passing to
11794 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11795 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011796 final DataStallReportParcelable p = new DataStallReportParcelable();
11797 p.timestampMillis = timestampMillis;
11798 p.detectionMethod = detectionMethod;
11799
11800 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11801 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11802 }
11803 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11804 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11805 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11806 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11807 }
11808
Serik Beketayevec8ad212020-12-07 22:43:07 -080011809 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011810 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011811
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011812 /**
11813 * Class to hold the information for network activity change event from idle timers
11814 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11815 */
11816 private static final class NetworkActivityParams {
11817 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011818 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
11819 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011820 public final int label;
11821 public final long timestampNs;
11822 // Uid represents the uid that was responsible for waking the radio.
11823 // -1 for no uid and uid is -1 if isActive is false.
11824 public final int uid;
11825
11826 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11827 this.isActive = isActive;
11828 this.label = label;
11829 this.timestampNs = timestampNs;
11830 this.uid = uid;
11831 }
11832 }
11833
lucaslin66f44212021-02-23 01:12:55 +080011834 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11835 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011836 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011837 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011838 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11839 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011840 }
lucaslin37a16d92021-01-21 19:48:09 +080011841
11842 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011843 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011844 mHandler.post(() -> {
11845 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011846 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011847 }
11848 });
lucaslin37a16d92021-01-21 19:48:09 +080011849 }
11850
11851 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011852 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011853 mHandler.post(() -> {
11854 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011855 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011856 }
11857 });
lucaslin66f44212021-02-23 01:12:55 +080011858 }
11859 }
11860
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011861 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080011862 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11863
11864 /**
11865 * Class used for updating network activity tracking with netd and notify network activity
11866 * changes.
11867 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011868 @VisibleForTesting
11869 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011870 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011871 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011872 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011873 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011874 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11875 new RemoteCallbackList<>();
11876 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011877 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011878 // If there is no default network, default network is considered active to keep the existing
11879 // behavior. Initial value is used until first connect to the default network.
11880 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011881 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011882 // Key is netId. Value is configured idle timer information.
11883 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011884 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011885 // Store netIds of Wi-Fi networks whose idletimers report that they are active
11886 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
11887 // Store netIds of cellular networks whose idletimers report that they are active
11888 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011889
Chalard Jean46bfbf02022-02-02 00:56:25 +090011890 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011891 public final int timeout;
11892 public final int transportType;
11893
11894 IdleTimerParams(int timeout, int transport) {
11895 this.timeout = timeout;
11896 this.transportType = transport;
11897 }
11898 }
11899
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011900 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011901 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011902 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011903 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011904 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011905 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011906 }
11907
11908 private void ensureRunningOnConnectivityServiceThread() {
11909 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11910 throw new IllegalStateException("Not running on ConnectivityService thread: "
11911 + Thread.currentThread().getName());
11912 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011913 }
11914
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011915 /**
11916 * Update network activity and call BatteryStats to update radio power state if the
11917 * mobile or Wi-Fi activity is changed.
11918 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
11919 * mobile network is active since BatteryStatsService only maintains a single power state
11920 * for the mobile network.
11921 * The Wi-Fi network is also the same.
11922 *
11923 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
11924 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
11925 * transports.
11926 */
11927 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
11928 final boolean isActive, final int uid) {
11929 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
11930 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
11931 + transportType);
11932 return;
11933 }
11934 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
11935 ? mActiveWifiNetworks : mActiveCellularNetworks;
11936
11937 final boolean wasEmpty = activeNetworks.isEmpty();
11938 if (isActive) {
11939 activeNetworks.add(netId);
11940 } else {
11941 activeNetworks.remove(netId);
11942 }
11943
11944 if (wasEmpty != activeNetworks.isEmpty()) {
11945 updateRadioPowerState(isActive, transportType, uid);
11946 }
11947 }
11948
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011949 private void handleDefaultNetworkActivity(final int transportType,
11950 final boolean isActive, final long timestampNs) {
11951 mIsDefaultNetworkActive = isActive;
11952 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
11953 isActive, timestampNs);
11954 if (isActive) {
11955 reportNetworkActive();
11956 }
11957 }
11958
11959 private void handleReportNetworkActivityWithNetIdLabel(
11960 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011961 final int netId = activityParams.label;
11962 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011963 if (idleTimerParams == null) {
11964 // This network activity change is not tracked anymore
11965 // This can happen if netd callback post activity change event message but idle
11966 // timer is removed before processing this message.
11967 return;
11968 }
11969 // TODO: if a network changes transports, storing the transport type in the
11970 // IdleTimerParams is not correct. Consider getting it from the network's
11971 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090011972 final int transportType = idleTimerParams.transportType;
11973 maybeUpdateRadioPowerState(netId, transportType,
11974 activityParams.isActive, activityParams.uid);
11975
11976 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
11977 // This activity change is not for the default network.
11978 return;
11979 }
11980
11981 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011982 activityParams.timestampNs);
11983 }
11984
11985 private void handleReportNetworkActivityWithTransportTypeLabel(
11986 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011987 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011988 // This activity change is not for the current default network.
11989 // This can happen if netd callback post activity change event message but
11990 // the default network is lost before processing this message.
11991 return;
11992 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090011993 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
11994 activityParams.timestampNs);
11995 }
11996
11997 /**
11998 * Handle network activity change
11999 */
12000 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
12001 ensureRunningOnConnectivityServiceThread();
12002 if (mTrackMultiNetworkActivities) {
12003 handleReportNetworkActivityWithNetIdLabel(activityParams);
12004 } else {
12005 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080012006 }
12007 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012008
lucaslin1193a5d2021-01-21 02:04:15 +080012009 private void reportNetworkActive() {
12010 final int length = mNetworkActivityListeners.beginBroadcast();
12011 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
12012 try {
12013 for (int i = 0; i < length; i++) {
12014 try {
12015 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
12016 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012017 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080012018 }
12019 }
12020 } finally {
12021 mNetworkActivityListeners.finishBroadcast();
12022 }
12023 }
12024
lucaslin1a8b4c62021-01-21 02:02:55 +080012025 // This is deprecated and only to support legacy use cases.
12026 private int transportTypeToLegacyType(int type) {
12027 switch (type) {
12028 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012029 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080012030 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012031 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080012032 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012033 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080012034 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012035 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080012036 default:
12037 loge("Unexpected transport in transportTypeToLegacyType: " + type);
12038 }
12039 return ConnectivityManager.TYPE_NONE;
12040 }
12041
12042 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12043 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12044 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12045 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12046 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12047 final long ident = Binder.clearCallingIdentity();
12048 try {
12049 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12050 RECEIVE_DATA_ACTIVITY_CHANGE,
12051 null /* resultReceiver */,
12052 null /* scheduler */,
12053 0 /* initialCode */,
12054 null /* initialData */,
12055 null /* initialExtra */);
12056 } finally {
12057 Binder.restoreCallingIdentity(ident);
12058 }
12059 }
12060
12061 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012062 * Get idle timer label
12063 */
12064 @VisibleForTesting
12065 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12066 final int netId, final int transportType) {
12067 return trackMultiNetworkActivities ? netId : transportType;
12068 }
12069
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012070 private boolean maybeCreateIdleTimer(
12071 String iface, int netId, int timeout, int transportType) {
12072 if (timeout <= 0 || iface == null) return false;
12073 try {
12074 final String label = Integer.toString(getIdleTimerLabel(
12075 mTrackMultiNetworkActivities, netId, transportType));
12076 mNetd.idletimerAddInterface(iface, timeout, label);
12077 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12078 return true;
12079 } catch (Exception e) {
12080 loge("Exception in createIdleTimer", e);
12081 return false;
12082 }
12083 }
12084
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012085 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012086 * Setup data activity tracking for the given network.
12087 *
12088 * Every {@code setupDataActivityTracking} should be paired with a
12089 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012090 *
12091 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012092 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012093 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012094 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012095 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012096 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012097
12098 final int timeout;
12099 final int type;
12100
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012101 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12102 // Do not track VPN network.
12103 return false;
12104 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012105 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12106 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012107 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012108 10);
12109 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12110 } else if (networkAgent.networkCapabilities.hasTransport(
12111 NetworkCapabilities.TRANSPORT_WIFI)) {
12112 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012113 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012114 15);
12115 type = NetworkCapabilities.TRANSPORT_WIFI;
12116 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012117 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012118 }
12119
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012120 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12121 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12122 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12123 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12124 // state only about a network that has an idletimer.
12125 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012126 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012127 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012128 }
12129
12130 /**
12131 * Remove data activity tracking when network disconnects.
12132 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012133 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12134 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 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12138
lucaslinb961efc2021-01-21 02:03:17 +080012139 if (iface == null) return;
12140
12141 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012142 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12143 // Do not track VPN network.
12144 return;
12145 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012146 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12147 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12148 type = NetworkCapabilities.TRANSPORT_WIFI;
12149 } else {
12150 return; // do not track any other networks
12151 }
12152
12153 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012154 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012155 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012156 if (params == null) {
12157 // IdleTimer is not added if the configured timeout is 0 or negative value
12158 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012159 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012160 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012161 final String label = Integer.toString(getIdleTimerLabel(
12162 mTrackMultiNetworkActivities, netId, params.transportType));
12163 // The call fails silently if no idle timer setup for this interface
12164 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012165 } catch (Exception e) {
12166 // You shall not crash!
12167 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012168 }
12169 }
12170
Motomu Utsumi6225d572023-05-29 15:08:57 +090012171 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12172 boolean hasIdleTimer) {
12173 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012174 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012175 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012176 // If only the default network is tracked, callbacks are called only when the
12177 // network has the idle timer.
12178 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012179 reportNetworkActive();
12180 }
12181 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012182 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012183 // If there is no default network, default network is considered active to keep the
12184 // existing behavior.
12185 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090012186 }
12187 }
12188
lucaslin1a8b4c62021-01-21 02:02:55 +080012189 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012190 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012191 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012192 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012193 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012194 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012195 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12196 // first connected and remove when the network is disconnected.
12197 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12198 // becomes the default network and remove when the network becomes no longer the default
12199 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012200 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012201 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012202 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012203 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012204 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012205 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012206 removeDataActivityTracking(oldNetwork);
12207 }
12208 }
lucaslinb961efc2021-01-21 02:03:17 +080012209
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012210 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012211 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12212 switch (transportType) {
12213 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012214 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012215 break;
12216 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012217 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012218 break;
12219 default:
12220 logw("Untracked transport type:" + transportType);
12221 }
12222 }
lucaslin1193a5d2021-01-21 02:04:15 +080012223
12224 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012225 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012226 }
12227
12228 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12229 mNetworkActivityListeners.register(l);
12230 }
12231
12232 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12233 mNetworkActivityListeners.unregister(l);
12234 }
lucaslin012f7a12021-01-21 02:04:35 +080012235
12236 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012237 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012238 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012239 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012240 pw.println("Idle timers:");
12241 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012242 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12243 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12244 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012245 pw.print(" timeout="); pw.print(params.timeout);
12246 pw.print(" type="); pw.println(params.transportType);
12247 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012248 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12249 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012250 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012251 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12252 // be accessed from handler thread, except dump(). As dump() is never called in
12253 // normal usage, it would be needlessly expensive to lock the collection only for
12254 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012255 // So catching the exception and logging.
12256 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012257 }
12258 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012259 }
James Mattis47db0582021-01-01 14:13:35 -080012260
Daniel Brightf9e945b2020-06-15 16:10:01 -070012261 /**
12262 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12263 *
12264 * @param socketInfo the socket information
12265 * @param callback the callback to register
12266 */
12267 @Override
12268 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12269 @NonNull final IQosCallback callback) {
12270 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12271 if (nai == null || nai.networkCapabilities == null) {
12272 try {
12273 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12274 } catch (final RemoteException ex) {
12275 loge("registerQosCallbackInternal: RemoteException", ex);
12276 }
12277 return;
12278 }
12279 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12280 }
12281
12282 /**
12283 * Register a {@link IQosCallback} with base {@link QosFilter}.
12284 *
12285 * @param filter the filter to register
12286 * @param callback the callback to register
12287 * @param nai the agent information related to the filter's network
12288 */
12289 @VisibleForTesting
12290 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12291 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012292 Objects.requireNonNull(filter, "filter must be non-null");
12293 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012294
12295 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012296 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12297 // on this network is unregistered when the app loses permission or b) no QoS
12298 // callbacks are sent for restricted networks unless the app currently has permission
12299 // to access restricted networks.
12300 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012301 }
12302 mQosCallbackTracker.registerCallback(callback, filter, nai);
12303 }
12304
12305 /**
12306 * Unregisters the given callback.
12307 *
12308 * @param callback the callback to unregister
12309 */
12310 @Override
12311 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012312 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012313 mQosCallbackTracker.unregisterCallback(callback);
12314 }
James Mattis47db0582021-01-01 14:13:35 -080012315
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012316 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12317 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12318 // Enterprise device can be fully managed like device owner and such use case
12319 // also should be supported. Calling app check for work profile and fully managed device
12320 // is already done in DevicePolicyManager.
12321 // This check is an extra caution to be sure device is fully managed or not.
12322 final UserManager um = mContext.getSystemService(UserManager.class);
12323 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12324 if (um.isManagedProfile(profile.getIdentifier())) {
12325 return true;
12326 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012327 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012328 return false;
12329 }
12330
James Mattis45d81842021-01-10 14:24:24 -080012331 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012332 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012333 *
12334 * See the documentation for the individual preferences for a description of the supported
12335 * behaviors.
12336 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012337 * @param profile If the device owner is set, any profile is allowed.
12338 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012339 * @param preferences the list of profile network preferences for the
12340 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012341 * @param listener an optional listener to listen for completion of the operation.
12342 */
12343 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012344 public void setProfileNetworkPreferences(
12345 @NonNull final UserHandle profile,
12346 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012347 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012348 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012349 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012350
12351 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012352 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12353 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12354 .build();
12355 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012356 }
12357
paulhu3ffffe72021-09-16 10:15:22 +080012358 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012359 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012360 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012361 }
12362 if (profile.getIdentifier() < 0) {
12363 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12364 + "UserHandle.CURRENT not supported)");
12365 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012366 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12367 throw new IllegalArgumentException("Profile must be a managed profile "
12368 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012369 }
paulhuaa0743d2021-05-26 21:56:03 +080012370
Chalard Jean0606fc82022-12-14 20:34:43 +090012371 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012372 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012373 for (final ProfileNetworkPreference preference : preferences) {
12374 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012375 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012376 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012377 switch (preference.getPreference()) {
12378 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12379 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012380 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012381 if (preference.getPreferenceEnterpriseId() != 0) {
12382 throw new IllegalArgumentException(
12383 "Invalid enterprise identifier in setProfileNetworkPreferences");
12384 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012385 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012386 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12387 blockingNonEnterprise = true;
12388 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012389 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12390 allowFallback = false;
12391 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012392 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012393 // This code is needed even though there is a check later on,
12394 // because isRangeAlreadyInPreferenceList assumes that every preference
12395 // has a UID list.
12396 if (hasDefaultPreference) {
12397 throw new IllegalArgumentException(
12398 "Default profile preference should not be set along with other "
12399 + "preference");
12400 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012401 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12402 throw new IllegalArgumentException(
12403 "Invalid enterprise identifier in setProfileNetworkPreferences");
12404 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012405 final Set<UidRange> uidRangeSet =
12406 getUidListToBeAppliedForNetworkPreference(profile, preference);
12407 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12408 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12409 } else {
12410 throw new IllegalArgumentException(
12411 "Overlapping uid range in setProfileNetworkPreferences");
12412 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012413 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012414 nc.addEnterpriseId(
12415 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012416 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12417 break;
12418 default:
12419 throw new IllegalArgumentException(
12420 "Invalid preference in setProfileNetworkPreferences");
12421 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012422 preferenceList.add(new ProfileNetworkPreferenceInfo(
12423 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012424 if (hasDefaultPreference && preferenceList.size() > 1) {
12425 throw new IllegalArgumentException(
12426 "Default profile preference should not be set along with other preference");
12427 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012428 }
12429 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012430 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012431 }
12432
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012433 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12434 @NonNull final UserHandle profile,
12435 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12436 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012437 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12438 profileNetworkPreference.getIncludedUids());
12439
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012440 if (uidRangeSet.size() > 0) {
12441 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12442 throw new IllegalArgumentException(
12443 "Allow uid range is outside the uid range of profile.");
12444 }
12445 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012446 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012447 profileNetworkPreference.getExcludedUids());
12448 if (disallowUidRangeSet.size() > 0) {
12449 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12450 throw new IllegalArgumentException(
12451 "disallow uid range is outside the uid range of profile.");
12452 }
12453 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12454 disallowUidRangeSet);
12455 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012456 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012457 uidRangeSet.add(profileUids);
12458 }
12459 }
12460 return uidRangeSet;
12461 }
12462
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012463 private boolean isEnterpriseIdentifierValid(
12464 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012465 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012466 return true;
12467 }
12468 return false;
12469 }
12470
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012471 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012472 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012473 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012474 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012475 // The NRI for a user should contain the request for capabilities.
12476 // If fallback to default network is needed then NRI should include
12477 // the request for the default network. Create an image of it to
12478 // have the correct UIDs in it (also a request can only be part of one NRI, because
12479 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012480 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12481 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012482 if (pref.allowFallback) {
12483 nrs.add(createDefaultInternetRequestForTransport(
12484 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12485 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012486 if (VDBG) {
12487 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12488 pref.capabilities.getUids()));
12489 }
12490
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012491 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012492 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012493 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012494 result.add(nri);
12495 }
12496 return result;
12497 }
12498
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012499 /**
12500 * Compare if the given UID range sets have the same UIDs.
12501 *
12502 */
12503 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012504 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012505 @NonNull Set<UidRange> uidRangeSet) {
12506 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12507 return false;
12508 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012509 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012510 if (UidRangeUtils.doesRangeSetOverlap(
12511 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12512 return true;
12513 }
12514 }
12515 return false;
12516 }
12517
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012518 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012519 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012520 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012521 /*
12522 * handleSetProfileNetworkPreference is always called for single user.
12523 * preferenceList only contains preferences for different uids within the same user
12524 * (enforced by getUidListToBeAppliedForNetworkPreference).
12525 * Clear all the existing preferences for the user before applying new preferences.
12526 *
12527 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012528 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12529 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012530 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12531 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012532
paulhu74128522021-09-28 02:29:03 +000012533 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12534 addPerAppDefaultNetworkRequests(
12535 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012536 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012537
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012538 // Finally, rematch.
12539 rematchAllNetworksAndRequests();
12540
12541 if (null != listener) {
12542 try {
12543 listener.onComplete();
12544 } catch (RemoteException e) {
12545 loge("Listener for setProfileNetworkPreference has died");
12546 }
12547 }
12548 }
12549
paulhu51f77dc2021-06-07 02:34:20 +000012550 @VisibleForTesting
12551 @NonNull
12552 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12553 @NonNull final Set<Integer> uids) {
12554 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12555 if (uids.size() == 0) {
12556 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12557 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12558 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12559 return nris;
12560 }
12561
12562 final List<NetworkRequest> requests = new ArrayList<>();
12563 // The NRI should be comprised of two layers:
12564 // - The request for the mobile network preferred.
12565 // - The request for the default network, for fallback.
12566 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012567 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012568 requests.add(createDefaultInternetRequestForTransport(
12569 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12570 final Set<UidRange> ranges = new ArraySet<>();
12571 for (final int uid : uids) {
12572 ranges.add(new UidRange(uid, uid));
12573 }
12574 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012575 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012576 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012577 return nris;
12578 }
12579
12580 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012581 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012582 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12583 addPerAppDefaultNetworkRequests(
12584 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012585 // Finally, rematch.
12586 rematchAllNetworksAndRequests();
12587 }
12588
Patrick Rohr2857ac42022-01-21 14:58:16 +010012589 private void handleIngressRateLimitChanged() {
12590 final long oldIngressRateLimit = mIngressRateLimit;
12591 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12592 mContext);
12593 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12594 if (canNetworkBeRateLimited(networkAgent)) {
12595 // If rate limit has previously been enabled, remove the old limit first.
12596 if (oldIngressRateLimit >= 0) {
12597 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12598 }
12599 if (mIngressRateLimit >= 0) {
12600 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12601 mIngressRateLimit);
12602 }
12603 }
12604 }
12605 }
12606
12607 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012608 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012609 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012610
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012611 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12612 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12613 // internet connectivity can be rate limited.
12614 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12615 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012616 return false;
12617 }
12618
12619 final String iface = networkAgent.linkProperties.getInterfaceName();
12620 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012621 // This may happen in tests, but if there is no interface then there is nothing that
12622 // can be rate limited.
12623 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012624 return false;
12625 }
12626 return true;
12627 }
12628
James Mattis45d81842021-01-10 14:24:24 -080012629 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012630 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12631 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012632 }
12633
12634 /**
12635 * Used by automotive devices to set the network preferences used to direct traffic at an
12636 * application level as per the given OemNetworkPreferences. An example use-case would be an
12637 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12638 * vehicle via a particular network.
12639 *
12640 * Calling this will overwrite the existing preference.
12641 *
James Mattisda32cfe2021-01-26 16:23:52 -080012642 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012643 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012644 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012645 */
James Mattis47db0582021-01-01 14:13:35 -080012646 @Override
James Mattis45d81842021-01-10 14:24:24 -080012647 public void setOemNetworkPreference(
12648 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012649 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012650
James Mattisfa270db2021-05-31 17:11:10 -070012651 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12652 // Only bypass the permission/device checks if this is a valid test request.
12653 if (isValidTestOemNetworkPreference(preference)) {
12654 enforceManageTestNetworksPermission();
12655 } else {
12656 enforceAutomotiveDevice();
12657 enforceOemNetworkPreferencesPermission();
12658 validateOemNetworkPreferences(preference);
12659 }
James Mattis45d81842021-01-10 14:24:24 -080012660
James Mattis45d81842021-01-10 14:24:24 -080012661 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12662 new Pair<>(preference, listener)));
12663 }
12664
James Mattisfa270db2021-05-31 17:11:10 -070012665 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012666 * Sets the specified UIDs to get/receive the VPN as the only default network.
12667 *
12668 * Calling this will overwrite the existing network preference for this session, and the
12669 * specified UIDs won't get any default network when no VPN is connected.
12670 *
12671 * @param session The VPN session which manages the passed UIDs.
12672 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12673 * setting for this session if the array is empty. Null is not allowed, the
12674 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12675 * @hide
12676 */
12677 @Override
12678 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12679 Objects.requireNonNull(ranges);
12680 enforceNetworkStackOrSettingsPermission();
12681 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12682 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12683 throw new IllegalArgumentException(
12684 "setVpnNetworkPreference: Passed UID ranges overlap");
12685 }
12686
12687 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12688 new VpnNetworkPreferenceInfo(session,
12689 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12690 }
12691
12692 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12693 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12694
12695 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12696 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12697
12698 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12699 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12700 // Finally, rematch.
12701 rematchAllNetworksAndRequests();
12702 }
12703
12704 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12705 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12706 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12707 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12708 final List<NetworkRequest> requests = new ArrayList<>();
12709 // Request VPN only, so other networks won't be the fallback options when VPN is not
12710 // connected temporarily.
12711 requests.add(createVpnRequest());
12712 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12713 setNetworkRequestUids(requests, uidRanges);
12714 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12715 }
12716 return nris;
12717 }
12718
12719 /**
James Mattisfa270db2021-05-31 17:11:10 -070012720 * Check the validity of an OEM network preference to be used for testing purposes.
12721 * @param preference the preference to validate
12722 * @return true if this is a valid OEM network preference test request.
12723 */
12724 private boolean isValidTestOemNetworkPreference(
12725 @NonNull final OemNetworkPreferences preference) {
12726 // Allow for clearing of an existing OemNetworkPreference used for testing.
12727 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12728 // changes after this check is complete. This is an unlikely scenario as calling of this API
12729 // is controlled by the OEM therefore the added complexity is not worth adding given those
12730 // circumstances. That said, it is an edge case to be aware of hence this comment.
12731 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12732 && isTestOemNetworkPreference(mOemNetworkPreferences);
12733 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12734 }
12735
12736 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12737 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12738 return prefMap.size() == 1
12739 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12740 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12741 }
12742
James Mattis45d81842021-01-10 14:24:24 -080012743 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12744 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12745 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012746 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12747 throw new IllegalArgumentException(
12748 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12749 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012750 }
12751 }
12752 }
12753
12754 private void handleSetOemNetworkPreference(
12755 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012756 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012757 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12758 if (DBG) {
12759 log("set OEM network preferences :" + preference.toString());
12760 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012761
James Mattiscb1e0362021-04-06 17:07:42 -070012762 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012763 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12764 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12765 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012766 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012767
12768 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012769 try {
12770 listener.onComplete();
12771 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012772 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012773 }
James Mattis45d81842021-01-10 14:24:24 -080012774 }
12775 }
12776
paulhu74128522021-09-28 02:29:03 +000012777 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012778 // Skip the requests which are set by other network preference. Because the uid range rules
12779 // should stay in netd.
12780 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012781 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012782 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012783 }
12784
James Mattis3ce3d3c2021-02-09 18:18:28 -080012785 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12786 ensureRunningOnConnectivityServiceThread();
12787 mDefaultNetworkRequests.addAll(nris);
12788 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12789 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012790 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012791 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12792 nrisToRegister.addAll(
12793 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12794 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012795 }
12796
12797 /**
12798 * All current requests that are tracking the default network need to be assessed as to whether
12799 * or not the current set of per-application default requests will be changing their default
12800 * network. If so, those requests will need to be updated so that they will send callbacks for
12801 * default network changes at the appropriate time. Additionally, those requests tracking the
12802 * default that were previously updated by this flow will need to be reassessed.
12803 * @return the nris which will need to be updated.
12804 */
12805 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12806 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12807 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12808 // same nri in the map's values for each of its NetworkRequest objects.
12809 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012810 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012811 // Include this nri if it is currently being tracked.
12812 if (isPerAppTrackedNri(nri)) {
12813 defaultCallbackRequests.add(nri);
12814 continue;
12815 }
12816 // We only track callbacks for requests tracking the default.
12817 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12818 continue;
12819 }
12820 // Include this nri if it will be tracked by the new per-app default requests.
12821 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012822 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012823 if (isNriGoingToBeTracked) {
12824 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012825 }
12826 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012827 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012828 }
12829
James Mattis3ce3d3c2021-02-09 18:18:28 -080012830 /**
12831 * Create nris for those network requests that are currently tracking the default network that
12832 * are being controlled by a per-application default.
12833 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12834 * foundation when creating the nri. Important items include the calling uid's original
12835 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12836 * requests are assumed to have already been validated as needing to be updated.
12837 * @return the Set of nris to use when registering network requests.
12838 */
12839 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12840 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12841 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12842 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12843 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012844 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012845
Chalard Jean9473c982021-07-29 20:03:04 +090012846 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012847 if (trackingNri == mDefaultRequest) {
12848 callbackRequestsToRegister.add(new NetworkRequestInfo(
12849 callbackRequest,
12850 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12851 continue;
12852 }
12853
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012854 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012855 callbackRequestsToRegister.add(new NetworkRequestInfo(
12856 callbackRequest,
12857 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012858 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012859 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012860 }
12861 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012862 }
12863
Chalard Jean17215832021-03-01 14:06:28 +090012864 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12865 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012866 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012867 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012868 }
12869 }
12870
James Mattis45d81842021-01-10 14:24:24 -080012871 /**
12872 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12873 */
12874 @VisibleForTesting
12875 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012876 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012877 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012878 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012879 final SparseArray<Set<Integer>> uids =
12880 createUidsFromOemNetworkPreferences(preference);
12881 for (int i = 0; i < uids.size(); i++) {
12882 final int key = uids.keyAt(i);
12883 final Set<Integer> value = uids.valueAt(i);
12884 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12885 // No need to add an nri without any requests.
12886 if (0 == nri.mRequests.size()) {
12887 continue;
12888 }
12889 nris.add(nri);
12890 }
12891
12892 return nris;
12893 }
12894
12895 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12896 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012897 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012898 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012899 final List<UserHandle> users =
12900 mContext.getSystemService(UserManager.class).getUserHandles(true);
12901 if (null == users || users.size() == 0) {
12902 if (VDBG || DDBG) {
12903 log("No users currently available for setting the OEM network preference.");
12904 }
James Mattisb6b6a432021-06-01 22:30:36 -070012905 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012906 }
James Mattis45d81842021-01-10 14:24:24 -080012907 for (final Map.Entry<String, Integer> entry :
12908 preference.getNetworkPreferences().entrySet()) {
12909 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012910 // Add the rules for all users as this policy is device wide.
12911 for (final UserHandle user : users) {
12912 try {
12913 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12914 if (!prefToUids.contains(pref)) {
12915 prefToUids.put(pref, new ArraySet<>());
12916 }
12917 prefToUids.get(pref).add(uid);
12918 } catch (PackageManager.NameNotFoundException e) {
12919 // Although this may seem like an error scenario, it is ok that uninstalled
12920 // packages are sent on a network preference as the system will watch for
12921 // package installations associated with this network preference and update
12922 // accordingly. This is done to minimize race conditions on app install.
12923 continue;
James Mattis45d81842021-01-10 14:24:24 -080012924 }
James Mattis45d81842021-01-10 14:24:24 -080012925 }
12926 }
James Mattisb6b6a432021-06-01 22:30:36 -070012927 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012928 }
12929
12930 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12931 @OemNetworkPreferences.OemNetworkPreference final int preference,
12932 @NonNull final Set<Integer> uids) {
12933 final List<NetworkRequest> requests = new ArrayList<>();
12934 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12935 switch (preference) {
12936 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12937 requests.add(createUnmeteredNetworkRequest());
12938 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012939 requests.add(createDefaultInternetRequestForTransport(
12940 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012941 break;
12942 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12943 requests.add(createUnmeteredNetworkRequest());
12944 requests.add(createOemPaidNetworkRequest());
12945 break;
12946 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12947 requests.add(createOemPaidNetworkRequest());
12948 break;
12949 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12950 requests.add(createOemPrivateNetworkRequest());
12951 break;
James Mattisfa270db2021-05-31 17:11:10 -070012952 case OEM_NETWORK_PREFERENCE_TEST:
12953 requests.add(createUnmeteredNetworkRequest());
12954 requests.add(createTestNetworkRequest());
12955 requests.add(createDefaultRequest());
12956 break;
12957 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12958 requests.add(createTestNetworkRequest());
12959 break;
James Mattis45d81842021-01-10 14:24:24 -080012960 default:
12961 // This should never happen.
12962 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12963 + " called with invalid preference of " + preference);
12964 }
12965
James Mattisfa270db2021-05-31 17:11:10 -070012966 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012967 for (final int uid : uids) {
12968 ranges.add(new UidRange(uid, uid));
12969 }
12970 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012971 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012972 }
12973
12974 private NetworkRequest createUnmeteredNetworkRequest() {
12975 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12976 .addCapability(NET_CAPABILITY_NOT_METERED)
12977 .addCapability(NET_CAPABILITY_VALIDATED);
12978 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12979 }
12980
12981 private NetworkRequest createOemPaidNetworkRequest() {
12982 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12983 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12984 .addCapability(NET_CAPABILITY_OEM_PAID)
12985 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12986 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12987 }
12988
12989 private NetworkRequest createOemPrivateNetworkRequest() {
12990 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12991 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12992 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12993 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12994 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12995 }
12996
12997 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012998 final NetworkCapabilities netcap = new NetworkCapabilities();
12999 netcap.addCapability(NET_CAPABILITY_INTERNET);
13000 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
13001 return netcap;
13002 }
13003
13004 private NetworkRequest createTestNetworkRequest() {
13005 final NetworkCapabilities netcap = new NetworkCapabilities();
13006 netcap.clearAll();
13007 netcap.addTransportType(TRANSPORT_TEST);
13008 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080013009 }
James Mattis47db0582021-01-01 14:13:35 -080013010 }
markchien738ad912021-12-09 18:15:45 +080013011
Junyu Lai38c75032023-12-04 07:52:19 +000013012 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080013013 @Override
Junyu Laidf210362023-10-24 02:47:50 +000013014 public void setDataSaverEnabled(final boolean enable) {
13015 enforceNetworkStackOrSettingsPermission();
13016 try {
13017 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
13018 if (!ret) {
13019 throw new IllegalStateException("Error when changing iptables: " + enable);
13020 }
13021 } catch (RemoteException e) {
13022 // Lack of permission or binder errors.
13023 throw new IllegalStateException(e);
13024 }
Ken Chen24330172023-10-20 13:02:14 +080013025
13026 try {
13027 mBpfNetMaps.setDataSaverEnabled(enable);
13028 } catch (ServiceSpecificException | UnsupportedOperationException e) {
13029 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
13030 }
Junyu Laidf210362023-10-24 02:47:50 +000013031 }
13032
13033 @Override
markchien738ad912021-12-09 18:15:45 +080013034 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
13035 enforceNetworkStackOrSettingsPermission();
13036
13037 try {
13038 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013039 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013040 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013041 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013042 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013043 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013044 throw new IllegalStateException(e);
13045 }
13046 }
13047
13048 @Override
13049 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13050 enforceNetworkStackOrSettingsPermission();
13051
13052 try {
13053 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013054 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013055 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013056 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013057 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013058 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013059 throw new IllegalStateException(e);
13060 }
13061 }
markchiene1561fa2021-12-09 22:00:56 +080013062
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013063 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13064 throws PackageManager.NameNotFoundException {
13065 final PackageManager pm = mContext.getPackageManager();
13066 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13067 if (appId < Process.FIRST_APPLICATION_UID) {
13068 throw new RuntimeException("Can't set package firewall rule for system app "
13069 + packageName + " with appId " + appId);
13070 }
13071 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13072 final int uid = uh.getUid(appId);
13073 setUidFirewallRule(chain, uid, rule);
13074 }
13075 return appId;
13076 }
13077
markchiene1561fa2021-12-09 22:00:56 +080013078 @Override
markchien3c04e662022-03-22 16:29:56 +080013079 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013080 enforceNetworkStackOrSettingsPermission();
13081
markchien3c04e662022-03-22 16:29:56 +080013082 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13083 int firewallRule = getFirewallRuleType(chain, rule);
13084
13085 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13086 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13087 }
13088
markchiene1561fa2021-12-09 22:00:56 +080013089 try {
markchien3c04e662022-03-22 16:29:56 +080013090 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013091 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013092 throw new IllegalStateException(e);
13093 }
13094 }
markchien98a6f952022-01-13 23:43:53 +080013095
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013096 private int getPackageFirewallRule(final int chain, final String packageName)
13097 throws PackageManager.NameNotFoundException {
13098 final PackageManager pm = mContext.getPackageManager();
13099 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13100 return getUidFirewallRule(chain, appId);
13101 }
13102
Motomu Utsumi900b8062023-01-19 16:16:49 +090013103 @Override
13104 public int getUidFirewallRule(final int chain, final int uid) {
13105 enforceNetworkStackOrSettingsPermission();
13106 return mBpfNetMaps.getUidRule(chain, uid);
13107 }
13108
markchien3c04e662022-03-22 16:29:56 +080013109 private int getFirewallRuleType(int chain, int rule) {
13110 final int defaultRule;
13111 switch (chain) {
13112 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013113 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13114 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013115 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013116 defaultRule = FIREWALL_RULE_ALLOW;
13117 break;
13118 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13119 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13120 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13121 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013122 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013123 defaultRule = FIREWALL_RULE_DENY;
13124 break;
13125 default:
13126 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13127 }
13128 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13129
13130 return rule;
13131 }
13132
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013133 private void closeSocketsForFirewallChainLocked(final int chain)
13134 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013135 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013136 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13137 // So, close all non-system socket owned by uids that are not explicitly allowed
13138 Set<Range<Integer>> ranges = new ArraySet<>();
13139 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13140 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13141 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13142 } else {
13143 // Denylist means the firewall allows all by default, uids must be explicitly denied
13144 // So, close socket owned by uids that are explicitly denied
13145 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13146 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13147 }
13148 }
13149
markchien98a6f952022-01-13 23:43:53 +080013150 @Override
13151 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13152 enforceNetworkStackOrSettingsPermission();
13153
13154 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013155 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013156 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013157 throw new IllegalStateException(e);
13158 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013159
Chalard Jeandf29a852023-05-29 17:02:43 +090013160 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013161 try {
13162 closeSocketsForFirewallChainLocked(chain);
13163 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13164 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13165 }
13166 }
markchien98a6f952022-01-13 23:43:53 +080013167 }
13168
markchien00a0bed2022-01-13 23:46:13 +080013169 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013170 public boolean getFirewallChainEnabled(final int chain) {
13171 enforceNetworkStackOrSettingsPermission();
13172
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013173 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013174 }
13175
13176 @Override
markchien00a0bed2022-01-13 23:46:13 +080013177 public void replaceFirewallChain(final int chain, final int[] uids) {
13178 enforceNetworkStackOrSettingsPermission();
13179
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013180 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013181 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013182
13183 @Override
13184 public IBinder getCompanionDeviceManagerProxyService() {
13185 enforceNetworkStackPermission(mContext);
13186 return mCdmps;
13187 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013188
13189 @Override
13190 public IBinder getRoutingCoordinatorService() {
13191 enforceNetworkStackPermission(mContext);
13192 return mRoutingCoordinatorService;
13193 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013194}