blob: 7d1644ed3bf8ac3b4421eb3f9893a5dfff4e7659 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Mark Fasheh7c999d82023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
Chalard Jeane0aaca52023-10-17 13:23:07 +090022import static android.content.pm.PackageManager.FEATURE_LEANBACK;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090023import static android.content.pm.PackageManager.FEATURE_WATCH;
24import static android.content.pm.PackageManager.FEATURE_WIFI;
25import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090026import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090027import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
29import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
34import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090035import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
36import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000037import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang9fe47be2021-06-08 13:11:45 +080038import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070039import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080040import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
41import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
42import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090043import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090044import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090045import static android.net.ConnectivityManager.TYPE_MOBILE;
46import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
48import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
49import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
50import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
51import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
52import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
53import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
54import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070055import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090056import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070057import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090058import static android.net.ConnectivityManager.TYPE_WIFI;
59import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070060import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070061import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080062import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080063import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080066import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040067import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
74import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080077import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080079import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
80import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080081import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090082import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090083import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080084import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
85import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080086import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
87import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
88import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090089import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090090import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060091import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070092import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080093import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090094import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070095import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
96import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070097import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080098import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +010099import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700100import static android.system.OsConstants.IPPROTO_TCP;
101import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900102
Junyu Lai155760b2023-10-05 14:51:00 +0800103import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
104import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
105import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
106import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
107import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Xiao Ma60142372022-07-16 17:30:20 +0900108import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800109import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800110import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
111import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
112import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900113import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Chalard Jeaneb663892023-10-07 15:17:07 +0900114
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800115import static java.util.Map.Entry;
116
Chalard Jean5b639762020-03-09 21:25:37 +0900117import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000118import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800119import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600120import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800121import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000122import android.app.ActivityManager;
123import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800124import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800125import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700126import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700127import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900128import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800129import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700130import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800131import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132import android.content.ContentResolver;
133import android.content.Context;
134import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700135import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800136import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900137import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700138import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800139import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900140import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900141import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700142import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800143import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800144import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900146import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800147import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900148import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800149import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900150import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800151import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700152import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900153import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800154import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800155import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800156import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800157import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800158import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900159import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900160import android.net.INetworkMonitor;
161import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900162import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900163import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700164import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800165import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900166import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900167import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900168import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800169import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900170import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900171import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100172import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800173import android.net.NativeNetworkConfig;
174import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800175import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700176import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700177import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900178import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700179import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800180import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700181import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900182import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900183import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000184import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900185import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700186import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900187import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700188import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900189import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700190import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800191import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900192import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700193import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000194import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800195import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900196import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800197import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400198import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700199import android.net.QosCallbackException;
200import android.net.QosFilter;
201import android.net.QosSocketFilter;
202import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700203import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800204import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800205import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900206import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400207import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800208import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800209import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400210import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800211import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900212import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900213import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900214import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900215import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800216import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900217import android.net.networkstack.ModuleNetworkStackClient;
218import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900219import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800220import android.net.resolv.aidl.DnsHealthEventParcel;
221import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
222import android.net.resolv.aidl.Nat64PrefixEventParcel;
223import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900224import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900225import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800226import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800227import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800228import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700229import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000230import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700232import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700233import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800234import android.os.Looper;
235import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700236import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700237import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900238import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800239import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700240import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700241import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800242import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700243import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900244import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900245import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700246import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700247import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400248import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800249import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900250import android.stats.connectivity.MeteredState;
251import android.stats.connectivity.RequestType;
252import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900253import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700254import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700255import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700256import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800257import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900258import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000259import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600260import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900261import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900262import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700263import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700264import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900265import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800266
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800267import androidx.annotation.RequiresApi;
268
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900269import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400270import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400271import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700272import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900273import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900274import com.android.metrics.ConnectionDurationForTransports;
275import com.android.metrics.ConnectionDurationPerTransports;
276import com.android.metrics.ConnectivitySampleMetricsHelper;
277import com.android.metrics.ConnectivityStateSample;
278import com.android.metrics.NetworkCountForTransports;
279import com.android.metrics.NetworkCountPerTransports;
280import com.android.metrics.NetworkDescription;
281import com.android.metrics.NetworkList;
282import com.android.metrics.NetworkRequestCount;
283import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800284import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900285import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800286import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000287import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900288import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800289import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900290import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900291import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100292import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900293import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
294import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900295import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800296import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800297import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100298import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000299import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800300import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
301import com.android.networkstack.apishim.ConstantsShim;
302import com.android.networkstack.apishim.common.BroadcastOptionsShim;
303import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900304import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900305import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000306import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900307import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800308import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800309import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900310import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900311import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900312import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500313import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700314import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900315import com.android.server.connectivity.FullScore;
Junyu Laif8dba342023-10-12 17:01:03 +0800316import com.android.server.connectivity.HandlerUtils;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900317import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900318import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000319import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100320import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700321import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900322import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700323import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600324import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900325import com.android.server.connectivity.NetworkNotificationManager;
326import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900327import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900328import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900329import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700330import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900331import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900332import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700333import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900334import com.android.server.connectivity.RoutingCoordinatorService;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800335import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000336import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800337import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600338
Josh Gao461a1222020-06-16 15:58:11 -0700339import libcore.io.IoUtils;
340
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900341import org.xmlpull.v1.XmlPullParserException;
342
The Android Open Source Project28527d22009-03-03 19:31:44 -0800343import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100344import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900345import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800346import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900347import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700348import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700349import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900350import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900351import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700352import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700353import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700354import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700355import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800356import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900357import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800358import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700359import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700360import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700361import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700362import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900363import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700364import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900365import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600366import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900367import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600368import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900369import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900370import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800371
372/**
373 * @hide
374 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800375public class ConnectivityService extends IConnectivityManager.Stub
376 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900377 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800378
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900379 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900380 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900381 private static final String NETWORK_ARG = "networks";
382 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800383 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900384
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900385 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900386 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
387 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800388
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900389 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700390
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100391 /**
392 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
393 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800394 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100395 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
396 * (preferably via runtime resource overlays).
397 */
398 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
399 "http://connectivitycheck.gstatic.com/generate_204";
400
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700401 // TODO: create better separation between radio types and network types
402
Robert Greenwalt2034b912009-08-12 16:08:25 -0700403 // how long to wait before switching back to a radio's default network
404 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
405 // system property that can override the above value
406 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
407 "android.telephony.apn-restore";
408
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900409 // How long to wait before putting up a "This network doesn't have an Internet connection,
410 // connect anyway?" dialog after the user selects a network that doesn't validate.
411 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
412
Chalard Jean5fb43c72022-09-08 19:03:14 +0900413 // How long to wait before considering that a network is bad in the absence of any form
414 // of connectivity (valid, partial, captive portal). If none has been detected after this
415 // delay, the stack considers this network bad, which may affect how it's handled in ranking
416 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900417 // Timeout in case the "actively prefer bad wifi" feature is on
418 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
419 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900420 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900421
junyulai0ac374f2020-12-14 18:41:52 +0800422 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900423 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
424 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800425 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700426
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800427 // Delimiter used when creating the broadcast delivery group for sending
428 // CONNECTIVITY_ACTION broadcast.
429 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
430
he_won.hwang881307a2022-03-15 21:23:52 +0900431 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900432 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900433
Daniel Brightf9e945b2020-06-15 16:10:01 -0700434 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900435 @VisibleForTesting
436 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700437
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900438 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700439 @VisibleForTesting
440 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900441
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900442 @VisibleForTesting
443 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800444 @VisibleForTesting
445 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900446 // True if the cell radio of the device is capable of time-sharing.
447 @VisibleForTesting
448 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900449
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800450 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800451 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800452 private final int mReleasePendingIntentDelayMs;
453
Chalard Jean46bfbf02022-02-02 00:56:25 +0900454 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900455
Motomu Utsumif360aa62023-01-30 17:52:20 +0900456 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700457
Chalard Jean9473c982021-07-29 20:03:04 +0900458 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800459 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700460 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800461 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700462
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900463 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700464
junyulaif2c67e42018-08-07 19:50:45 +0800465 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000466 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
467 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800468 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900469 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800470
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900471 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900472 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000473 private final int mWakeUpMark;
474 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000475 // The Context is created for UserHandle.ALL.
476 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900477 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900478 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700479 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700480 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800481
Chenbo Feng15416292018-11-08 17:36:21 -0800482 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800483 protected IDnsResolver mDnsResolver;
484 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800485 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700486 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900487 private final NetworkStatsManager mStatsManager;
488 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800489 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700490
Benedict Wong493e04b2018-11-09 14:45:34 -0800491 /**
492 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
493 * instances.
494 */
495 @GuardedBy("mTNSLock")
496 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800497 private final CompanionDeviceManagerProxyService mCdmps;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900498 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800499
500 private final Object mTNSLock = new Object();
501
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700502 private String mCurrentTcpBufferSizes;
503
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900504 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000505 new Class[] {
506 ConnectivityService.class,
507 NetworkAgent.class,
508 NetworkAgentInfo.class,
509 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900510
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500511 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400512 // Tear down networks that have no chance (e.g. even if validated) of becoming
513 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500514 // all networks have been rematched against all NetworkRequests.
515 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400516 // Don't reap networks. This should be passed when some networks have not yet been
517 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500518 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900519 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500520
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900521 private enum UnneededFor {
522 LINGER, // Determine whether this network is unneeded and should be lingered.
523 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
524 }
525
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700526 /**
paulhuaa0743d2021-05-26 21:56:03 +0800527 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800528 * should have priority. The order is passed to netd which will use it together
529 * with UID ranges to generate the corresponding IP rule. This serves to
530 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800531 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800532 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000533 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800534 *
paulhu48291862021-07-14 14:53:57 +0800535 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
536 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800537 */
paulhu48291862021-07-14 14:53:57 +0800538 // Used when sending to netd to code for "no order".
539 static final int PREFERENCE_ORDER_NONE = 0;
540 // Order for requests that don't code for a per-app preference. As it is
541 // out of the valid range, the corresponding order should be
542 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800543 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800544 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800545 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800546 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
547 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800548 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800549 static final int PREFERENCE_ORDER_OEM = 10;
550 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800551 // See {@link #setProfileNetworkPreference}.
552 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800553 static final int PREFERENCE_ORDER_PROFILE = 20;
554 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800555 // better scores are connected.
556 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800557 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800558 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900559 // Preference order that signifies the network shouldn't be set as a default network for
560 // the UIDs, only give them access to it. TODO : replace this with a boolean
561 // in NativeUidRangeConfig
562 @VisibleForTesting
563 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
564 // Bound for the lowest valid preference order.
565 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800566
567 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700568 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700569 * from one net to another. Clear happens when we get a new
570 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
571 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700572 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700573 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700574
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700575 /**
576 * used internally to reload global proxy settings
577 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700578 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700579
Robert Greenwalt34848c02011-03-25 13:09:25 -0700580 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400581 * PAC manager has received new port.
582 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800583 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400584
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700585 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900586 * used internally when registering NetworkProviders
587 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700588 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900589 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700590
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700591 /**
592 * used internally when registering NetworkAgents
593 * obj = Messenger
594 */
595 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
596
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700597 /**
598 * used to add a network request
599 * includes a NetworkRequestInfo
600 */
601 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
602
603 /**
604 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900605 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700606 * cancel it.
607 * includes a NetworkRequestInfo
608 */
609 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
610
611 /**
612 * used to add a network listener - no request
613 * includes a NetworkRequestInfo
614 */
615 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
616
617 /**
618 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400619 * arg1 = UID of caller
620 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700621 */
622 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
623
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700624 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900625 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700626 * obj = Messenger
627 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900628 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700629
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700630 /**
631 * used internally to expire a wakelock when transitioning
632 * from one net to another. Expire happens when we fail to find
633 * a new network (typically after 1 minute) -
634 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
635 * a replacement network.
636 */
637 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
638
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700639 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800640 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400641 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800642 */
643 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
644
645 /**
646 * used to remove a pending intent and its associated network request.
647 * arg1 = UID of caller
648 * obj = PendingIntent
649 */
650 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
651
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900652 /**
653 * used to specify whether a network should be used even if unvalidated.
654 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
655 * arg2 = whether to remember this choice in the future (1 or 0)
656 * obj = network
657 */
658 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
659
660 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700661 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900662 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700663 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900664
Paul Jensenc8873fc2015-06-17 14:15:39 -0400665 /**
666 * used to add a network listener with a pending intent
667 * obj = NetworkRequestInfo
668 */
669 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
670
Hugo Benichid6b510a2017-04-06 17:22:18 +0900671 /**
672 * used to specify whether a network should not be penalized when it becomes unvalidated.
673 */
674 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
675
676 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700677 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900678 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700679 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900680
Erik Kline31b4a9e2018-01-11 21:07:29 +0900681 // Handle changes in Private DNS settings.
682 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
683
dalyk1720e542018-03-05 12:42:22 -0500684 // Handle private DNS validation status updates.
685 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
686
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900687 /**
688 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
689 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800690 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
691 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
692 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900693 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900694 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900695
696 /**
697 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
698 * config was resolved.
699 * obj = PrivateDnsConfig
700 * arg2 = netid
701 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900702 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900703
704 /**
705 * Request ConnectivityService display provisioning notification.
706 * arg1 = Whether to make the notification visible.
707 * arg2 = NetID.
708 * obj = Intent to be launched when notification selected by user, null if !arg1.
709 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900710 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900711
712 /**
lucaslin2240ef62019-03-12 13:08:03 +0800713 * Used to specify whether a network should be used even if connectivity is partial.
714 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
715 * false)
716 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
717 * obj = network
718 */
lucaslin444d43a2020-02-20 16:56:59 +0800719 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800720
721 /**
lucasline117e2e2019-10-22 18:27:33 +0800722 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
723 * Both of the arguments are bitmasks, and the value of bits come from
724 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900725 * arg1 = unused
726 * arg2 = netId
727 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800728 */
lucaslin444d43a2020-02-20 16:56:59 +0800729 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800730
731 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900732 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
733 * arg1 = unused
734 * arg2 = netId
735 * obj = captive portal data
736 */
lucaslin444d43a2020-02-20 16:56:59 +0800737 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900738
739 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900740 * Used by setRequireVpnForUids.
741 * arg1 = whether the specified UID ranges are required to use a VPN.
742 * obj = Array of UidRange objects.
743 */
744 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
745
746 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900747 * Used internally when setting the default networks for OemNetworkPreferences.
748 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800749 */
750 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
751
752 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800753 * Used to indicate the system default network becomes active.
754 */
755 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
756
757 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900758 * Used internally when setting a network preference for a user profile.
759 * obj = Pair<ProfileNetworkPreference, Listener>
760 */
761 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
762
763 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000764 * Event to specify that reasons for why an uid is blocked changed.
765 * arg1 = uid
766 * arg2 = blockedReasons
767 */
768 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
769
770 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900771 * Event to register a new network offer
772 * obj = NetworkOffer
773 */
774 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
775
776 /**
777 * Event to unregister an existing network offer
778 * obj = INetworkOfferCallback
779 */
780 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
781
782 /**
paulhu51f77dc2021-06-07 02:34:20 +0000783 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
784 */
785 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
786
787 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800788 * Event to set temporary allow bad wifi within a limited time to override
789 * {@code config_networkAvoidBadWifi}.
790 */
791 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
792
793 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100794 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
795 */
796 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
797
798 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900799 * The initial evaluation period is over for this network.
800 *
801 * If no form of connectivity has been found on this network (valid, partial, captive portal)
802 * then the stack will now consider it to have been determined bad.
803 */
804 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
805
806 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000807 * Used internally when the user does not want the network from captive portal app.
808 * obj = Network
809 */
810 private static final int EVENT_USER_DOES_NOT_WANT = 58;
811
812 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000813 * Event to set VPN as preferred network for specific apps.
814 * obj = VpnNetworkPreferenceInfo
815 */
816 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
817
818 /**
chiachangwange0192a72023-02-06 13:25:01 +0000819 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
820 */
821 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
822
823 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000824 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
825 */
826 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
827
828 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900829 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
830 * should be shown.
831 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900832 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900833
834 /**
835 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
836 * should be hidden.
837 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900838 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900839
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800840 /**
841 * The maximum alive time to allow bad wifi configuration for testing.
842 */
843 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
844
Patrick Rohr2857ac42022-01-21 14:58:16 +0100845 /**
chiachangwange0192a72023-02-06 13:25:01 +0000846 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
847 * testing.
848 */
849 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
850
851 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100852 * The priority of the tc police rate limiter -- smaller value is higher priority.
853 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
854 */
855 private static final short TC_PRIO_POLICE = 1;
856
857 /**
858 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
859 */
860 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700861 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100862
Hugo Benichi47011212017-03-30 10:46:05 +0900863 private static String eventName(int what) {
864 return sMagicDecoderRing.get(what, Integer.toString(what));
865 }
866
paulhua10d8212020-11-10 15:32:56 +0800867 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900868 final DnsResolverServiceManager dsm = context.getSystemService(
869 DnsResolverServiceManager.class);
870 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800871 }
872
Cody Kesting73708bf2019-12-18 10:57:50 -0800873 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900874 @VisibleForTesting
875 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700876 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700877 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700878 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700879 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800880 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
881 @VisibleForTesting
882 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
883
Erik Kline32120082017-12-13 19:40:49 +0900884 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900885 @VisibleForTesting
886 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700887
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400888 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800889 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400890
Chalard Jean46bfbf02022-02-02 00:56:25 +0900891 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800892 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700893
Chalard Jean5d70ba42018-06-07 16:44:04 +0900894 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
895 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800896 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400897
Erik Kline05f2b402015-04-30 12:58:40 +0900898 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700899
Chalard Jean46bfbf02022-02-02 00:56:25 +0900900 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400901
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700902 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900903 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700904
Valentin Iftime9fa35092019-09-24 13:32:13 +0200905 private Set<String> mWolSupportedInterfaces;
906
Roshan Pius08c94fb2020-01-16 12:17:17 -0800907 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800908 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800909 private final AppOpsManager mAppOpsManager;
910
911 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400912
chiachangwang3d60bac2023-01-17 14:38:08 +0000913 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900914 private final QosCallbackTracker mQosCallbackTracker;
915 private final NetworkNotificationManager mNotifier;
916 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900917
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700918 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800919 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700920
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900921 // Sequence number for NetworkProvider IDs.
922 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
923 NetworkProvider.FIRST_PROVIDER_ID);
924
Erik Klineedf878b2015-07-09 18:24:03 +0900925 // NetworkRequest activity String log entries.
926 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
927 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
928
Hugo Benichid159fdd2016-07-11 11:05:12 +0900929 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900930 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900931 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
932
Hugo Benichi47011212017-03-30 10:46:05 +0900933 private static final int MAX_WAKELOCK_LOGS = 20;
934 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900935 private int mTotalWakelockAcquisitions = 0;
936 private int mTotalWakelockReleases = 0;
937 private long mTotalWakelockDurationMs = 0;
938 private long mMaxWakelockDurationMs = 0;
939 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900940
Hugo Benichi208c0102016-07-28 17:53:06 +0900941 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900942
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700943 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900944 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700945
Erik Kline95ecfee2016-10-02 18:02:14 +0900946 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900947 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900948
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900949 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800950 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
951 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800952
Patrick Rohr2857ac42022-01-21 14:58:16 +0100953 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
954 // configured via {@link
955 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
956 // Only the handler thread is allowed to access this field.
957 private long mIngressRateLimit = -1;
958
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900959 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
960 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900961 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900962 @GuardedBy("mSelfCertifiedCapabilityCache")
963 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
964 mSelfCertifiedCapabilityCache = new HashMap<>();
965
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900966 // Flag to enable the feature of closing frozen app sockets.
967 private final boolean mDestroyFrozenSockets;
968
969 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
970 private final boolean mDelayDestroyFrozenSockets;
971
972 // Uids that ConnectivityService is pending to close sockets of.
973 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
974
Robert Greenwalt802c1102014-06-02 15:32:02 -0700975 /**
976 * Implements support for the legacy "one network per network type" model.
977 *
978 * We used to have a static array of NetworkStateTrackers, one for each
979 * network type, but that doesn't work any more now that we can have,
980 * for example, more that one wifi network. This class stores all the
981 * NetworkAgentInfo objects that support a given type, but the legacy
982 * API will only see the first one.
983 *
984 * It serves two main purposes:
985 *
986 * 1. Provide information about "the network for a given type" (since this
987 * API only supports one).
988 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
989 * the first network for a given type changes, or if the default network
990 * changes.
991 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900992 @VisibleForTesting
993 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900994
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900995 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900996 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900997
Robert Greenwalt802c1102014-06-02 15:32:02 -0700998 /**
999 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1000 * Each list holds references to all NetworkAgentInfos that are used to
1001 * satisfy requests for that network type.
1002 *
1003 * This array is built out at startup such that an unsupported network
1004 * doesn't get an ArrayList instance, making this a tristate:
1005 * unsupported, supported but not active and active.
1006 *
1007 * The actual lists are populated when we scan the network types that
1008 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001009 *
1010 * Threading model:
1011 * - addSupportedType() is only called in the constructor
1012 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1013 * They are therefore not thread-safe with respect to each other.
1014 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1015 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001016 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001017 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001018 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001019 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001020 @NonNull
1021 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001022
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001023 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1024 // an entry have no timer (equivalent to -1). Lazily loaded.
1025 @NonNull
1026 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1027
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001028 LegacyTypeTracker(@NonNull ConnectivityService service) {
1029 mService = service;
1030 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001031 }
1032
Chiachang Wang3bc52762021-11-25 14:17:57 +08001033 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1034 // addressed.
1035 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001036 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1037 final PackageManager pm = ctx.getPackageManager();
1038 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1039 addSupportedType(TYPE_WIFI);
1040 }
1041 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1042 addSupportedType(TYPE_WIFI_P2P);
1043 }
1044 if (tm.isDataCapable()) {
1045 // Telephony does not have granular support for these types: they are either all
1046 // supported, or none is supported
1047 addSupportedType(TYPE_MOBILE);
1048 addSupportedType(TYPE_MOBILE_MMS);
1049 addSupportedType(TYPE_MOBILE_SUPL);
1050 addSupportedType(TYPE_MOBILE_DUN);
1051 addSupportedType(TYPE_MOBILE_HIPRI);
1052 addSupportedType(TYPE_MOBILE_FOTA);
1053 addSupportedType(TYPE_MOBILE_IMS);
1054 addSupportedType(TYPE_MOBILE_CBS);
1055 addSupportedType(TYPE_MOBILE_IA);
1056 addSupportedType(TYPE_MOBILE_EMERGENCY);
1057 }
1058 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1059 addSupportedType(TYPE_BLUETOOTH);
1060 }
1061 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1062 // TYPE_PROXY is only used on Wear
1063 addSupportedType(TYPE_PROXY);
1064 }
1065 // Ethernet is often not specified in the configs, although many devices can use it via
1066 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001067 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001068 addSupportedType(TYPE_ETHERNET);
1069 }
1070
1071 // Always add TYPE_VPN as a supported type
1072 addSupportedType(TYPE_VPN);
1073 }
1074
1075 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001076 if (mTypeLists[type] != null) {
1077 throw new IllegalStateException(
1078 "legacy list for type " + type + "already initialized");
1079 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001080 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001081 }
1082
Robert Greenwalt802c1102014-06-02 15:32:02 -07001083 public boolean isTypeSupported(int type) {
1084 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1085 }
1086
1087 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001088 synchronized (mTypeLists) {
1089 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1090 return mTypeLists[type].get(0);
1091 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001092 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001093 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001094 }
1095
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001096 public int getRestoreTimerForType(int type) {
1097 synchronized (mTypeLists) {
1098 if (mRestoreTimers == null) {
1099 mRestoreTimers = loadRestoreTimers();
1100 }
1101 return mRestoreTimers.getOrDefault(type, -1);
1102 }
1103 }
1104
1105 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1106 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001107 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001108 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1109 for (final String config : configs) {
1110 final String[] splits = TextUtils.split(config, ",");
1111 if (splits.length != 2) {
1112 logwtf("Invalid restore timer token count: " + config);
1113 continue;
1114 }
1115 try {
1116 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1117 } catch (NumberFormatException e) {
1118 logwtf("Invalid restore timer number format: " + config, e);
1119 }
1120 }
1121 return ret;
1122 }
1123
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001124 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001125 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001126 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001127 log("Sending " + state
1128 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001129 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001130 }
1131 }
1132
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001133 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1134 // network type, to preserve previous behaviour.
1135 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1136 if (vpnNai != mService.getLegacyLockdownNai()) return;
1137
1138 if (vpnNai.declaredUnderlyingNetworks == null
1139 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1140 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1141 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1142 return;
1143 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001144 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001145 vpnNai.declaredUnderlyingNetworks[0]);
1146 if (underlyingNai == null) return;
1147
1148 final int type = underlyingNai.networkInfo.getType();
1149 final DetailedState state = DetailedState.CONNECTED;
1150 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1151 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1152 }
1153
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001154 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001155 public void add(int type, NetworkAgentInfo nai) {
1156 if (!isTypeSupported(type)) {
1157 return; // Invalid network type.
1158 }
1159 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1160
1161 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1162 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001163 return;
1164 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001165 synchronized (mTypeLists) {
1166 list.add(nai);
1167 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001168
Chalard Jean5b409c72021-02-04 13:12:59 +09001169 // Send a broadcast if this is the first network of its type or if it's the default.
1170 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001171
1172 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1173 // to preserve previous behaviour.
1174 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001175 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001176 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1177 mService.sendLegacyNetworkBroadcast(nai, state, type);
1178 }
1179
1180 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1181 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001182 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001183 }
1184
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001185 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001186 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001187 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1188 if (list == null || list.isEmpty()) {
1189 return;
1190 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001191 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001192
Hugo Benichi389633f2016-06-21 09:48:07 +09001193 synchronized (mTypeLists) {
1194 if (!list.remove(nai)) {
1195 return;
1196 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001197 }
1198
Lorenzo Colitti49767722015-05-01 00:30:10 +09001199 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001200 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1201 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001202 }
1203
1204 if (!list.isEmpty() && wasFirstNetwork) {
1205 if (DBG) log("Other network available for type " + type +
1206 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001207 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001208 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001209 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001210 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001211 }
1212 }
1213
1214 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001215 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1216 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001217 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001218 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001219 }
1220 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001221
Chalard Jean46bfbf02022-02-02 00:56:25 +09001222 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001223 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001224 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001225 final DetailedState state = nai.networkInfo.getDetailedState();
1226 for (int type = 0; type < mTypeLists.length; type++) {
1227 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001228 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001229 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001230 if (isFirst || contains && isDefault) {
1231 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001232 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001233 }
1234 }
1235 }
1236
Robert Greenwalt94e22142014-07-30 16:31:24 -07001237 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001238 pw.println("mLegacyTypeTracker:");
1239 pw.increaseIndent();
1240 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001241 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001242 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001243 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001244 pw.println();
1245 pw.println("Current state:");
1246 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001247 synchronized (mTypeLists) {
1248 for (int type = 0; type < mTypeLists.length; type++) {
1249 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1250 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001251 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001252 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001253 }
1254 }
1255 pw.decreaseIndent();
1256 pw.decreaseIndent();
1257 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001258 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001259 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001260 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001261
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001262 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001263 /**
1264 * Helper class which parses out priority arguments and dumps sections according to their
1265 * priority. If priority arguments are omitted, function calls the legacy dump command.
1266 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001267 private class LocalPriorityDump {
1268 private static final String PRIORITY_ARG = "--dump-priority";
1269 private static final String PRIORITY_ARG_HIGH = "HIGH";
1270 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001271 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001272
1273 LocalPriorityDump() {}
1274
1275 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Laif8dba342023-10-12 17:01:03 +08001276 if (!HandlerUtils.runWithScissors(mHandler, () -> {
1277 doDump(fd, pw, new String[]{DIAG_ARG});
1278 doDump(fd, pw, new String[]{SHORT_ARG});
1279 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1280 pw.println("dumpHigh timeout");
1281 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001282 }
1283
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001284 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Laif8dba342023-10-12 17:01:03 +08001285 if (!HandlerUtils.runWithScissors(mHandler, () -> doDump(fd, pw, args),
1286 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1287 pw.println("dumpNormal timeout");
1288 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001289 }
1290
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001291 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1292 if (args == null) {
1293 dumpNormal(fd, pw, args);
1294 return;
1295 }
1296
1297 String priority = null;
1298 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1299 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1300 argIndex++;
1301 priority = args[argIndex];
1302 }
1303 }
1304
1305 if (PRIORITY_ARG_HIGH.equals(priority)) {
1306 dumpHigh(fd, pw);
1307 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1308 dumpNormal(fd, pw, args);
1309 } else {
1310 // ConnectivityService publishes binder service using publishBinderService() with
1311 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001312 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1313 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001314 // TODO: Integrate into signal dump.
1315 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001316 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001317 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001318 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001319
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001320 /**
1321 * Dependencies of ConnectivityService, for injection in tests.
1322 */
1323 @VisibleForTesting
1324 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001325 public int getCallingUid() {
1326 return Binder.getCallingUid();
1327 }
1328
Chalard Jeandf29a852023-05-29 17:02:43 +09001329 public boolean isAtLeastS() {
1330 return SdkLevel.isAtLeastS();
1331 }
1332
1333 public boolean isAtLeastT() {
1334 return SdkLevel.isAtLeastT();
1335 }
1336
1337 public boolean isAtLeastU() {
1338 return SdkLevel.isAtLeastU();
1339 }
1340
Chalard Jeaneb663892023-10-07 15:17:07 +09001341 public boolean isAtLeastV() {
1342 return SdkLevel.isAtLeastV();
1343 }
1344
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001345 /**
1346 * Get system properties to use in ConnectivityService.
1347 */
1348 public MockableSystemProperties getSystemProperties() {
1349 return new MockableSystemProperties();
1350 }
1351
1352 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001353 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1354 */
1355 public ConnectivityResources getResources(@NonNull Context ctx) {
1356 return new ConnectivityResources(ctx);
1357 }
1358
1359 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001360 * Create a HandlerThread to use in ConnectivityService.
1361 */
1362 public HandlerThread makeHandlerThread() {
1363 return new HandlerThread("ConnectivityServiceThread");
1364 }
1365
1366 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001367 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001368 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001369 public NetworkStackClientBase getNetworkStack() {
1370 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001371 }
1372
1373 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001374 * @see ProxyTracker
1375 */
1376 public ProxyTracker makeProxyTracker(@NonNull Context context,
1377 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001378 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001379 }
1380
1381 /**
1382 * @see NetIdManager
1383 */
1384 public NetIdManager makeNetIdManager() {
1385 return new NetIdManager();
1386 }
1387
1388 /**
1389 * @see NetworkUtils#queryUserAccess(int, int)
1390 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001391 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1392 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001393 }
1394
1395 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001396 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1397 * requires CAP_NET_ADMIN, which the unit tests do not have.
1398 */
1399 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1400 InetSocketAddress remote) {
1401 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1402 }
1403
1404 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001405 * @see MultinetworkPolicyTracker
1406 */
1407 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1408 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1409 return new MultinetworkPolicyTracker(c, h, r);
1410 }
1411
Aaron Huang330a4c02020-10-27 03:36:19 +08001412 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001413 * @see AutomaticOnOffKeepaliveTracker
1414 */
1415 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1416 @NonNull Context c, @NonNull Handler h) {
1417 return new AutomaticOnOffKeepaliveTracker(c, h);
1418 }
1419
1420 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001421 * @see BatteryStatsManager
1422 */
1423 public void reportNetworkInterfaceForTransports(Context context, String iface,
1424 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001425 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001426 context.getSystemService(BatteryStatsManager.class);
1427 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1428 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001429
1430 public boolean getCellular464XlatEnabled() {
1431 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1432 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001433
1434 /**
1435 * @see PendingIntent#intentFilterEquals
1436 */
1437 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1438 return a.intentFilterEquals(b);
1439 }
1440
1441 /**
1442 * @see LocationPermissionChecker
1443 */
1444 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1445 return new LocationPermissionChecker(context);
1446 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001447
1448 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001449 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001450 *
1451 * This method returns null in versions before T, where carrier privilege
1452 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001453 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001454 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001455 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1456 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001457 if (isAtLeastT()) {
Chalard Jean84dfa9f2023-01-30 11:23:20 +09001458 return new CarrierPrivilegeAuthenticator(context, this, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001459 } else {
1460 return null;
1461 }
1462 }
1463
1464 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001465 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001466 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001467 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001468 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001469 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001470
1471 /**
1472 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001473 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001474 * @return BpfNetMaps implementation.
1475 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001476 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1477 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001478 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001479
1480 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001481 * @see ClatCoordinator
1482 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001483 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001484 public ClatCoordinator getClatCoordinator(INetd netd) {
1485 return new ClatCoordinator(
1486 new ClatCoordinator.Dependencies() {
1487 @NonNull
1488 public INetd getNetd() {
1489 return netd;
1490 }
1491 });
1492 }
1493
1494 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001495 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1496 */
1497 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1498 final InterfaceParams params = InterfaceParams.getByName(iface);
1499 if (params == null) {
1500 // the interface might have disappeared.
1501 logw("Failed to get interface params for interface " + iface);
1502 return;
1503 }
1504 try {
1505 // converting rateInBytesPerSecond from long to int is safe here because the
1506 // setting's range is limited to INT_MAX.
1507 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001508 Log.i(TAG,
1509 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001510 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1511 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1512 } catch (IOException e) {
1513 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1514 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1515 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1516 + ") failure: ", e);
1517 }
1518 }
1519
1520 /**
1521 * Wraps {@link TcUtils#tcFilterDelDev}
1522 */
1523 public void disableIngressRateLimit(String iface) {
1524 final InterfaceParams params = InterfaceParams.getByName(iface);
1525 if (params == null) {
1526 // the interface might have disappeared.
1527 logw("Failed to get interface params for interface " + iface);
1528 return;
1529 }
1530 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001531 Log.i(TAG,
1532 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001533 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1534 } catch (IOException e) {
1535 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1536 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1537 }
1538 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001539
1540 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001541 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1542 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001543 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001544 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001545 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001546 }
1547
1548 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001549 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1550 */
1551 // TODO: when available in all active branches:
1552 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1553 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1554 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1555 return BroadcastOptionsShimImpl.newInstance(options);
1556 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001557
1558 /**
1559 * Wrapper method for
1560 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1561 *
1562 * @param changeId The ID of the compatibility change in question.
1563 * @param packageName The package name of the app in question.
1564 * @param user The user that the operation is done for.
1565 * @return {@code true} if the change is enabled for the specified package.
1566 */
1567 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1568 @NonNull final UserHandle user) {
1569 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1570 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001571
1572 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001573 * As above but with a UID.
1574 * @see CompatChanges#isChangeEnabled(long, int)
1575 */
1576 public boolean isChangeEnabled(final long changeId, final int uid) {
1577 return CompatChanges.isChangeEnabled(changeId, uid);
1578 }
1579
1580 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001581 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1582 *
1583 * @param ranges target uid ranges
1584 * @param exemptUids uids to skip close socket
1585 */
1586 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1587 @NonNull final Set<Integer> exemptUids)
1588 throws SocketException, InterruptedIOException, ErrnoException {
1589 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1590 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001591
1592 /**
1593 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1594 *
1595 * @param ownerUids target uids to close sockets
1596 */
1597 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1598 throws SocketException, InterruptedIOException, ErrnoException {
1599 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1600 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001601
1602 /**
1603 * Schedule the evaluation timeout.
1604 *
1605 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1606 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1607 * of these events happen, this time will run out, after which the network is considered
1608 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1609 * on this network and considers it won't provide connectivity. In particular, that means
1610 * it's when the system prefers it to cell if it's wifi and configuration says it should
1611 * prefer bad wifi to cell.
1612 */
1613 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1614 @NonNull final Network network, final long delayMs) {
1615 handler.sendMessageDelayed(
1616 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1617 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001618 }
1619
junyulaie7c7d2a2021-01-26 15:29:15 +08001620 public ConnectivityService(Context context) {
1621 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001622 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1623 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001624 }
1625
1626 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001627 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1628 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001629 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001630
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001631 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001632 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001633 mSystemProperties = mDeps.getSystemProperties();
1634 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001635 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001636 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001637 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1638 // Pass limit - 1 to maintain backward compatibility.
1639 // TODO: Remove the workaround.
1640 mNetworkRequestCounter =
1641 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1642 mSystemNetworkRequestCounter =
1643 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001644
Hugo Benichi208c0102016-07-28 17:53:06 +09001645 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001646 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1647 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001648 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001649 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001650 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001651 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1652 mDefaultNetworkRequests.add(mDefaultRequest);
1653 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001654
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001655 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001656 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001657
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001658 // The default WiFi request is a background request so that apps using WiFi are
1659 // migrated to a better network (typically ethernet) when one comes up, instead
1660 // of staying on WiFi forever.
1661 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1662 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1663
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001664 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1665 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1666 NetworkRequest.Type.BACKGROUND_REQUEST);
1667
Chalard Jean0702f982021-09-16 21:50:07 +09001668 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1669 // TODO: Consider making the timer customizable.
1670 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1671 mCellularRadioTimesharingCapable =
1672 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1673
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001674 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1675 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1676
1677 if (SdkLevel.isAtLeastU()) {
1678 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1679 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1680 final int defaultUMarkMask = 0x80000000; // u32
1681
1682 if ((mark == 0) || (mask == 0)) {
1683 // simply treat unset/disabled as the default U value
1684 mark = defaultUMarkMask;
1685 mask = defaultUMarkMask;
1686 }
1687 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1688 // invalid device overlay settings
1689 throw new IllegalArgumentException(
1690 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1691 }
1692 }
1693
1694 mWakeUpMark = mark;
1695 mWakeUpMask = mask;
1696
Paul Hu51f816b2022-08-11 14:43:47 +00001697 mNetd = netd;
1698 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001699 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001700 mPermissionMonitor =
1701 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001702 mHandlerThread.start();
1703 mHandler = new InternalHandler(mHandlerThread.getLooper());
1704 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001705 mConnectivityDiagnosticsHandler =
1706 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001707
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001708 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001709 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001710
junyulaie7c7d2a2021-01-26 15:29:15 +08001711 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001712 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001713 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001714 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001715
Wink Saville32506bc2013-06-29 21:10:57 -07001716 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001717 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001718 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001719 mCarrierPrivilegeAuthenticator =
1720 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001721
Sudheer Shanka9967d462021-03-18 19:09:25 +00001722 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001723 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1724 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001725 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001726
1727 final PowerManager powerManager = (PowerManager) context.getSystemService(
1728 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001729 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001730 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001731
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001732 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1733 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001734 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001735 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001736 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001737 mProtectedNetworks.add(p);
1738 } else {
1739 if (DBG) loge("Ignoring protectedNetwork " + p);
1740 }
1741 }
1742
soma, kawata29444ae2019-05-23 09:30:40 +09001743 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1744
James Mattis02220e22021-03-13 19:27:21 -08001745 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001746 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001747 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001748 final IntentFilter userIntentFilter = new IntentFilter();
1749 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1750 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1751 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1752 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001753
James Mattis02220e22021-03-13 19:27:21 -08001754 // Listen to package add/removes for netd
1755 final IntentFilter packageIntentFilter = new IntentFilter();
1756 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1757 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1758 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1759 packageIntentFilter.addDataScheme("package");
1760 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001761 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001762
Motomu Utsumi1e51a642023-07-18 15:11:41 +09001763 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001764
Chalard Jean46bfbf02022-02-02 00:56:25 +09001765 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001766 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001767 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001768 } catch (RemoteException | ServiceSpecificException e) {
1769 loge("Error registering event listener :" + e);
1770 }
1771
Erik Kline05f2b402015-04-30 12:58:40 +09001772 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1773 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001774
chiachangwang7c17c282023-02-02 05:58:59 +00001775 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001776 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001777 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001778
1779 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001780 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001781 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1782 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001783 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001784 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1785 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001786
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001787 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001788 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001789 mNetworkRanker =
1790 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1791
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001792 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001793
Chiachang Wangc1215d32020-10-20 15:38:58 +08001794 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001795 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001796
Chalard Jean28018572020-12-21 18:36:52 +09001797 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1798 // request that doesn't allow fallback to the default network. It should never be visible
1799 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1800 // arguments like the handler or the DnsResolver.
1801 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001802 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001803 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001804 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001805 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001806 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001807 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1808 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001809
1810 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001811 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1812 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1813 // Even if it could, running on S would at least require mocking out the BPF map,
1814 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1815 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001816 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001817 mDscpPolicyTracker = new DscpPolicyTracker();
1818 }
Tyler Wear72388212021-09-09 14:49:02 -07001819 } catch (ErrnoException e) {
1820 loge("Unable to create DscpPolicyTracker");
1821 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001822
1823 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1824 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001825
Chalard Jeandf29a852023-05-29 17:02:43 +09001826 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001827 mCdmps = new CompanionDeviceManagerProxyService(context);
1828 } else {
1829 mCdmps = null;
1830 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001831
Chalard Jean2fb66f12023-08-25 12:50:37 +09001832 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
1833
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001834 mDestroyFrozenSockets = mDeps.isAtLeastU()
1835 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1836 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1837 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
1838 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001839 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1840 new UidFrozenStateChangedCallback() {
1841 @Override
1842 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1843 if (uids.length != frozenStates.length) {
1844 Log.wtf(TAG, "uids has length " + uids.length
1845 + " but frozenStates has length " + frozenStates.length);
1846 return;
1847 }
1848
1849 final UidFrozenStateChangedArgs args =
1850 new UidFrozenStateChangedArgs(uids, frozenStates);
1851
1852 mHandler.sendMessage(
1853 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1854 }
1855 };
1856
1857 final ActivityManager activityManager =
1858 mContext.getSystemService(ActivityManager.class);
1859 activityManager.registerUidFrozenStateChangedCallback(
1860 (Runnable r) -> r.run(), frozenStateChangedCallback);
1861 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001862 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001863
Xiao Ma0a171c02022-01-23 16:14:51 +00001864 /**
1865 * Check whether or not the device supports Ethernet transport.
1866 */
1867 public static boolean deviceSupportsEthernet(final Context context) {
1868 final PackageManager pm = context.getPackageManager();
1869 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1870 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1871 }
1872
Chalard Jean46adcf32018-04-18 20:18:38 +09001873 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001874 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1875 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001876 }
1877
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001878 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1879 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001880 final NetworkCapabilities netCap = new NetworkCapabilities();
1881 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001882 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001883 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001884 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001885 return netCap;
1886 }
1887
James Mattis45d81842021-01-10 14:24:24 -08001888 private NetworkRequest createDefaultRequest() {
1889 return createDefaultInternetRequestForTransport(
1890 TYPE_NONE, NetworkRequest.Type.REQUEST);
1891 }
1892
lucaslin3ba7cc22022-12-19 02:35:33 +00001893 private NetworkRequest createVpnRequest() {
1894 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1895 .withoutDefaultCapabilities()
1896 .addTransportType(TRANSPORT_VPN)
1897 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1898 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1899 .build();
1900 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1901 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1902 }
1903
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001904 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001905 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001906 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001907 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001908 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001909 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001910 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001911 netCap.addTransportType(transportType);
1912 }
James Mattis45d81842021-01-10 14:24:24 -08001913 return createNetworkRequest(type, netCap);
1914 }
1915
1916 private NetworkRequest createNetworkRequest(
1917 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001918 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001919 }
1920
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001921 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1922 NetworkRequest.Type type) {
1923 final NetworkCapabilities netCap = new NetworkCapabilities();
1924 netCap.clearAll();
1925 netCap.addCapability(capability);
1926 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1927 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1928 }
1929
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001930 // Used only for testing.
1931 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001932 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001933 // changing ContentResolver to make registerContentObserver non-final).
1934 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1935 // by subclassing SettingsObserver.
1936 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001937 void updateAlwaysOnNetworks() {
1938 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001939 }
1940
Erik Kline9a62f012018-03-21 07:18:33 -07001941 // See FakeSettingsProvider comment above.
1942 @VisibleForTesting
1943 void updatePrivateDnsSettings() {
1944 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1945 }
1946
paulhu51f77dc2021-06-07 02:34:20 +00001947 @VisibleForTesting
1948 void updateMobileDataPreferredUids() {
1949 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1950 }
1951
Patrick Rohr2857ac42022-01-21 14:58:16 +01001952 @VisibleForTesting
1953 void updateIngressRateLimit() {
1954 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1955 }
1956
Aaron Huang40b52442021-06-08 04:34:24 +08001957 @VisibleForTesting
1958 void simulateUpdateProxyInfo(@Nullable final Network network,
1959 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001960 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001961 new Pair<>(network, proxyInfo)).sendToTarget();
1962 }
1963
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001964 private void handleAlwaysOnNetworkRequest(
1965 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001966 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001967 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001968 handleAlwaysOnNetworkRequest(networkRequest, enable);
1969 }
1970
1971 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001972 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001973 if (enable == isEnabled) {
1974 return; // Nothing to do.
1975 }
1976
1977 if (enable) {
1978 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001979 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001980 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001981 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001982 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001983 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1984 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001985 }
1986 }
1987
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001988 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001989 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1990 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1991 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1992 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001993 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1994 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001995 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001996 }
1997
paulhu51f77dc2021-06-07 02:34:20 +00001998 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001999 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002000 private void registerSettingsCallbacks() {
2001 // Watch for global HTTP proxy changes.
2002 mSettingsObserver.observe(
2003 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2004 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2005
Chalard Jean46bfbf02022-02-02 00:56:25 +09002006 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002007 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002008 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002009 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2010
Chalard Jean46bfbf02022-02-02 00:56:25 +09002011 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002012 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002013 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002014 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002015
2016 // Watch for mobile data preferred uids changes.
2017 mSettingsObserver.observe(
2018 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2019 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002020
2021 // Watch for ingress rate limit changes.
2022 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002023 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002024 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2025 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002026 }
2027
Erik Kline31b4a9e2018-01-11 21:07:29 +09002028 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002029 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2030 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002031 }
2032 }
2033
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002034 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002035 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2036 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002037 return mNextNetworkRequestId++;
2038 }
2039
junyulai74f9a8b2018-06-13 15:00:37 +08002040 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002041 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002042 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002043 if (network == null) {
2044 return null;
2045 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002046 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002047 }
2048
2049 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002050 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002051 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002052 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002053 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002054
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002055 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002056 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002057 private NetworkAgentInfo getVpnForUid(int uid) {
2058 synchronized (mNetworkForNetId) {
2059 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2060 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002061 if (nai.isVPN() && nai.everConnected()
2062 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002063 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002064 }
2065 }
2066 }
2067 return null;
2068 }
2069
Chalard Jean46bfbf02022-02-02 00:56:25 +09002070 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002071 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002072 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002073 final NetworkAgentInfo nai = getVpnForUid(uid);
2074 if (nai != null) return nai.declaredUnderlyingNetworks;
2075 return null;
2076 }
2077
Lorenzo Colittia7574052021-01-19 01:33:05 +09002078 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002079 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002080
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002081 final Network[] networks = getVpnUnderlyingNetworks(uid);
2082 if (networks != null) {
2083 // getUnderlyingNetworks() returns:
2084 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2085 // empty array => the VPN explicitly said "no default network".
2086 // non-empty array => the VPN specified one or more default networks; we use the
2087 // first one.
2088 if (networks.length > 0) {
2089 nai = getNetworkAgentInfoForNetwork(networks[0]);
2090 } else {
2091 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002092 }
2093 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002094 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002095 }
2096
2097 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002098 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002099 */
paulhu7aeba372020-12-30 00:42:19 +08002100 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2101 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002102 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002103 if (ignoreBlocked) {
2104 return false;
2105 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002106 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002107 final long ident = Binder.clearCallingIdentity();
2108 try {
2109 final boolean metered = nc == null ? true : nc.isMetered();
2110 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2111 } finally {
2112 Binder.restoreCallingIdentity(ident);
2113 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002114 }
2115
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002116 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002117 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2118 return;
2119 }
Hugo Benichi47011212017-03-30 10:46:05 +09002120 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002121 synchronized (mBlockedAppUids) {
2122 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002123 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002124 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002125 blocked = false;
2126 } else {
2127 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002128 }
2129 }
Hugo Benichi47011212017-03-30 10:46:05 +09002130 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2131 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2132 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002133 }
2134
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002135 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002136 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2137 return;
2138 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002139 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002140 final int requestId = nri.getActiveRequest() != null
2141 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002142 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002143 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002144 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002145 }
2146
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002147 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002148 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002149 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002150 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002151 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002152 @NonNull
2153 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2154 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002155 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2156 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2157 // but only exists if an app asks about them or requests them. Ensure the requesting app
2158 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002159 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002160 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2161 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2162 null /* extraInfo */);
2163 }
2164 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002165 return filtered;
2166 }
2167
2168 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2169 boolean ignoreBlocked) {
2170 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2171 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002172 }
2173
2174 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002175 * Return NetworkInfo for the active (i.e., connected) network interface.
2176 * It is assumed that at most one network is active at a time. If more
2177 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002178 * @return the info for the active network, or {@code null} if none is
2179 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002180 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002181 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002182 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002183 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002184 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002185 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002186 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2187 if (nai == null) return null;
2188 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2189 maybeLogBlockedNetworkInfo(networkInfo, uid);
2190 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002191 }
2192
Paul Jensen1f567382015-02-13 14:18:39 -05002193 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002194 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002195 public Network getActiveNetwork() {
2196 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002197 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002198 }
2199
2200 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002201 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002202 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002203 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002204 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002205 }
2206
Chalard Jean46bfbf02022-02-02 00:56:25 +09002207 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002208 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002209 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2210 if (vpnNai != null) {
2211 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2212 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2213 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002214 }
Paul Jensen1f567382015-02-13 14:18:39 -05002215 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002216
James Mattis2516da32021-01-31 17:06:19 -08002217 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002218 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2219 ignoreBlocked)) {
2220 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002221 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002222 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002223 }
2224
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002225 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002226 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002227 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002228 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002229 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2230 if (nai == null) return null;
2231 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002232 }
2233
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002234 /** Returns a NetworkInfo object for a network that doesn't exist. */
2235 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2236 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2237 getNetworkTypeName(networkType), "" /* subtypeName */);
2238 info.setIsAvailable(true);
2239 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2240 // background data is restricted.
2241 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2242 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2243 ? DetailedState.BLOCKED
2244 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002245 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2246 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002247 return info;
2248 }
2249
Lorenzo Colittia7574052021-01-19 01:33:05 +09002250 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002251 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2252 return null;
2253 }
2254 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002255 if (nai == null) {
2256 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002257 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002258 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2259 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002260 }
2261
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002262 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002263 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002264 public NetworkInfo getNetworkInfo(int networkType) {
2265 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002266 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002267 if (getVpnUnderlyingNetworks(uid) != null) {
2268 // A VPN is active, so we may need to return one of its underlying networks. This
2269 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002270 // getNetworkAgentInfoForUid.
2271 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2272 if (nai == null) return null;
2273 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2274 if (networkInfo.getType() == networkType) {
2275 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002276 }
2277 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002278 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002279 }
2280
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002281 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002282 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002283 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002284 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002285 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002286 if (nai == null) return null;
2287 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002288 }
2289
2290 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002291 public NetworkInfo[] getAllNetworkInfo() {
2292 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002293 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002294 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2295 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002296 NetworkInfo info = getNetworkInfo(networkType);
2297 if (info != null) {
2298 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002299 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002300 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002301 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002302 }
2303
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002304 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002305 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002306 public Network getNetworkForType(int networkType) {
2307 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002308 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2309 return null;
2310 }
2311 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2312 if (nai == null) {
2313 return null;
2314 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002315 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002316 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2317 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002318 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002319 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002320 }
2321
2322 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002323 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002324 public Network[] getAllNetworks() {
2325 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002326 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002327 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002328 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002329 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002330 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002331 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002332 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002333 }
2334
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002335 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002336 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002337 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002338 // The basic principle is: if an app's traffic could possibly go over a
2339 // network, without the app doing anything multinetwork-specific,
2340 // (hence, by "default"), then include that network's capabilities in
2341 // the array.
2342 //
2343 // In the normal case, app traffic only goes over the system's default
2344 // network connection, so that's the only network returned.
2345 //
2346 // With a VPN in force, some app traffic may go into the VPN, and thus
2347 // over whatever underlying networks the VPN specifies, while other app
2348 // traffic may go over the system default network (e.g.: a split-tunnel
2349 // VPN, or an app disallowed by the VPN), so the set of networks
2350 // returned includes the VPN's underlying networks and the system
2351 // default.
2352 enforceAccessPermission();
2353
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002354 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002355
James Mattis2516da32021-01-31 17:06:19 -08002356 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2357 if (!nri.isBeingSatisfied()) {
2358 continue;
2359 }
2360 final NetworkAgentInfo nai = nri.getSatisfier();
2361 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2362 if (null != nc
2363 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2364 && !result.containsKey(nai.network)) {
2365 result.put(
2366 nai.network,
2367 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002368 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002369 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2370 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002371 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002372 }
2373
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002374 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002375 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002376 if (null != networks) {
2377 for (final Network network : networks) {
2378 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2379 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002380 result.put(
2381 network,
2382 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002383 nc,
2384 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002385 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002386 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002387 }
2388 }
2389 }
2390
2391 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2392 out = result.values().toArray(out);
2393 return out;
2394 }
2395
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002396 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2397 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2398 // can call sampleConnectivityState and make the checks on it.
2399 @NonNull
2400 private StatsEvent sampleConnectivityStateToStatsEvent() {
2401 final ConnectivityStateSample sample = sampleConnectivityState();
2402 return ConnectivityStatsLog.buildStatsEvent(
2403 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2404 sample.getNetworkCountPerTransports().toByteArray(),
2405 sample.getConnectionDurationPerTransports().toByteArray(),
2406 sample.getNetworkRequestCount().toByteArray(),
2407 sample.getNetworks().toByteArray());
2408 }
2409
2410 /**
2411 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2412 *
2413 * This is used for metrics. These snapshots will be sampled and constitute a base for
2414 * statistics about connectivity state of devices.
2415 */
2416 @VisibleForTesting
2417 @NonNull
2418 public ConnectivityStateSample sampleConnectivityState() {
2419 ensureRunningOnConnectivityServiceThread();
2420 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2421 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2422 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2423 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2424 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2425 return builder.build();
2426 }
2427
2428 private static NetworkCountPerTransports sampleNetworkCount(
2429 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2430 final SparseIntArray countPerTransports = new SparseIntArray();
2431 for (final NetworkAgentInfo nai : nais) {
2432 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2433 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2434 }
2435 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2436 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2437 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2438 c.setTransportTypes(countPerTransports.keyAt(i));
2439 c.setNetworkCount(countPerTransports.valueAt(i));
2440 builder.addNetworkCountForTransports(c);
2441 }
2442 return builder.build();
2443 }
2444
2445 private static ConnectionDurationPerTransports sampleConnectionDuration(
2446 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2447 final ConnectionDurationPerTransports.Builder builder =
2448 ConnectionDurationPerTransports.newBuilder();
2449 for (final NetworkAgentInfo nai : nais) {
2450 final ConnectionDurationForTransports.Builder c =
2451 ConnectionDurationForTransports.newBuilder();
2452 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2453 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2454 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2455 // Add millisPerSecond/2 to round up or down to the nearest value
2456 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2457 builder.addConnectionDurationForTransports(c);
2458 }
2459 return builder.build();
2460 }
2461
2462 private static NetworkRequestCount sampleNetworkRequestCount(
2463 @NonNull final Collection<NetworkRequestInfo> nris) {
2464 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2465 final SparseIntArray countPerType = new SparseIntArray();
2466 for (final NetworkRequestInfo nri : nris) {
2467 final int type;
2468 if (Process.SYSTEM_UID == nri.mAsUid) {
2469 // The request is filed "as" the system, so it's the system on its own behalf.
2470 type = RequestType.RT_SYSTEM.getNumber();
2471 } else if (Process.SYSTEM_UID == nri.mUid) {
2472 // The request is filed by the system as some other app, so it's the system on
2473 // behalf of an app.
2474 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2475 } else {
2476 // Not the system, so it's an app requesting on its own behalf.
2477 type = RequestType.RT_APP.getNumber();
2478 }
2479 countPerType.put(type, countPerType.get(type, 0));
2480 }
2481 for (int i = countPerType.size() - 1; i >= 0; --i) {
2482 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2483 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2484 r.setRequestCount(countPerType.valueAt(i));
2485 builder.addRequestCountForType(r);
2486 }
2487 return builder.build();
2488 }
2489
2490 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2491 final NetworkList.Builder builder = NetworkList.newBuilder();
2492 for (final NetworkAgentInfo nai : nais) {
2493 final NetworkCapabilities nc = nai.networkCapabilities;
2494 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2495 d.setTransportTypes((int) nc.getTransportTypesInternal());
2496 final MeteredState meteredState;
2497 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2498 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2499 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2500 meteredState = MeteredState.METERED_NO;
2501 } else {
2502 meteredState = MeteredState.METERED_YES;
2503 }
2504 d.setMeteredState(meteredState);
2505 final ValidatedState validatedState;
2506 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2507 validatedState = ValidatedState.VS_PORTAL;
2508 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2509 validatedState = ValidatedState.VS_PARTIAL;
2510 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2511 validatedState = ValidatedState.VS_VALID;
2512 } else {
2513 validatedState = ValidatedState.VS_INVALID;
2514 }
2515 d.setValidatedState(validatedState);
2516 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2517 d.setCapabilities(nc.getCapabilitiesInternal());
2518 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2519 builder.addNetworkDescription(d);
2520 }
2521 return builder.build();
2522 }
2523
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002524 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002525 public boolean isNetworkSupported(int networkType) {
2526 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002527 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002528 }
2529
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002530 /**
2531 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002532 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002533 * @return the ip properties for the active network, or {@code null} if
2534 * none is active
2535 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002536 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002537 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002538 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002539 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002540 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2541 if (nai == null) return null;
2542 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002543 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002544 }
2545
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002546 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002547 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002548 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002549 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002550 final LinkProperties lp = getLinkProperties(nai);
2551 if (lp == null) return null;
2552 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002553 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002554 }
2555
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002556 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002557 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002558 public LinkProperties getLinkProperties(Network network) {
2559 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002560 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2561 if (lp == null) return null;
2562 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002563 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002564 }
2565
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002566 @Nullable
2567 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002568 if (nai == null) {
2569 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002570 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002571 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002572 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002573 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002574 }
2575
lucaslinc582d502022-01-27 09:07:00 +08002576 @Override
2577 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002578 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002579 @NonNull String packageName, @Nullable String callingAttributionTag) {
2580 Objects.requireNonNull(packageName);
2581 Objects.requireNonNull(lp);
2582 enforceNetworkStackOrSettingsPermission();
2583 if (!checkAccessPermission(-1 /* pid */, uid)) {
2584 return null;
2585 }
2586 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2587 }
2588
Qingxi Lib2748102020-01-08 12:51:49 -08002589 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2590 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2591 }
2592
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002593 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002594 if (nai == null) return null;
2595 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002596 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002597 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002598 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002599 }
2600
2601 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002602 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2603 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002604 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002605 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002606 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002607 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002608 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002609 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002610 }
2611
lucaslinc582d502022-01-27 09:07:00 +08002612 @Override
lucaslind2b06132022-03-02 10:56:57 +08002613 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2614 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2615 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002616 Objects.requireNonNull(nc);
2617 Objects.requireNonNull(packageName);
2618 enforceNetworkStackOrSettingsPermission();
2619 if (!checkAccessPermission(-1 /* pid */, uid)) {
2620 return null;
2621 }
2622 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2623 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2624 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2625 callingAttributionTag);
2626 }
2627
lucaslin69e1aa92022-03-22 18:15:09 +08002628 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2629 if (nc.getUnderlyingNetworks() != null
2630 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2631 nc.setUnderlyingNetworks(null);
2632 }
2633 }
2634
Qingxi Libb8da982020-01-17 17:54:27 -08002635 @VisibleForTesting
2636 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002637 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002638 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2639 // this would be expensive (one more permission check every time any NC callback is
2640 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2641 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2642 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002643 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002644 if (!checkSettingsPermission(callerPid, callerUid)) {
2645 newNc.setUids(null);
2646 newNc.setSSID(null);
2647 }
Etan Cohen107ae952018-12-30 17:59:59 -08002648 if (newNc.getNetworkSpecifier() != null) {
2649 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2650 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002651 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2652 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002653 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2654 newNc.setAdministratorUids(new int[0]);
2655 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002656 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002657 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002658 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002659 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002660 }
lucaslin69e1aa92022-03-22 18:15:09 +08002661 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002662
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002663 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002664 }
2665
Roshan Pius98f59ec2021-02-23 08:47:39 -08002666 /**
2667 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002668 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002669 * NetworkCapabilities.
2670 * Note: This wrapper does not support any sort of invalidation and thus must not be
2671 * persistent or long-lived. It may only be used for the time necessary to
2672 * compute the redactions required by one particular NetworkCallback or
2673 * synchronous call.
2674 */
2675 private class RedactionPermissionChecker {
2676 private final int mCallingPid;
2677 private final int mCallingUid;
2678 @NonNull private final String mCallingPackageName;
2679 @Nullable private final String mCallingAttributionTag;
2680
2681 private Boolean mHasLocationPermission = null;
2682 private Boolean mHasLocalMacAddressPermission = null;
2683 private Boolean mHasSettingsPermission = null;
2684
2685 RedactionPermissionChecker(int callingPid, int callingUid,
2686 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2687 mCallingPid = callingPid;
2688 mCallingUid = callingUid;
2689 mCallingPackageName = callingPackageName;
2690 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002691 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002692
2693 private boolean hasLocationPermissionInternal() {
2694 final long token = Binder.clearCallingIdentity();
2695 try {
2696 return mLocationPermissionChecker.checkLocationPermission(
2697 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2698 null /* message */);
2699 } finally {
2700 Binder.restoreCallingIdentity(token);
2701 }
2702 }
2703
2704 /**
2705 * Returns whether the app holds location permission or not (might return cached result
2706 * if the permission was already checked before).
2707 */
2708 public boolean hasLocationPermission() {
2709 if (mHasLocationPermission == null) {
2710 // If there is no cached result, perform the check now.
2711 mHasLocationPermission = hasLocationPermissionInternal();
2712 }
2713 return mHasLocationPermission;
2714 }
2715
2716 /**
2717 * Returns whether the app holds local mac address permission or not (might return cached
2718 * result if the permission was already checked before).
2719 */
2720 public boolean hasLocalMacAddressPermission() {
2721 if (mHasLocalMacAddressPermission == null) {
2722 // If there is no cached result, perform the check now.
2723 mHasLocalMacAddressPermission =
2724 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2725 }
2726 return mHasLocalMacAddressPermission;
2727 }
2728
2729 /**
2730 * Returns whether the app holds settings permission or not (might return cached
2731 * result if the permission was already checked before).
2732 */
2733 public boolean hasSettingsPermission() {
2734 if (mHasSettingsPermission == null) {
2735 // If there is no cached result, perform the check now.
2736 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2737 }
2738 return mHasSettingsPermission;
2739 }
2740 }
2741
2742 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2743 @NetworkCapabilities.NetCapability long redaction) {
2744 return (redactions & redaction) != 0;
2745 }
2746
2747 /**
2748 * Use the provided |applicableRedactions| to check the receiving app's
2749 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2750 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2751 * before being sent to the corresponding app.
2752 */
2753 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2754 @NetworkCapabilities.RedactionType long applicableRedactions,
2755 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2756 boolean includeLocationSensitiveInfo) {
2757 long redactions = applicableRedactions;
2758 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2759 if (includeLocationSensitiveInfo
2760 && redactionPermissionChecker.hasLocationPermission()) {
2761 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2762 }
2763 }
2764 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2765 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2766 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2767 }
2768 }
2769 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2770 if (redactionPermissionChecker.hasSettingsPermission()) {
2771 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2772 }
2773 }
2774 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002775 }
2776
Qingxi Lib2748102020-01-08 12:51:49 -08002777 @VisibleForTesting
2778 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002779 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002780 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002781 int callingPid, int callingUid, @NonNull String callingPkgName,
2782 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002783 if (nc == null) {
2784 return null;
2785 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002786 // Avoid doing location permission check if the transport info has no location sensitive
2787 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002788 final RedactionPermissionChecker redactionPermissionChecker =
2789 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2790 callingAttributionTag);
2791 final long redactions = retrieveRequiredRedactions(
2792 nc.getApplicableRedactions(), redactionPermissionChecker,
2793 includeLocationSensitiveInfo);
2794 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002795 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002796 // TODO : calling UID is redacted because apps should generally not know what UID is
2797 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002798 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002799 newNc.setOwnerUid(INVALID_UID);
2800 return newNc;
2801 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002802 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2803 if (nc.hasTransport(TRANSPORT_VPN)) {
2804 // Owner UIDs already checked above. No need to re-check.
2805 return newNc;
2806 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002807 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2808 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002809 // compatibility for older apps.
2810 if (!includeLocationSensitiveInfo
2811 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002812 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002813 newNc.setOwnerUid(INVALID_UID);
2814 return newNc;
2815 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002816 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002817 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002818 newNc.setOwnerUid(INVALID_UID);
2819 }
Qingxi Lib2748102020-01-08 12:51:49 -08002820 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002821 }
2822
lucaslinc582d502022-01-27 09:07:00 +08002823 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002824 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2825 LinkProperties lp, int callerPid, int callerUid) {
2826 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002827 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2828 // this would be expensive (one more permission check every time any LP callback is
2829 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2830 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2831 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002832
2833 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2834 final boolean needsSanitization =
2835 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2836 if (!needsSanitization) {
2837 return new LinkProperties(lp);
2838 }
2839
2840 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002841 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002842 }
2843
2844 final LinkProperties newLp = new LinkProperties(lp);
2845 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2846 // object gets parceled.
2847 newLp.setCaptivePortalApiUrl(null);
2848 newLp.setCaptivePortalData(null);
2849 return newLp;
2850 }
2851
Roshan Pius08c94fb2020-01-16 12:17:17 -08002852 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2853 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002854 // There is no need to track the effective UID of the request here. If the caller
2855 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002856 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002857 // Unprivileged apps can only pass in null or their own UID.
2858 if (nc.getUids() == null) {
2859 // If the caller passes in null, the callback will also match networks that do not
2860 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2861 // In this case, redact everything in the request immediately. This ensures that the
2862 // app is not able to get any redacted information by filing an unredacted request
2863 // and observing whether the request matches something.
2864 if (nc.getNetworkSpecifier() != null) {
2865 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2866 }
2867 } else {
2868 nc.setSingleUid(callerUid);
2869 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002870 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002871 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002872 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002873
2874 // Clear owner UID; this can never come from an app.
2875 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002876 }
2877
Chalard Jean38354d12018-03-20 19:13:57 +09002878 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002879 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002880 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2881 }
2882 }
2883
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002884 @Override
2885 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2886 enforceAccessPermission();
2887 final int callerUid = Binder.getCallingUid();
2888 final long token = Binder.clearCallingIdentity();
2889 try {
2890 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2891 } finally {
2892 Binder.restoreCallingIdentity(token);
2893 }
2894 }
2895
junyulaiebd15162021-03-03 12:09:05 +08002896 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002897 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002898 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002899 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002900 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002901
Serik Beketayev05130302021-01-15 16:47:25 -08002902 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002903 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002904 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2905 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002906 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002907 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002908 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002909 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2910 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002911 }
2912 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002913 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002914 }
2915
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002916 @Override
junyulaiebd15162021-03-03 12:09:05 +08002917 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002918 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002919 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002920 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002921
2922 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2923 for (Network network : getAllNetworks()) {
2924 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002925 final boolean includeNetwork = (nai != null) && nai.isCreated();
2926 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002927 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2928 // NetworkCapabilities, which may contain UIDs of apps to which the
2929 // network applies. Should the UIDs be cleared so as not to leak or
2930 // interfere ?
2931 result.add(nai.getNetworkStateSnapshot());
2932 }
2933 }
2934 return result;
2935 }
2936
2937 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002938 public boolean isActiveNetworkMetered() {
2939 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002940
Qingxi Lib2748102020-01-08 12:51:49 -08002941 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002942 if (caps != null) {
2943 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2944 } else {
2945 // Always return the most conservative value
2946 return true;
2947 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002948 }
2949
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002950 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002951 * Ensures that the system cannot call a particular method.
2952 */
2953 private boolean disallowedBecauseSystemCaller() {
2954 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002955 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2956 // for devices launched with Q and above. However, existing devices upgrading to Q and
2957 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002958 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002959 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002960 log("This method exists only for app backwards compatibility"
2961 + " and must not be called by system services.");
2962 return true;
2963 }
2964 return false;
2965 }
2966
paulhub2c28682021-08-18 18:35:54 +08002967 private int getAppUid(final String app, final UserHandle user) {
2968 final PackageManager pm =
2969 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2970 final long token = Binder.clearCallingIdentity();
2971 try {
2972 return pm.getPackageUid(app, 0 /* flags */);
2973 } catch (PackageManager.NameNotFoundException e) {
2974 return -1;
2975 } finally {
2976 Binder.restoreCallingIdentity(token);
2977 }
2978 }
2979
2980 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2981 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2982 if (getAppUid(packageName, user) != callingUid) {
2983 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2984 }
2985 }
2986
Lorenzo Colitti23862912018-09-28 11:31:55 +09002987 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002988 * Ensure that a network route exists to deliver traffic to the specified
2989 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002990 * @param networkType the type of the network over which traffic to the
2991 * specified host is to be routed
2992 * @param hostAddress the IP address of the host to which the route is
2993 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002994 * @return {@code true} on success, {@code false} on failure
2995 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002996 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002997 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2998 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002999 if (disallowedBecauseSystemCaller()) {
3000 return false;
3001 }
paulhub2c28682021-08-18 18:35:54 +08003002 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003003 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003004 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003005 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003006 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003007
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003008 InetAddress addr;
3009 try {
3010 addr = InetAddress.getByAddress(hostAddress);
3011 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003012 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003013 return false;
3014 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003015
The Android Open Source Project28527d22009-03-03 19:31:44 -08003016 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003017 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003018 return false;
3019 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003020
3021 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3022 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003023 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003024 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3025 } else {
3026 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3027 }
3028 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003029 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003030
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003031 DetailedState netState;
3032 synchronized (nai) {
3033 netState = nai.networkInfo.getDetailedState();
3034 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003035
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003036 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003037 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003038 log("requestRouteToHostAddress on down network "
3039 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003040 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003041 }
3042 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003043 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003044
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003045 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003046 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003047 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003048 LinkProperties lp;
3049 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003050 synchronized (nai) {
3051 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003052 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003053 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003054 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003055 if (DBG) {
3056 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3057 }
Wink Saville32506bc2013-06-29 21:10:57 -07003058 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003059 } finally {
3060 Binder.restoreCallingIdentity(token);
3061 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003062 }
3063
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003064 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003065 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003066 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003067 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003068 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003069 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003070 if (bestRoute.getGateway().equals(addr)) {
3071 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003072 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003073 } else {
3074 // if we will connect to this through another route, add a direct route
3075 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003076 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003077 }
3078 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003079 if (DBG) log("Adding legacy route " + bestRoute +
3080 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003081
3082 final String dst = bestRoute.getDestinationLinkAddress().toString();
3083 final String nextHop = bestRoute.hasGateway()
3084 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003085 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003086 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3087 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003088 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003089 return false;
3090 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003091 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003092 }
3093
paulhu7c0a2e62021-01-08 00:51:49 +08003094 class DnsResolverUnsolicitedEventCallback extends
3095 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003096 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003097 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003098 try {
3099 mHandler.sendMessage(mHandler.obtainMessage(
3100 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003101 new PrivateDnsValidationUpdate(event.netId,
3102 InetAddresses.parseNumericAddress(event.ipAddress),
3103 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003104 } catch (IllegalArgumentException e) {
3105 loge("Error parsing ip address in validation event");
3106 }
3107 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003108
3109 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003110 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3111 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003112 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3113 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3114 // event callback for certain nai. e.g. cellular. Register here to pass to
3115 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003116 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003117 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3118 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003119 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003120 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003121 }
3122 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003123
3124 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003125 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3126 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3127 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003128 }
dalyk1720e542018-03-05 12:42:22 -05003129
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003130 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003131 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003132 return this.VERSION;
3133 }
3134
3135 @Override
3136 public String getInterfaceHash() {
3137 return this.HASH;
3138 }
paulhu7c0a2e62021-01-08 00:51:49 +08003139 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003140
3141 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003142 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3143 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003144
paulhu7c0a2e62021-01-08 00:51:49 +08003145 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003146 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003147 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003148 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003149 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003150 }
3151 }
3152
Sudheer Shanka9967d462021-03-18 19:09:25 +00003153 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003154 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003155 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003156 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3157 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003158 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003159 };
3160
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003161 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003162 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003163 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003164 }
3165
Mark Fasheh7c999d82023-05-04 20:23:11 +00003166 static final class UidFrozenStateChangedArgs {
3167 final int[] mUids;
3168 final int[] mFrozenStates;
3169
3170 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3171 mUids = uids;
3172 mFrozenStates = frozenStates;
3173 }
3174 }
3175
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003176 /**
3177 * Check if the cell network is idle.
3178 * @return true if the cell network state is idle
3179 * false if the cell network state is active or unknown
3180 */
3181 private boolean isCellNetworkIdle() {
3182 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3183 if (defaultNai == null
3184 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3185 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3186 // cell network is not the default network, cell network state is unknown.
3187 // TODO(b/279380356): Track cell network state when the cell is not the default network
3188 return false;
3189 }
3190
3191 return !mNetworkActivityTracker.isDefaultNetworkActive();
3192 }
3193
Mark Fasheh7c999d82023-05-04 20:23:11 +00003194 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003195 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003196
3197 for (int i = 0; i < uids.length; i++) {
3198 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003199 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003200 } else {
3201 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003202 }
3203 }
3204
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003205 if (ownerUids.isEmpty()) {
3206 return;
3207 }
3208
3209 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3210 // Delay closing sockets to avoid waking the cell modem up.
3211 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3212 // than waking cell modem up.
3213 mPendingFrozenUids.addAll(ownerUids);
3214 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003215 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003216 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003217 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003218 loge("Exception in socket destroy: " + e);
3219 }
3220 }
3221 }
3222
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003223 private void closePendingFrozenSockets() {
3224 ensureRunningOnConnectivityServiceThread();
3225
3226 try {
3227 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3228 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3229 loge("Failed to close pending frozen app sockets: " + e);
3230 }
3231 mPendingFrozenUids.clear();
3232 }
3233
3234 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3235 mNetworkActivityTracker.handleReportNetworkActivity(params);
3236
3237 if (mDelayDestroyFrozenSockets
3238 && params.isActive
3239 && params.label == TRANSPORT_CELLULAR
3240 && !mPendingFrozenUids.isEmpty()) {
3241 closePendingFrozenSockets();
3242 }
3243 }
3244
3245 /**
3246 * If the cellular network is no longer the default network, close pending frozen sockets.
3247 *
3248 * @param newNetwork new default network
3249 * @param oldNetwork old default network
3250 */
3251 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3252 NetworkAgentInfo oldNetwork) {
3253 final boolean isOldNetworkCellular = oldNetwork != null
3254 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3255 final boolean isNewNetworkCellular = newNetwork != null
3256 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3257
3258 if (isOldNetworkCellular
3259 && !isNewNetworkCellular
3260 && !mPendingFrozenUids.isEmpty()) {
3261 closePendingFrozenSockets();
3262 }
3263 }
3264
3265 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3266 pw.println("CloseFrozenAppSockets:");
3267 pw.increaseIndent();
3268 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3269 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3270 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3271 pw.decreaseIndent();
3272 }
3273
Junyu Lai155760b2023-10-05 14:51:00 +08003274 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3275 pw.println("Bpf Program Status:");
3276 pw.increaseIndent();
3277 try {
3278 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003279 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003280 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003281 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003282 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003283 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003284 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003285 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003286 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003287 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003288 } catch (IOException e) {
3289 pw.println(" IOException");
3290 }
3291 pw.decreaseIndent();
3292 }
3293
Mark Fasheh7c999d82023-05-04 20:23:11 +00003294 @VisibleForTesting
3295 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003296 @VisibleForTesting
3297 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3298 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003299
Paul Jensen83f5d572014-08-29 09:54:01 -04003300 private void enforceInternetPermission() {
3301 mContext.enforceCallingOrSelfPermission(
3302 android.Manifest.permission.INTERNET,
3303 "ConnectivityService");
3304 }
3305
The Android Open Source Project28527d22009-03-03 19:31:44 -08003306 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003307 mContext.enforceCallingOrSelfPermission(
3308 android.Manifest.permission.ACCESS_NETWORK_STATE,
3309 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003310 }
3311
lucaslinc582d502022-01-27 09:07:00 +08003312 private boolean checkAccessPermission(int pid, int uid) {
3313 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3314 == PERMISSION_GRANTED;
3315 }
3316
paulhua6ee2122021-02-22 15:40:43 +08003317 /**
3318 * Performs a strict and comprehensive check of whether a calling package is allowed to
3319 * change the state of network, as the condition differs for pre-M, M+, and
3320 * privileged/preinstalled apps. The caller is expected to have either the
3321 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3322 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3323 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3324 * permission and cannot be revoked. See http://b/23597341
3325 *
3326 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3327 * of this app will be updated to the current time.
3328 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003329 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003330 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3331 == PackageManager.PERMISSION_GRANTED) {
3332 return;
3333 }
3334
3335 if (callingPkg == null) {
3336 throw new SecurityException("Calling package name is null.");
3337 }
3338
3339 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3340 final int uid = mDeps.getCallingUid();
3341 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3342 callingPkg, callingAttributionTag, null /* message */);
3343
3344 if (mode == AppOpsManager.MODE_ALLOWED) {
3345 return;
3346 }
3347
3348 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3349 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3350 return;
3351 }
3352
3353 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3354 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3355 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003356 }
3357
Charles He9369e612017-05-15 17:07:18 +01003358 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003359 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003360 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003361 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003362 }
3363
Quang Luong98858d62023-02-11 00:25:24 +00003364 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003365 enforceAnyPermissionOf(mContext,
3366 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003367 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003368 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3369 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3370 }
3371
paulhu8e96a752019-08-12 16:25:11 +08003372 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003373 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003374 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003375 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003376 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003377 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003378 }
3379
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003380 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003381 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003382 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003383 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003384 android.Manifest.permission.NETWORK_SETTINGS,
3385 android.Manifest.permission.NETWORK_FACTORY,
3386 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3387 }
3388
3389 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003390 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003391 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003392 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003393 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3394 android.Manifest.permission.NETWORK_FACTORY,
3395 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3396 }
3397
lucaslin69e1aa92022-03-22 18:15:09 +08003398 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3399 return PERMISSION_GRANTED == mContext.checkPermission(
3400 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3401 || PERMISSION_GRANTED == mContext.checkPermission(
3402 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3403 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003404 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003405 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003406 }
3407
Chalard Jean9a396cc2018-02-21 18:43:54 +09003408 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003409 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003410 android.Manifest.permission.NETWORK_SETTINGS,
3411 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003412 }
3413
3414 private boolean checkSettingsPermission(int pid, int uid) {
3415 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003416 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3417 || PERMISSION_GRANTED == mContext.checkPermission(
3418 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003419 }
3420
paulhu8e96a752019-08-12 16:25:11 +08003421 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003422 enforceNetworkStackPermissionOr(mContext,
3423 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003424 }
3425
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003426 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003427 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003428 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003429 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003430 }
3431
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003432 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003433 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003434 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3435 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003436 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003437 }
3438
James Mattis8378aec2021-01-26 14:05:36 -08003439 private void enforceOemNetworkPreferencesPermission() {
3440 mContext.enforceCallingOrSelfPermission(
3441 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3442 "ConnectivityService");
3443 }
3444
James Mattisfa270db2021-05-31 17:11:10 -07003445 private void enforceManageTestNetworksPermission() {
3446 mContext.enforceCallingOrSelfPermission(
3447 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3448 "ConnectivityService");
3449 }
3450
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003451 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003452 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003453 android.Manifest.permission.NETWORK_STACK,
3454 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003455 }
3456
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003457 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003458 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003459 android.Manifest.permission.NETWORK_STACK,
3460 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3461 }
3462
paulhu1a407652019-03-22 16:35:06 +08003463 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003464 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003465 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003466 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3467 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003468 }
3469
Paul Hu8fc2a552022-05-04 18:44:42 +08003470 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3471 boolean checkUidsAllowedList) {
3472 if (PermissionUtils.checkAnyPermissionOf(mContext,
3473 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3474 return true;
3475 }
3476
3477 // fallback to ConnectivityInternalPermission
3478 // TODO: Remove this fallback check after all apps have declared
3479 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3480 if (PermissionUtils.checkAnyPermissionOf(mContext,
3481 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3482 return true;
3483 }
3484
3485 // Check whether uid is in allowed on restricted networks list.
3486 if (checkUidsAllowedList
3487 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3488 return true;
3489 }
3490 return false;
3491 }
3492
3493 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3494 final int callingUid = mDeps.getCallingUid();
3495 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3496 throw new SecurityException("ConnectivityService: user " + callingUid
3497 + " has no permission to access restricted network.");
3498 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003499 }
3500
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003501 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003502 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003503 }
3504
Roshan Pius98f59ec2021-02-23 08:47:39 -08003505 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3506 return PERMISSION_GRANTED == mContext.checkPermission(
3507 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3508 }
3509
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003510 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003511 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003512 }
3513
3514 private void sendInetConditionBroadcast(NetworkInfo info) {
3515 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3516 }
3517
Wink Saville4f0de1e2011-08-04 15:01:58 -07003518 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003519 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003520 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003521 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003522 if (info.isFailover()) {
3523 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3524 info.setFailover(false);
3525 }
3526 if (info.getReason() != null) {
3527 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3528 }
3529 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003530 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3531 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003532 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003533 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003534 return intent;
3535 }
3536
3537 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3538 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3539 }
3540
Michael Groover73f69482023-01-27 11:01:25 -06003541 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3542 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003543 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3544 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003545 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003546 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003547 if (!mSystemReady
3548 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003549 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003550 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003551 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003552 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003553 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003554 }
3555
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003556 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003557 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003558 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003559 final NetworkInfo ni = intent.getParcelableExtra(
3560 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003561 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3562 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003563 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003564 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003565 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003566 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003567 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003568 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003569 } finally {
3570 Binder.restoreCallingIdentity(ident);
3571 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003572 }
3573 }
3574
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003575 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3576 NetworkInfo info) {
3577 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003578 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003579
3580 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3581 try {
3582 // This allows us to discard older broadcasts still waiting to be delivered
3583 // which have the same namespace and key.
3584 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3585 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3586 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003587 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003588 } catch (UnsupportedApiLevelException e) {
3589 Log.wtf(TAG, "Using unsupported API" + e);
3590 }
3591 }
3592
3593 @VisibleForTesting
3594 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3595 final StringBuilder sb = new StringBuilder();
3596 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3597 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3598 sb.append(info.getExtraInfo());
3599 return sb.toString();
3600 }
3601
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003602 /**
Aaron Huang96011892020-06-27 07:18:23 +08003603 * Called by SystemServer through ConnectivityManager when the system is ready.
3604 */
3605 @Override
3606 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003607 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003608 throw new SecurityException("Calling Uid is not system uid.");
3609 }
3610 systemReadyInternal();
3611 }
3612
3613 /**
3614 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003615 */
3616 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003617 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003618 // Load flags after PackageManager is ready to query module version
3619 mFlags.loadFlags(mDeps, mContext);
3620
Aaron Huang9a57acf2020-12-08 10:03:29 +08003621 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3622 // listening network request which is sent by MultipathPolicyTracker won't be added
3623 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3624 // be called after PermissionMonitor#startMonitoring().
3625 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3626 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3627 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003628 final ConditionVariable startMonitoringDone = new ConditionVariable();
3629 mHandler.post(() -> {
3630 mPermissionMonitor.startMonitoring();
3631 startMonitoringDone.open();
3632 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003633 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003634 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003635
Hugo Benichie5220992017-04-26 14:53:28 +09003636 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003637 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003638 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003639 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003640 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003641 }
3642 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003643
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003644 // Create network requests for always-on networks.
3645 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003646
3647 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003648 // Note that updating can be skipped here if the list is empty only because no uid
3649 // rules are applied before system ready. Normally, the empty uid list means to clear
3650 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003651 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3652 updateMobileDataPreferredUids();
3653 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003654
3655 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003656 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003657 mBpfNetMaps.setPullAtomCallback(mContext);
3658 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003659 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3660 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003661 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3662 // have permission problem. While CV#block() is unbounded in time and can in principle block
3663 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3664 // could have blocked forever too.
3665 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003666 }
3667
The Android Open Source Project28527d22009-03-03 19:31:44 -08003668 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003669 * Start listening for default data network activity state changes.
3670 */
3671 @Override
3672 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003673 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003674 }
3675
3676 /**
3677 * Stop listening for default data network activity state changes.
3678 */
3679 @Override
3680 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003681 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003682 }
3683
3684 /**
3685 * Check whether the default network radio is currently active.
3686 */
3687 @Override
3688 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003689 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003690 }
3691
3692 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003693 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003694 * and set it on it's iface.
3695 */
Junyu Lai970963e2022-10-25 15:46:47 +08003696 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003697 final String iface = newLp.getInterfaceName();
3698 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003699 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003700 // Silently ignore unset MTU value.
3701 return;
3702 }
Hansen Kurli04252032022-12-07 11:21:49 +00003703 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3704 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3705 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003706 return;
3707 }
Hansen Kurli04252032022-12-07 11:21:49 +00003708 // Cannot set MTU without interface name
3709 if (TextUtils.isEmpty(iface)) {
3710 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003711 return;
3712 }
sy.yun4aa73922013-09-02 05:24:09 +09003713
Hansen Kurli04252032022-12-07 11:21:49 +00003714 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3715 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003716 return;
3717 }
3718
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003719 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003720 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003721 mNetd.interfaceSetMtu(iface, mtu);
3722 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003723 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003724 }
3725 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003726
Chenbo Feng15416292018-11-08 17:36:21 -08003727 @VisibleForTesting
3728 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003729
Junyu Lai970963e2022-10-25 15:46:47 +08003730 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003731 String[] values = null;
3732 if (tcpBufferSizes != null) {
3733 values = tcpBufferSizes.split(",");
3734 }
3735
3736 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003737 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003738 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3739 values = tcpBufferSizes.split(",");
3740 }
3741
3742 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3743
3744 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003745 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003746
Chenbo Feng15416292018-11-08 17:36:21 -08003747 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3748 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3749 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003750 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003751 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003752 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003753 }
3754 }
3755
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003756 @Override
3757 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003758 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003759 NETWORK_RESTORE_DELAY_PROP_NAME);
3760 if(restoreDefaultNetworkDelayStr != null &&
3761 restoreDefaultNetworkDelayStr.length() != 0) {
3762 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003763 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003764 } catch (NumberFormatException e) {
3765 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003766 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003767 // if the system property isn't set, use the value for the apn type
3768 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3769
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003770 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3771 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003772 }
3773 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003774 }
3775
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003776 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003777 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003778 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003779 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003780 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003781 // Start gathering diagnostic information.
3782 netDiags.add(new NetworkDiagnostics(
3783 nai.network,
3784 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003785 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003786 DIAG_TIME_MS));
3787 }
3788
3789 for (NetworkDiagnostics netDiag : netDiags) {
3790 pw.println();
3791 netDiag.waitForMeasurements();
3792 netDiag.dump(pw);
3793 }
3794 }
3795
The Android Open Source Project28527d22009-03-03 19:31:44 -08003796 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003797 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3798 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003799 if (!checkDumpPermission(mContext, TAG, writer)) return;
3800
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003801 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003802 }
3803
lucaslin99473f62020-12-10 15:10:54 +08003804 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3805 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3806 != PackageManager.PERMISSION_GRANTED) {
3807 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003808 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003809 + " due to missing android.permission.DUMP permission");
3810 return false;
3811 } else {
3812 return true;
3813 }
3814 }
3815
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003816 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003817 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003818
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003819 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003820 dumpNetworkDiagnostics(pw);
3821 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003822 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003823 dumpNetworks(pw);
3824 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003825 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003826 dumpNetworkRequests(pw);
3827 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003828 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3829 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3830 dumpTrafficController(pw, fd, verbose);
3831 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003832 }
Erik Kline9647f382015-06-05 17:47:34 +09003833
Junyu Lai0da479b2022-04-20 15:06:29 +08003834 pw.println("NetworkProviders for:");
3835 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003836 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003837 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003838 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003839 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003840 pw.println();
3841
Chalard Jean5b409c72021-02-04 13:12:59 +09003842 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003843 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003844 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003845 pw.println("none");
3846 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003847 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003848 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003849 pw.println();
3850
James Mattis8b298a02021-06-01 22:34:04 -07003851 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003852 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003853 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003854 pw.decreaseIndent();
3855 pw.println();
3856
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003857 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003858 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003859 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003860 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003861 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003862
junyulaif2c67e42018-08-07 19:50:45 +08003863 pw.println("Status for known UIDs:");
3864 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003865 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003866 for (int i = 0; i < size; i++) {
3867 // Don't crash if the array is modified while dumping in bugreports.
3868 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003869 final int uid = mUidBlockedReasons.keyAt(i);
3870 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3871 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003872 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003873 } catch (ArrayIndexOutOfBoundsException e) {
3874 pw.println(" ArrayIndexOutOfBoundsException");
3875 } catch (ConcurrentModificationException e) {
3876 pw.println(" ConcurrentModificationException");
3877 }
3878 }
3879 pw.println();
3880 pw.decreaseIndent();
3881
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003882 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003883 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003884 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003885 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003886 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003887
Junyu Lai0da479b2022-04-20 15:06:29 +08003888 pw.println("Network Offers:");
3889 pw.increaseIndent();
3890 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3891 pw.println(offerInfo.offer);
3892 }
3893 pw.decreaseIndent();
3894 pw.println();
3895
Robert Greenwalt94e22142014-07-30 16:31:24 -07003896 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003897
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003898 pw.println();
markchien5e866652019-09-30 14:40:57 +08003899 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003900
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003901 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003902 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003903
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003904 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003905 dumpCloseFrozenAppSockets(pw);
3906
3907 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003908 dumpBpfProgramStatus(pw);
3909
3910 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003911
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003912 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003913 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003914 pw.println("mNetworkRequestInfoLogs (most recent first):");
3915 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003916 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003917 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003918
3919 pw.println();
3920 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3921 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003922 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003923 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003924
3925 pw.println();
3926 pw.println("NetTransition WakeLock activity (most recent first):");
3927 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003928 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3929 pw.println("total releases: " + mTotalWakelockReleases);
3930 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3931 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3932 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3933 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3934 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3935 }
James Mattiscb1e0362021-04-06 17:07:42 -07003936 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003937
3938 pw.println();
3939 pw.println("bandwidth update requests (by uid):");
3940 pw.increaseIndent();
3941 synchronized (mBandwidthRequests) {
3942 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3943 pw.println("[" + mBandwidthRequests.keyAt(i)
3944 + "]: " + mBandwidthRequests.valueAt(i));
3945 }
3946 }
3947 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003948 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003949
James Mattiscb1e0362021-04-06 17:07:42 -07003950 pw.println();
3951 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3952 pw.increaseIndent();
3953 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003954 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003955 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003956
3957 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003958
3959 pw.println();
3960 pw.println("Permission Monitor:");
3961 pw.increaseIndent();
3962 mPermissionMonitor.dump(pw);
3963 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003964
3965 pw.println();
3966 pw.println("Legacy network activity:");
3967 pw.increaseIndent();
3968 mNetworkActivityTracker.dump(pw);
3969 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003970 }
3971
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003972 private void dumpNetworks(IndentingPrintWriter pw) {
3973 for (NetworkAgentInfo nai : networksSortedById()) {
3974 pw.println(nai.toString());
3975 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003976 pw.println("Nat464Xlat:");
3977 pw.increaseIndent();
3978 nai.dumpNat464Xlat(pw);
3979 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003980 pw.println(String.format(
3981 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3982 nai.numForegroundNetworkRequests(),
3983 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3984 nai.numBackgroundNetworkRequests(),
3985 nai.numNetworkRequests()));
3986 pw.increaseIndent();
3987 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3988 pw.println(nai.requestAt(i).toString());
3989 }
3990 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003991 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003992 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003993 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003994 pw.decreaseIndent();
3995 pw.decreaseIndent();
3996 }
3997 }
3998
James Mattis8b298a02021-06-01 22:34:04 -07003999 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4000 if (!mProfileNetworkPreferences.isEmpty()) {
4001 pw.println("Profile preferences:");
4002 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004003 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004004 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004005 }
James Mattis8b298a02021-06-01 22:34:04 -07004006 if (!mOemNetworkPreferences.isEmpty()) {
4007 pw.println("OEM preferences:");
4008 pw.increaseIndent();
4009 pw.println(mOemNetworkPreferences);
4010 pw.decreaseIndent();
4011 }
4012 if (!mMobileDataPreferredUids.isEmpty()) {
4013 pw.println("Mobile data preferred UIDs:");
4014 pw.increaseIndent();
4015 pw.println(mMobileDataPreferredUids);
4016 pw.decreaseIndent();
4017 }
James Mattis45d81842021-01-10 14:24:24 -08004018
James Mattis8b298a02021-06-01 22:34:04 -07004019 pw.println("Default requests:");
4020 pw.increaseIndent();
4021 dumpPerAppDefaultRequests(pw);
4022 pw.decreaseIndent();
4023 }
4024
4025 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004026 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4027 if (mDefaultRequest == defaultRequest) {
4028 continue;
4029 }
4030
James Mattis8b298a02021-06-01 22:34:04 -07004031 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4032 final String networkOutput;
4033 if (null == satisfier) {
4034 networkOutput = "null";
4035 } else if (mNoServiceNetwork.equals(satisfier)) {
4036 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004037 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004038 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004039 }
James Mattis8b298a02021-06-01 22:34:04 -07004040 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4041 ? "" : " asUid: " + defaultRequest.mAsUid;
4042 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4043 + defaultRequest.mPid + asUidString + "]";
4044 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4045 + " Preference order: " + defaultRequest.mPreferenceOrder
4046 + " Tracked UIDs: " + defaultRequest.getUids();
4047 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004048 }
4049 }
4050
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004051 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004052 NetworkRequestInfo[] infos = null;
4053 while (infos == null) {
4054 try {
4055 infos = requestsSortedById();
4056 } catch (ConcurrentModificationException e) {
4057 // mNetworkRequests should only be accessed from handler thread, except dump().
4058 // As dump() is never called in normal usage, it would be needlessly expensive
4059 // to lock the collection only for its benefit. Instead, retry getting the
4060 // requests if ConcurrentModificationException is thrown during dump().
4061 }
4062 }
4063 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004064 pw.println(nri.toString());
4065 }
4066 }
4067
Ken Chene6d511f2022-01-25 11:10:42 +08004068 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4069 boolean verbose) {
4070 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004071 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004072 } catch (ServiceSpecificException e) {
4073 pw.println(e.getMessage());
4074 } catch (IOException e) {
4075 loge("Dump BPF maps failed, " + e);
4076 }
4077 }
4078
Chalard Jean524f0b12021-10-25 21:11:56 +09004079 private void dumpAllRequestInfoLogsToLogcat() {
4080 try (PrintWriter logPw = new PrintWriter(new Writer() {
4081 @Override
4082 public void write(final char[] cbuf, final int off, final int len) {
4083 // This method is called with 0-length and 1-length arrays for empty strings
4084 // or strings containing only the DEL character.
4085 if (len <= 1) return;
4086 Log.e(TAG, new String(cbuf, off, len));
4087 }
4088 @Override public void flush() {}
4089 @Override public void close() {}
4090 })) {
4091 mNetworkRequestInfoLogs.dump(logPw);
4092 }
4093 }
4094
Hugo Benichia480ba52018-09-03 08:19:02 +09004095 /**
4096 * Return an array of all current NetworkAgentInfos sorted by network id.
4097 */
4098 private NetworkAgentInfo[] networksSortedById() {
4099 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004100 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004101 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004102 return networks;
4103 }
4104
4105 /**
4106 * Return an array of all current NetworkRequest sorted by request id.
4107 */
James Mattis258ea3c2020-11-15 15:04:40 -08004108 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004109 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004110 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004111 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004112 // Sort the array based off the NRI containing the min requestId in its requests.
4113 Arrays.sort(requests,
4114 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4115 Comparator.comparingInt(req -> req.requestId)).requestId
4116 )
4117 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004118 return requests;
4119 }
4120
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004121 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004122 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004123 if (officialNai != null && officialNai.equals(nai)) return true;
4124 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004125 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004126 " - " + nai);
4127 }
4128 return false;
4129 }
4130
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004131 private boolean isDisconnectRequest(Message msg) {
4132 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4133 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4134 return info.getState() == NetworkInfo.State.DISCONNECTED;
4135 }
4136
Robert Greenwalt2034b912009-08-12 16:08:25 -07004137 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004138 private class NetworkStateTrackerHandler extends Handler {
4139 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004140 super(looper);
4141 }
4142
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004143 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004144 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4145 final NetworkAgentInfo nai = arg.first;
4146 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004147 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004148 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004149 }
4150 return;
4151 }
4152
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004153 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004154 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004155 return;
4156 }
4157
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004158 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004159 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004160 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4161 if (!nai.respectsNcStructuralConstraints(proposed)) {
4162 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4163 + nai.networkCapabilities + " -> " + proposed);
4164 disconnectAndDestroyNetwork(nai);
4165 return;
4166 }
4167 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004168 final NetworkCapabilities sanitized =
4169 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004170 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004171 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004172 break;
4173 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004174 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004175 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004176 processLinkPropertiesFromAgent(nai, newLp);
4177 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004178 break;
4179 }
4180 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004181 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004182 updateNetworkInfo(nai, info);
4183 break;
4184 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004185 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4186 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004187 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004188 break;
4189 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004190 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004191 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004192 break;
4193 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004194 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004195 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004196 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004197 // Note that if the NAI had been connected, this would affect the
4198 // score, and therefore would require re-mixing the score and performing
4199 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004200 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004201 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4202 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004203 // Mark the network as temporarily accepting partial connectivity so that it
4204 // will be validated (and possibly become default) even if it only provides
4205 // partial internet access. Note that if user connects to partial connectivity
4206 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4207 // out of wifi coverage) and if the same wifi is available again, the device
4208 // will auto connect to this wifi even though the wifi has "no internet".
4209 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004210 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004211 break;
4212 }
junyulai011b1f12019-01-03 18:50:15 +08004213 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004214 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004215 break;
4216 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004217 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004218 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004219 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004220
4221 if (isLegacyLockdownNai(nai)
4222 && (underlying == null || underlying.size() != 1)) {
4223 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4224 + " must have exactly one underlying network: " + underlying);
4225 }
4226
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004227 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4228 nai.declaredUnderlyingNetworks = (underlying != null)
4229 ? underlying.toArray(new Network[0]) : null;
4230
4231 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4232 if (DBG) {
4233 log(nai.toShortString() + " changed underlying networks to "
4234 + Arrays.toString(nai.declaredUnderlyingNetworks));
4235 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004236 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004237 notifyIfacesChangedForNetworkStats();
4238 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004239 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004240 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004241 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4242 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4243 nai.teardownDelayMs = msg.arg1;
4244 } else {
4245 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4246 }
Chalard Jean550b5212021-03-05 23:07:53 +09004247 break;
4248 }
4249 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4250 nai.setLingerDuration((int) arg.second);
4251 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004252 }
Tyler Wear72388212021-09-09 14:49:02 -07004253 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4254 DscpPolicy policy = (DscpPolicy) arg.second;
4255 if (mDscpPolicyTracker != null) {
4256 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4257 }
4258 break;
4259 }
4260 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4261 if (mDscpPolicyTracker != null) {
4262 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4263 }
4264 break;
4265 }
4266 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4267 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004268 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004269 }
4270 break;
4271 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004272 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004273 if (!nai.everConnected()) {
4274 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4275 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004276 teardownUnneededNetwork(nai);
4277 break;
4278 }
4279
4280 if (nai.isDestroyed()) {
4281 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4282 + ", ignoring");
4283 break;
4284 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004285
4286 final int timeoutMs = (int) arg.second;
4287 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4288 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4289 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4290 }
4291
4292 // Marking a network awaiting replacement is used to ensure that any requests
4293 // satisfied by the network do not switch to another network until a
4294 // replacement is available or the wait for a replacement times out.
4295 // If the network is inactive (i.e., nascent or lingering), then there are no
4296 // such requests, and there is no point keeping it. Just tear it down.
4297 // Note that setLingerDuration(0) cannot be used to do this because the network
4298 // could be nascent.
4299 nai.clearInactivityState();
4300 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4301 Log.d(TAG, nai.toShortString()
4302 + " marked awaiting replacement is unneeded, tearing down instead");
4303 teardownUnneededNetwork(nai);
4304 break;
4305 }
4306
4307 Log.d(TAG, "Marking " + nai.toShortString()
4308 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4309 destroyNativeNetwork(nai);
4310
4311 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4312 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4313 // consider the fact that the network could already have disconnected or been
4314 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4315 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4316 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4317 mKeepaliveTracker.handleStopAllKeepalives(nai,
4318 SocketKeepalive.ERROR_INVALID_NETWORK);
4319
4320 nai.updateScoreForNetworkAgentUpdate();
4321 // This rematch is almost certainly not going to result in any changes, because
4322 // the destroyed flag is only just above the "current satisfier wins"
4323 // tie-breaker. But technically anything that affects scoring should rematch.
4324 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004325 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004326 break;
4327 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004328 }
4329 }
4330
4331 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004332 final int netId = msg.arg2;
4333 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004334 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004335 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004336 switch (msg.what) {
4337 default:
4338 return false;
lucasline117e2e2019-10-22 18:27:33 +08004339 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004340 if (nai == null) {
4341 break;
4342 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004343 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4344 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004345 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004346 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004347 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004348 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004349 if (probePrivateDnsCompleted) {
4350 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4351 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004352 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004353 }
4354 // Only show the notification when the private DNS is broken and the
4355 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004356 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004357 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4358 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004359 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004360 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4361 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4362 // private DNS is broken, it means this network is being reevaluated.
4363 // Either probing private DNS is not necessary any more or it hasn't been
4364 // done yet. In either case, the networkCapabilities should be updated to
4365 // reflect the new status.
4366 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004367 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004368 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004369 }
4370 break;
4371 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004372 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004373 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4374
Erik Kline31b4a9e2018-01-11 21:07:29 +09004375 if (nai == null) break;
4376
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004377 handleNetworkTested(nai, results.mTestResult,
4378 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004379 break;
4380 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004381 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004382 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004383 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004384 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004385 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004386 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004387 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4388 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004389 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004390 if (nai == null) {
4391 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4392 break;
4393 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004394 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004395 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004396 (PendingIntent) msg.obj,
4397 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004398 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004399 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004400 break;
4401 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004402 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004403 if (nai == null) break;
4404
Erik Kline9a62f012018-03-21 07:18:33 -07004405 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004406 break;
4407 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004408 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004409 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004410 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004411 break;
4412 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004413 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004414 return true;
4415 }
4416
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004417 private void handleNetworkTested(
4418 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004419 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4420 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004421 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004422
4423 // If there is any kind of working networking, then the NAI has been evaluated
4424 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4425 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004426 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004427 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004428 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4429 // any callback that receives onAvailable for that rematch receives an extra caps
4430 // callback. To prevent that, update the score in the agent so the updates below won't
4431 // see an update to both caps and score at the same time.
4432 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004433 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4434
he_won.hwang881307a2022-03-15 21:23:52 +09004435 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4436 // Assume the validation failure is due to a temporary failure after roaming
4437 // and ignore it. NetworkMonitor will continue to retry validation. If it
4438 // continues to fail after the block timeout expires, the network will be
4439 // marked unvalidated. If it succeeds, then validation state will not change.
4440 return;
4441 }
4442
Chalard Jean254bd162022-08-25 13:04:51 +09004443 final boolean wasValidated = nai.isValidated();
4444 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004445 final boolean wasPortal = nai.captivePortalDetected();
4446 nai.setPartialConnectivity(partial);
4447 nai.setCaptivePortalDetected(portal);
4448 nai.updateScoreForNetworkAgentUpdate();
4449 final boolean partialConnectivityChanged = (wasPartial != partial);
4450 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004451
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004452 if (DBG) {
4453 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4454 ? " with redirect to " + redirectUrl
4455 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004456 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004457 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004458 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004459 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004460 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004461 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004462 if (valid) {
4463 handleFreshlyValidatedNetwork(nai);
4464 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4465 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004466 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004467 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004468 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004469 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004470 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004471 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004472 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004473 NotificationType.PRIVATE_DNS_BROKEN);
4474 // If network becomes valid, the hasShownBroken should be reset for
4475 // that network so that the notification will be fired when the private
4476 // DNS is broken again.
4477 nai.networkAgentConfig.hasShownBroken = false;
4478 }
4479 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004480 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004481 } else if (portalChanged) {
4482 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004483 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004484 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4485 nai.onPreventAutomaticReconnect();
4486 teardownUnneededNetwork(nai);
4487 return;
4488 } else {
4489 updateCapabilitiesForNetwork(nai);
4490 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004491 } else if (becameEvaluated) {
4492 // If valid or partial connectivity changed, updateCapabilities* has
4493 // done the rematch.
4494 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004495 }
4496 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004497
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004498 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004499 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004500 nai.onValidationStatusChanged(
4501 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4502 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004503
4504 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004505 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004506 // immediately. Re-notify partial connectivity silently if no internet
4507 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004508 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004509 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004510 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4511 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004512 }
4513
Chalard Jean254bd162022-08-25 13:04:51 +09004514 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004515 handleNetworkUnvalidated(nai);
4516 }
4517 }
4518
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004519 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4520 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4521 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4522 // Do not avoid captive portal when network is wear proxy.
4523 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4524 }
4525
Calvin Ondada1452016-10-11 15:10:46 -07004526 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004527 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4528 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004529 }
4530
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004531 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4532 switch (msg.what) {
4533 default:
4534 return false;
4535 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4536 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4537 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4538 handleLingerComplete(nai);
4539 }
4540 break;
4541 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004542 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4543 handleNetworkAgentRegistered(msg);
4544 break;
4545 }
4546 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4547 handleNetworkAgentDisconnected(msg);
4548 break;
4549 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004550 }
4551 return true;
4552 }
4553
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004554 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004555 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004556 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004557 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004558 maybeHandleNetworkAgentMessage(msg);
4559 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004560 }
4561 }
4562
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004563 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004564 private final int mNetId;
4565 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004566
4567 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004568 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004569 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004570 }
4571
4572 @Override
4573 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4574 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004575 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004576 }
4577
4578 @Override
4579 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004580 // Legacy version of notifyNetworkTestedWithExtras.
4581 // Would only be called if the system has a NetworkStack module older than the
4582 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004583 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004584 }
4585
4586 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004587 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004588 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4589 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004590 final Message msg = mTrackerHandler.obtainMessage(
4591 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004592 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004593 new NetworkTestedResults(
4594 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004595 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004596
4597 // Invoke ConnectivityReport generation for this Network test event.
4598 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4599 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004600
Cody Kestingf1120be2020-08-03 18:01:40 -07004601 // NetworkMonitor reports the network validation result as a bitmask while
4602 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4603 // logical value for ConnectivityDiagnostics.
4604 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4605 p.result);
4606
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004607 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004608 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004609 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4610 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4611
Aaron Huang959d3642021-01-21 15:47:41 +08004612 ConnectivityReportEvent reportEvent =
4613 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4614 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004615 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004616 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004617 }
4618
4619 @Override
4620 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4621 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4622 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004623 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004624 }
4625
4626 @Override
lucasline117e2e2019-10-22 18:27:33 +08004627 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4628 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4629 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004630 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004631 }
4632
4633 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004634 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4635 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4636 EVENT_CAPPORT_DATA_CHANGED,
4637 0, mNetId, data));
4638 }
4639
4640 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004641 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004642 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004643 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004644
4645 final PendingIntent pendingIntent;
4646 // Only the system server can register notifications with package "android"
4647 final long token = Binder.clearCallingIdentity();
4648 try {
paulhu7746e4e2020-06-09 19:07:03 +08004649 pendingIntent = PendingIntent.getBroadcast(
4650 mContext,
4651 0 /* requestCode */,
4652 intent,
4653 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004654 } finally {
4655 Binder.restoreCallingIdentity(token);
4656 }
4657 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4658 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004659 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004660 }
4661
4662 @Override
4663 public void hideProvisioningNotification() {
4664 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004665 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004666 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004667
4668 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004669 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004670 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004671 }
4672
4673 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004674 public int getInterfaceVersion() {
4675 return this.VERSION;
4676 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004677
4678 @Override
4679 public String getInterfaceHash() {
4680 return this.HASH;
4681 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004682 }
4683
Cody Kestingf1120be2020-08-03 18:01:40 -07004684 /**
4685 * Converts the given NetworkMonitor-specific validation result bitmask to a
4686 * ConnectivityDiagnostics-specific validation result int.
4687 */
4688 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4689 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4690 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4691 }
4692 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4693 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4694 }
4695 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4696 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4697 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4698 }
4699
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004700 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004701 log("Data stall detected with methods: " + p.detectionMethod);
4702
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004703 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004704 int detectionMethod = 0;
4705 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4706 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4707 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4708 }
4709 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4710 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4711 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4712 p.tcpMetricsCollectionPeriodMillis);
4713 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004714 }
4715
Cody Kestingf53a0752020-04-15 12:33:28 -07004716 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004717 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004718 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004719
4720 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4721 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4722 // the cost of going through two handlers.
4723 mConnectivityDiagnosticsHandler.sendMessage(msg);
4724 }
4725
Cody Kestingb37958e2020-05-15 10:36:01 -07004726 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4727 return (p.detectionMethod & detectionMethod) != 0;
4728 }
4729
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004730 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4731 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004732 }
4733
Erik Klinea73af002018-06-26 18:53:43 +09004734 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4735 if (nai == null) return;
4736 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4737 // in order to restart a validation pass from within netd.
4738 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4739 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004740 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004741 }
4742 }
4743
Erik Kline31b4a9e2018-01-11 21:07:29 +09004744 private void handlePrivateDnsSettingsChanged() {
4745 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4746
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004747 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004748 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004749 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004750 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4751 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004752 }
4753 }
4754
Erik Kline9a62f012018-03-21 07:18:33 -07004755 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4756 // Private DNS only ever applies to networks that might provide
4757 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004758 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004759
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004760 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004761 // schedule DNS resolutions. If a DNS resolution is required the
4762 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004763 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004764
4765 // With Private DNS bypass support, we can proceed to update the
4766 // Private DNS config immediately, even if we're in strict mode
4767 // and have not yet resolved the provider name into a set of IPs.
4768 updatePrivateDns(nai, cfg);
4769 }
4770
4771 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4772 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004773 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004774 }
4775
dalyk1720e542018-03-05 12:42:22 -05004776 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4777 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4778 if (nai == null) {
4779 return;
4780 }
4781 mDnsManager.updatePrivateDnsValidation(update);
4782 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4783 }
4784
paulhu7c0a2e62021-01-08 00:51:49 +08004785 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004786 int prefixLength) {
4787 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4788 if (nai == null) return;
4789
paulhu7c0a2e62021-01-08 00:51:49 +08004790 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4791 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004792
4793 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004794 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004795 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004796 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004797 prefixLength);
4798 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004799 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004800 return;
4801 }
4802 }
4803
Lorenzo Colittid523d142020-04-01 20:16:30 +09004804 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004805 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4806 }
4807
Hai Shalome58bdc62021-01-11 18:45:34 -08004808 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004809 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004810 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004811 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4812 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4813 }
4814
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004815 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004816 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004817 * @param nai the agent info to update
4818 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004819 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004820 */
junyulai2b6f0c22021-02-03 20:15:30 +08004821 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4822 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4823 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004824 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004825 // one lingered request, set inactive.
4826 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004827 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004828 if (DBG) log("Unsetting inactive " + nai.toShortString());
4829 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004830 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004831 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004832 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004833 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4834 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004835 }
junyulai2b6f0c22021-02-03 20:15:30 +08004836 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004837 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004838 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004839 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004840 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004841 }
4842
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004843 private void handleNetworkAgentRegistered(Message msg) {
4844 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4845 if (!mNetworkAgentInfos.contains(nai)) {
4846 return;
4847 }
4848
4849 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4850 if (VDBG) log("NetworkAgent registered");
4851 } else {
4852 loge("Error connecting NetworkAgent");
4853 mNetworkAgentInfos.remove(nai);
4854 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004855 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004856 synchronized (mNetworkForNetId) {
4857 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004858 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004859 mNetIdManager.releaseNetId(nai.network.getNetId());
4860 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004861 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004862 }
4863 }
4864 }
Paul Jensend5f53392014-11-25 15:26:53 -05004865
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004866 @VisibleForTesting
4867 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004868 // The feature of creating the networks immediately was slated for U, but race conditions
4869 // detected late required this was flagged off.
4870 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4871 // in NetworkAgentTest.
4872 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004873 }
4874
4875 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4876 @NonNull NetworkInfo.State state) {
4877 if (nai.isCreated()) return false;
4878 if (state == NetworkInfo.State.CONNECTED) return true;
4879 if (state != NetworkInfo.State.CONNECTING) {
4880 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004881 if (shouldCreateNetworksImmediately()) {
4882 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4883 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004884 return false;
4885 }
4886 return nai.isVPN() || shouldCreateNetworksImmediately();
4887 }
4888
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004889 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004890 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004891 }
4892
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004893 @VisibleForTesting
4894 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004895 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004896 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004897
4898 // If the network never roamed, return false. The check below is not sufficient if time
4899 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4900 if (nai.lastRoamTime == 0) return false;
4901
he_won.hwang881307a2022-03-15 21:23:52 +09004902 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4903 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004904 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004905 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004906 final long currentTimeMs = SystemClock.elapsedRealtime();
4907 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004908 if (timeSinceLastRoam <= blockTimeOut) {
4909 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4910 return true;
4911 }
4912 }
4913 return false;
4914 }
4915
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004916 private void handleNetworkAgentDisconnected(Message msg) {
4917 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004918 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004919 }
4920
Chalard Jeand9fffc32018-05-11 20:19:20 +09004921 // Destroys a network, remove references to it from the internal state managed by
4922 // ConnectivityService, free its interfaces and clean up.
4923 // Must be called on the Handler thread.
4924 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004925 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004926
4927 if (!mNetworkAgentInfos.contains(nai)) return;
4928
Chalard Jeand9fffc32018-05-11 20:19:20 +09004929 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004930 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004931 }
lucaslinb25c9a62019-02-12 15:30:13 +08004932 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004933 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004934 // A network agent has disconnected.
4935 // TODO - if we move the logic to the network agent (have them disconnect
4936 // because they lost all their requests or because their score isn't good)
4937 // then they would disconnect organically, report their new state and then
4938 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004939 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004940 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4941 null, null);
4942 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004943 final boolean wasDefault = isDefaultNetwork(nai);
4944 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004945 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004946 }
4947 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09004948 // If this was a local network forwarded to some upstream, or if some local network was
4949 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09004950 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09004951 // If this is a local network with an upstream selector, remove the associated network
4952 // request.
4953 if (nai.isLocalNetwork()) {
4954 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
4955 if (null != selector) {
4956 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
4957 }
4958 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004959 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4960 // by other networks that are already connected. Perhaps that can be done by
4961 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4962 // of rematchAllNetworksAndRequests
4963 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004964 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004965
4966 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004967 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4968 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004969 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004970 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004971 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004972 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004973 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004974 synchronized (mNetworkForNetId) {
4975 // Remove the NetworkAgent, but don't mark the netId as
4976 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004977 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004978 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004979 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004980 // Update allowed network lists in netd. This should be called after removing nai
4981 // from mNetworkAgentInfos.
4982 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004983 // Remove all previously satisfied requests.
4984 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004985 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004986 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004987 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004988 if (currentNetwork != null
4989 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004990 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004991 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4992 // rematch not to keep disconnected agents instead of setting it here ; this
4993 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004994 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004995 for (final NetworkOfferInfo noi : mNetworkOffers) {
4996 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004997 }
James Mattise3ef1912020-12-20 11:09:58 -08004998
Chalard Jean5b409c72021-02-04 13:12:59 +09004999 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08005000 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09005001 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08005002 // network, because while incorrect this is the closest to the old (also
5003 // incorrect) behavior.
5004 mNetworkActivityTracker.updateDataActivityTracking(
5005 null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005006 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005007 ensureNetworkTransitionWakelock(nai.toShortString());
5008 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005009 }
5010 }
junyulai2b6f0c22021-02-03 20:15:30 +08005011 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005012 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005013 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005014 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005015 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005016 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005017 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005018
Aaron Huang9fe47be2021-06-08 13:11:45 +08005019 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5020 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5021 // not called by the rematch in this case. This is because the code above unset
5022 // this network from the default request's satisfier, and that is what the rematch
5023 // is using as its source data to know what the old satisfier was. So as far as the
5024 // rematch above is concerned, the old default network was null.
5025 // Therefore if there is no new default, the default network was null and is still
5026 // null, thus there was no change so makeDefault() is not called. So if the old
5027 // network had a proxy and there is no new default, the proxy tracker should be told
5028 // that there is no longer a default proxy.
5029 // Strictly speaking this is not essential because having a proxy setting when
5030 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5031 mProxyTracker.setDefaultProxy(null);
5032 }
5033
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005034 // Immediate teardown.
5035 if (nai.teardownDelayMs == 0) {
5036 destroyNetwork(nai);
5037 return;
5038 }
5039
5040 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005041 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305042 try {
5043 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5044 } catch (RemoteException e) {
5045 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5046 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005047 }
5048 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5049 }
5050
5051 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005052 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005053 // Tell netd to clean up the configuration for this network
5054 // (routing rules, DNS, etc).
5055 // This may be slow as it requires a lot of netd shelling out to ip and
5056 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005057 // after we've rematched networks with requests (which might change the default
5058 // network or service a new request from an app), so network traffic isn't interrupted
5059 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005060 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005061 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005062 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005063 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5064 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5065 // false if the network was never created.
5066 // TODO: delete when S is no longer supported.
5067 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005068 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005069 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005070 }
5071
Chalard Jean1e4c2182023-10-06 18:45:53 +09005072 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005073 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005074 // Step 1 : maybe this network was the upstream for one or more local networks.
5075 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5076 if (!local.isLocalNetwork()) continue;
5077 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5078 if (null == selector) continue;
5079 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5080 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5081 // called after removing all associated NRIs from mNetworkRequests.
5082 if (null == nri) continue;
5083 final NetworkAgentInfo satisfier = nri.getSatisfier();
5084 if (disconnecting != satisfier) continue;
5085 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005086 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5087 // correctly contains null as an upstream.
5088 if (sendCallbacks) {
5089 nri.setSatisfier(null, null);
5090 notifyNetworkCallbacks(local,
5091 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5092 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005093 }
5094
5095 // Step 2 : maybe this is a local network that had an upstream.
5096 if (!disconnecting.isLocalNetwork()) return;
5097 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5098 if (null == selector) return;
5099 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5100 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5101 // is called after removing all associated NRIs from mNetworkRequests.
5102 if (null == nri) return;
5103 final NetworkAgentInfo satisfier = nri.getSatisfier();
5104 if (null == satisfier) return;
5105 removeLocalNetworkUpstream(disconnecting, satisfier);
5106 }
5107
5108 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5109 @NonNull final NetworkAgentInfo upstream) {
5110 try {
5111 mRoutingCoordinatorService.removeInterfaceForward(
5112 localAgent.linkProperties.getInterfaceName(),
5113 upstream.linkProperties.getInterfaceName());
5114 } catch (RemoteException e) {
5115 loge("Couldn't remove interface forward for "
5116 + localAgent.linkProperties.getInterfaceName() + " to "
5117 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5118 }
5119 }
5120
Ken Chen6df7a902021-04-09 15:08:42 +08005121 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005122 try {
5123 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005124 final NativeNetworkConfig config;
5125 if (nai.isVPN()) {
5126 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005127 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005128 return false;
5129 }
5130 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5131 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005132 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005133 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005134 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005135 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005136 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5137 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005138 getNetworkPermission(nai.networkCapabilities),
5139 false /* secure */,
5140 VpnManager.TYPE_VPN_NONE,
5141 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005142 }
Ken Chen6df7a902021-04-09 15:08:42 +08005143 mNetd.networkCreate(config);
5144 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005145 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5146 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005147 return true;
5148 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005149 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005150 return false;
5151 }
5152 }
5153
Ken Chen6df7a902021-04-09 15:08:42 +08005154 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005155 if (mDscpPolicyTracker != null) {
5156 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5157 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005158 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005159 // the interface is going to go away. Don't send the callbacks however ; if the network
5160 // was is being disconnected the callbacks have already been sent, and if it is being
5161 // destroyed pending replacement they will be sent when it is disconnected.
5162 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005163 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005164 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005165 } catch (RemoteException | ServiceSpecificException e) {
5166 loge("Exception destroying network(networkDestroy): " + e);
5167 }
5168 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005169 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005170 } catch (RemoteException | ServiceSpecificException e) {
5171 loge("Exception destroying network: " + e);
5172 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005173 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5174 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5175 // gets created, could add data to DnsManager data structures that will never get deleted.
5176 mDnsManager.removeNetwork(nai.network);
5177
5178 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005179 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005180 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5181 }
5182
Chalard Jean254bd162022-08-25 13:04:51 +09005183 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005184 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005185 }
5186
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005187 // If this method proves to be too slow then we can maintain a separate
5188 // pendingIntent => NetworkRequestInfo map.
5189 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5190 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005191 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5192 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5193 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005194 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005195 return entry.getValue();
5196 }
5197 }
5198 return null;
5199 }
5200
Chalard Jean524f0b12021-10-25 21:11:56 +09005201 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005202 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005203 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5204 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5205 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5206 // bug is fixed.
5207 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005208 throw new IllegalStateException("This NRI is already registered. New : " + nri
5209 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005210 }
5211 }
5212 }
5213 }
5214
Chalard Jeanac9ace02022-01-26 16:54:05 +09005215 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5216 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005217 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005218 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5219 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005220 }
5221 return false;
5222 }
5223
James Mattisf7027322020-12-13 16:28:14 -08005224 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005225 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005226 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5227 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5228 final NetworkRequestInfo existingRequest =
5229 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005230 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005231 if (DBG) {
5232 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5233 + nri.mRequests.get(0) + " because their intents matched.");
5234 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005235 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005236 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005237 }
Erik Kline05f2b402015-04-30 12:58:40 +09005238 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005239 }
5240
James Mattisf7027322020-12-13 16:28:14 -08005241 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005242 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005243 }
5244
James Mattis3ce3d3c2021-02-09 18:18:28 -08005245 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005246 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005247 for (final NetworkRequestInfo nri : nris) {
5248 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005249 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005250 for (final NetworkRequest req : nri.mRequests) {
5251 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005252 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005253 if (req.isListen()) {
5254 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5255 if (req.networkCapabilities.hasSignalStrength()
5256 && network.satisfiesImmutableCapabilitiesOf(req)) {
5257 updateSignalStrengthThresholds(network, "REGISTER", req);
5258 }
James Mattisf7027322020-12-13 16:28:14 -08005259 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005260 }
5261 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005262
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005263 // If this NRI has a satisfier already, it is replacing an older request that
5264 // has been removed. Track it.
5265 final NetworkRequest activeRequest = nri.getActiveRequest();
5266 if (null != activeRequest) {
5267 // If there is an active request, then for sure there is a satisfier.
5268 nri.getSatisfier().addRequest(activeRequest);
5269 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005270 }
James Mattisf7027322020-12-13 16:28:14 -08005271
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005272 if (mFlags.noRematchAllRequestsOnRegister()) {
5273 rematchNetworksAndRequests(nris);
5274 } else {
5275 rematchAllNetworksAndRequests();
5276 }
James Mattis45d81842021-01-10 14:24:24 -08005277
Chalard Jean0354d8c2021-01-12 10:58:56 +09005278 // Requests that have not been matched to a network will not have been sent to the
5279 // providers, because the old satisfier and the new satisfier are the same (null in this
5280 // case). Send these requests to the providers.
5281 for (final NetworkRequestInfo nri : nris) {
5282 for (final NetworkOfferInfo noi : mNetworkOffers) {
5283 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005284 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005285 }
5286 }
5287
James Mattisf7027322020-12-13 16:28:14 -08005288 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5289 final int callingUid) {
5290 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005291 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005292 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5293 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5294 handleReleaseNetworkRequest(
5295 nri.mRequests.get(0),
5296 callingUid,
5297 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005298 }
5299 }
5300
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005301 // Determines whether the network is the best (or could become the best, if it validated), for
5302 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5303 // on the value of reason:
5304 //
5305 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5306 // then it should be torn down.
5307 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5308 // then it should be lingered.
5309 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005310 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005311
Chalard Jean254bd162022-08-25 13:04:51 +09005312 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005313 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5314 return false;
5315 }
5316
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005317 final int numRequests;
5318 switch (reason) {
5319 case TEARDOWN:
5320 numRequests = nai.numRequestNetworkRequests();
5321 break;
5322 case LINGER:
5323 numRequests = nai.numForegroundNetworkRequests();
5324 break;
5325 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005326 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005327 return true;
5328 }
5329
Chalard Jean947acd42021-03-08 22:29:27 +09005330 if (numRequests > 0) return false;
5331
Paul Jensende49eb12015-06-25 15:30:08 -04005332 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005333 if (reason == UnneededFor.LINGER
5334 && !nri.isMultilayerRequest()
5335 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005336 // Background requests don't affect lingering.
5337 continue;
5338 }
5339
James Mattis3d229892020-11-16 16:46:28 -08005340 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005341 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005342 }
5343 }
Paul Jensende49eb12015-06-25 15:30:08 -04005344 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005345 }
5346
James Mattis3d229892020-11-16 16:46:28 -08005347 private boolean isNetworkPotentialSatisfier(
5348 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005349 // While destroyed network sometimes satisfy requests (including occasionally newly
5350 // satisfying requests), *potential* satisfiers are networks that might beat a current
5351 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5352 // because it's never a good idea to keep a destroyed network in case it validates.
5353 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5354 // candidate after it's been replaced by another unvalidated network.
5355 if (candidate.isDestroyed()) return false;
5356 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005357 // request, return immediately. For multilayer requests, check to see if any of the
5358 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005359 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5360 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005361 return false;
5362 }
5363 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005364 // This multilayer listen request is satisfied therefore no further requests need to be
5365 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005366 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005367 return false;
5368 }
James Mattis3d229892020-11-16 16:46:28 -08005369 // As non-multilayer listen requests have already returned, the below would only happen
5370 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005371 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005372 continue;
5373 }
Chalard Jean80685f42023-10-30 18:31:27 +09005374 // If there is hope for this network might validate and subsequently become the best
5375 // network for that request, then it is needed. Note that this network can't already
5376 // be the best for this request, or it would be the current satisfier, and therefore
5377 // there would be no need to call this method to find out if it is a *potential*
5378 // satisfier ("unneeded", the only caller, only calls this if this network currently
5379 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005380 if (candidate.satisfies(req)) {
5381 // As soon as a network is found that satisfies a request, return. Specifically for
5382 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5383 // is important so as to not evaluate lower priority requests further in
5384 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005385 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5386 ? nri.getSatisfier() : null;
5387 // Note that this catches two important cases:
5388 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5389 // is currently satisfying the request. This is desirable when
5390 // cellular ends up validating but WiFi does not.
5391 // 2. Unvalidated WiFi will not be reaped when validated cellular
5392 // is currently satisfying the request. This is desirable when
5393 // WiFi ends up validating and out scoring cellular.
5394 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005395 }
5396 }
5397
5398 return false;
5399 }
5400
Erik Kline0c04b742016-07-07 16:50:58 +09005401 private NetworkRequestInfo getNriForAppRequest(
5402 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005403 // Looking up the app passed param request in mRequests isn't possible since it may return
5404 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5405 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005406 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5407 // to avoid potential race conditions when validating a package->uid mapping when sending
5408 // the callback on the very low-chance that an application shuts down prior to the callback
5409 // being sent.
5410 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5411 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005412
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005413 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005414 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005415 log(String.format("UID %d attempted to %s for unowned request %s",
5416 callingUid, requestedOperation, nri));
5417 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005418 }
Erik Kline0c04b742016-07-07 16:50:58 +09005419 }
5420
5421 return nri;
5422 }
5423
James Mattisf7027322020-12-13 16:28:14 -08005424 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5425 final String callingMethod) {
5426 if (nri.isMultilayerRequest()) {
5427 throw new IllegalStateException(
5428 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005429 }
5430 }
5431
James Mattisf7027322020-12-13 16:28:14 -08005432 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005433 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005434 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5435 // single NetworkRequest and thus does not apply to multilayer requests.
5436 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5437 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005438 return;
5439 }
James Mattis2516da32021-01-31 17:06:19 -08005440 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005441 return;
5442 }
James Mattisf7027322020-12-13 16:28:14 -08005443 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5444 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005445 }
5446 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005447 callCallbackForRequest(
5448 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005449 }
5450
James Mattisf7027322020-12-13 16:28:14 -08005451 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5452 final int callingUid,
5453 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005454 final NetworkRequestInfo nri =
5455 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5456 if (nri == null) {
5457 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005458 }
James Mattisf7027322020-12-13 16:28:14 -08005459 if (VDBG || (DBG && request.isRequest())) {
5460 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005461 }
5462 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005463 if (callOnUnavailable) {
5464 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5465 }
Erik Kline155a59a2015-11-25 12:49:38 +09005466 }
Erik Kline0c04b742016-07-07 16:50:58 +09005467
James Mattisa076c532020-12-02 14:12:41 -08005468 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005469 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005470 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005471 if (null == mNetworkRequests.remove(req)) {
5472 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5473 continue;
5474 }
James Mattisa076c532020-12-02 14:12:41 -08005475 if (req.isListen()) {
5476 removeListenRequestFromNetworks(req);
5477 }
5478 }
James Mattis8f036802021-06-20 16:26:01 -07005479 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005480 if (mDefaultNetworkRequests.remove(nri)) {
5481 // If this request was one of the defaults, then the UID rules need to be updated
5482 // WARNING : if the app(s) for which this network request is the default are doing
5483 // traffic, this will kill their connected sockets, even if an equivalent request
5484 // is going to be reinstated right away ; unconnected traffic will go on the default
5485 // until the new default is set, which will happen very soon.
5486 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5487 // remove ranges for those requests that won't have a replacement
5488 final NetworkAgentInfo satisfier = nri.getSatisfier();
5489 if (null != satisfier) {
5490 try {
paulhu0e79d952021-06-09 16:11:35 +08005491 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5492 satisfier.network.getNetId(),
5493 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005494 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005495 } catch (RemoteException e) {
5496 loge("Exception setting network preference default network", e);
5497 }
5498 }
5499 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005500
Junyu Lai00d92df2022-07-05 11:01:52 +08005501 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005502 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005503 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005504
5505 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005506 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005507 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005508 }
5509 }
5510
Chalard Jean0354d8c2021-01-12 10:58:56 +09005511 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5512 // needed for this offer.
5513 for (final NetworkOfferInfo noi : mNetworkOffers) {
5514 for (final NetworkRequest req : nri.mRequests) {
5515 if (req.isRequest() && noi.offer.neededFor(req)) {
5516 noi.offer.onNetworkUnneeded(req);
5517 }
5518 }
5519 }
James Mattisa076c532020-12-02 14:12:41 -08005520 }
5521
James Mattis3ce3d3c2021-02-09 18:18:28 -08005522 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5523 for (final NetworkRequestInfo nri : nris) {
5524 if (mDefaultRequest == nri) {
5525 // Make sure we never remove the default request.
5526 continue;
5527 }
5528 handleRemoveNetworkRequest(nri);
5529 }
5530 }
5531
James Mattisa076c532020-12-02 14:12:41 -08005532 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5533 // listens don't have a singular affected Network. Check all networks to see
5534 // if this listen request applies and remove it.
5535 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5536 nai.removeRequest(req.requestId);
5537 if (req.networkCapabilities.hasSignalStrength()
5538 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5539 updateSignalStrengthThresholds(nai, "RELEASE", req);
5540 }
5541 }
5542 }
5543
5544 /**
5545 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5546 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5547 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5548 */
5549 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5550 boolean wasKept = false;
5551 final NetworkAgentInfo nai = nri.getSatisfier();
5552 if (nai != null) {
5553 final int requestLegacyType = nri.getActiveRequest().legacyType;
5554 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5555 nai.removeRequest(nri.getActiveRequest().requestId);
5556 if (VDBG || DDBG) {
5557 log(" Removing from current network " + nai.toShortString()
5558 + ", leaving " + nai.numNetworkRequests() + " requests.");
5559 }
5560 // If there are still lingered requests on this network, don't tear it down,
5561 // but resume lingering instead.
5562 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005563 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005564 notifyNetworkLosing(nai, now);
5565 }
5566 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5567 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5568 teardownUnneededNetwork(nai);
5569 } else {
5570 wasKept = true;
5571 }
James Mattisa076c532020-12-02 14:12:41 -08005572 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5573 // Went from foreground to background.
5574 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005575 }
5576
Erik Kline0c04b742016-07-07 16:50:58 +09005577 // Maintain the illusion. When this request arrived, we might have pretended
5578 // that a network connected to serve it, even though the network was already
5579 // connected. Now that this request has gone away, we might have to pretend
5580 // that the network disconnected. LegacyTypeTracker will generate that
5581 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005582 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005583 boolean doRemove = true;
5584 if (wasKept) {
5585 // check if any of the remaining requests for this network are for the
5586 // same legacy type - if so, don't remove the nai
5587 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5588 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005589 if (otherRequest.legacyType == requestLegacyType
5590 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005591 if (DBG) log(" still have other legacy request - leaving");
5592 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005593 }
5594 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005595 }
5596
Erik Kline0c04b742016-07-07 16:50:58 +09005597 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005598 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005599 }
5600 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005601 }
5602 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005603
Junyu Lai00d92df2022-07-05 11:01:52 +08005604 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005605 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005606 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5607 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5608 }
5609
Lorenzo Colittid6459092016-07-04 12:55:44 +09005610 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005611 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005612 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005613 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005614 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005615 }
5616
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005617 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005618 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5619 enforceNetworkStackSettingsOrSetup();
5620 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5621 encodeBool(accept), encodeBool(always), network));
5622 }
5623
5624 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005625 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005626 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005627 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5628 }
5629
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005630 @Override
5631 public void setTestAllowBadWifiUntil(long timeMs) {
5632 enforceSettingsPermission();
5633 if (!Build.isDebuggable()) {
5634 throw new IllegalStateException("Does not support in non-debuggable build");
5635 }
5636
5637 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5638 throw new IllegalArgumentException("It should not exceed "
5639 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5640 }
5641
5642 mHandler.sendMessage(
5643 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5644 }
5645
chiachangwange0192a72023-02-06 13:25:01 +00005646 @Override
5647 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5648 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005649
5650 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5651 throw new IllegalArgumentException("Argument should not exceed "
5652 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5653 }
5654
5655 mHandler.sendMessage(
5656 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5657 }
5658
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005659 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5660 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5661 " accept=" + accept + " always=" + always);
5662
5663 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5664 if (nai == null) {
5665 // Nothing to do.
5666 return;
5667 }
5668
Chalard Jean254bd162022-08-25 13:04:51 +09005669 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005670 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005671 return;
5672 }
5673
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005674 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005675 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005676 }
5677
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005678 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5679 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005680 // If network becomes partial connectivity and user already accepted to use this
5681 // network, we should respect the user's option and don't need to popup the
5682 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005683 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005684 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005685 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005686 }
5687
5688 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005689 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005690 }
5691
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005692 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005693 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005694 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005695 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005696 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005697 }
5698
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005699 }
5700
lucaslin2240ef62019-03-12 13:08:03 +08005701 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5702 boolean always) {
5703 if (DBG) {
5704 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5705 + " always=" + always);
5706 }
5707
5708 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5709 if (nai == null) {
5710 // Nothing to do.
5711 return;
5712 }
5713
Chalard Jean254bd162022-08-25 13:04:51 +09005714 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005715 // The network validated while the dialog box was up. Take no action.
5716 return;
5717 }
5718
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005719 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5720 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005721 }
5722
5723 // TODO: Use the current design or save the user choice into IpMemoryStore.
5724 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005725 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005726 }
5727
5728 if (!accept) {
5729 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005730 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005731 // Tear down the network.
5732 teardownUnneededNetwork(nai);
5733 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005734 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5735 // result in a partial connectivity result which will be processed by
5736 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005737 //
5738 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5739 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005740 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005741 }
5742 }
5743
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005744 private void handleSetAvoidUnvalidated(Network network) {
5745 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005746 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005747 // Nothing to do. The network either disconnected or revalidated.
5748 return;
5749 }
Chalard Jean254bd162022-08-25 13:04:51 +09005750 if (0L == nai.getAvoidUnvalidated()) {
5751 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005752 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005753 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005754 }
5755 }
5756
Chalard Jean5fb43c72022-09-08 19:03:14 +09005757 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005758 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005759 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005760 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005761 }
5762
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005763 @Override
5764 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005765 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005766 mHandler.post(() -> {
5767 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5768 if (nai == null) return;
5769 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005770 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005771 });
5772 }
5773
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005774 /**
5775 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5776 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005777 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005778 * @param appExtras Bundle to use as intent extras for the captive portal application.
5779 * Must be treated as opaque to avoid preventing the captive portal app to
5780 * update its arguments.
5781 */
5782 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005783 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005784 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5785 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005786
5787 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5788 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005789 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5790 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005791 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5792
lucaslin75ff7022020-12-17 04:14:35 +08005793 final long token = Binder.clearCallingIdentity();
5794 try {
5795 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5796 } finally {
5797 Binder.restoreCallingIdentity(token);
5798 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005799 }
5800
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005801 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5802 private final Network mNetwork;
5803
5804 private CaptivePortalImpl(Network network) {
5805 mNetwork = network;
5806 }
5807
5808 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005809 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005810 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5811 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005812 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5813 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5814 // Since the network will be disconnected, skip notifying NetworkMonitor
5815 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005816 }
5817
Chiachang Wang938bfba2020-01-09 13:50:55 +08005818 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005819 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005820 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005821 }
5822
5823 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005824 public void appRequest(final int request) {
5825 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5826 if (nm == null) return;
5827
5828 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005829 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005830 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005831 }
5832 }
5833
5834 @Nullable
5835 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5836 // getNetworkAgentInfoForNetwork is thread-safe
5837 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5838 if (nai == null) return null;
5839
5840 // nai.networkMonitor() is thread-safe
5841 return nai.networkMonitor();
5842 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005843 }
5844
Hugo Benichic9048bc2016-09-14 23:23:08 +00005845 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005846 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005847 }
5848
Chalard Jean020b93a2022-09-01 13:20:14 +09005849 private boolean activelyPreferBadWifi() {
5850 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5851 }
5852
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005853 /**
5854 * Return whether the device should maintain continuous, working connectivity by switching away
5855 * from WiFi networks having no connectivity.
5856 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5857 */
5858 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005859 if (!checkNetworkStackPermission()) {
5860 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5861 }
5862 return avoidBadWifi();
5863 }
5864
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005865 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005866 ensureRunningOnConnectivityServiceThread();
5867 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005868 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005869 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005870 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005871 if (avoidBadWifi) {
5872 // If the device is now avoiding bad wifi, remove notifications that might have
5873 // been put up when the device didn't.
5874 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5875 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005876 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005877 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5878 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5879 for (final NetworkOfferInfo noi : offersToUpdate) {
5880 updateOfferScore(noi.offer);
5881 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005882 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005883 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005884 }
5885
Erik Kline95ecfee2016-10-02 18:02:14 +09005886 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005887 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005888 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005889 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005890 if (!configRestrict) {
5891 pw.println("Bad Wi-Fi avoidance: unrestricted");
5892 return;
5893 }
5894
5895 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5896 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005897 pw.println("Config restrict: " + configRestrict);
5898 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005899
Chalard Jeane0fdea32022-09-14 21:44:22 +09005900 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005901 String description;
5902 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005903 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005904 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005905 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005906 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005907 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005908 description = "avoid";
5909 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005910 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005911 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005912 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005913
5914 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5915 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005916 if (null == configValue) {
5917 description = "unset";
5918 } else if (configValue) {
5919 description = "force true";
5920 } else {
5921 description = "force false";
5922 }
5923 pw.println("Actively prefer bad wifi conf: " + description);
5924 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005925 pw.println("Network overrides:");
5926 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005927 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005928 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005929 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005930 }
5931 }
5932 pw.decreaseIndent();
5933 pw.decreaseIndent();
5934 }
5935
paulhu7746e4e2020-06-09 19:07:03 +08005936 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5937 // unify the method.
5938 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5939 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5940 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5941 return settingsComponent != null
5942 ? settingsComponent.getPackageName() : "com.android.settings";
5943 }
5944
lucaslinb1e8e382019-01-24 15:55:30 +08005945 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005946 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005947 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005948 switch (type) {
5949 case NO_INTERNET:
5950 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005951 // High priority because it is only displayed for explicitly selected networks.
5952 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005953 break;
lucasline117e2e2019-10-22 18:27:33 +08005954 case PRIVATE_DNS_BROKEN:
5955 action = Settings.ACTION_WIRELESS_SETTINGS;
5956 // High priority because we should let user know why there is no internet.
5957 highPriority = true;
5958 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005959 case LOST_INTERNET:
5960 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005961 // High priority because it could help the user avoid unexpected data usage.
5962 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005963 break;
lucaslin2240ef62019-03-12 13:08:03 +08005964 case PARTIAL_CONNECTIVITY:
5965 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005966 // Don't bother the user with a high-priority notification if the network was not
5967 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005968 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005969 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005970 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005971 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005972 return;
5973 }
5974
5975 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005976 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005977 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005978 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005979 // Some OEMs have their own Settings package. Thus, need to get the current using
5980 // Settings package name instead of just use default name "com.android.settings".
5981 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5982 intent.setClassName(settingsPkgName,
5983 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005984 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005985
paulhu2af50222020-10-11 22:52:27 +08005986 PendingIntent pendingIntent = PendingIntent.getActivity(
5987 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005988 0 /* requestCode */,
5989 intent,
paulhu2af50222020-10-11 22:52:27 +08005990 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005991
Serik Beketayevec8ad212020-12-07 22:43:07 -08005992 mNotifier.showNotification(
5993 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005994 }
5995
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005996 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5997 // Don't prompt if the network is validated, and don't prompt on captive portals
5998 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005999 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006000 return false;
6001 }
6002
6003 // If a network has partial connectivity, always prompt unless the user has already accepted
6004 // partial connectivity and selected don't ask again. This ensures that if the device
6005 // automatically connects to a network that has partial Internet access, the user will
6006 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006007 // because we have prompted them.
6008 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006009 return true;
6010 }
6011
6012 // If a network has no Internet access, only prompt if the network was explicitly selected
6013 // and if the user has not already told us to use the network regardless of whether it
6014 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006015 if (nai.networkAgentConfig.explicitlySelected
6016 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006017 return true;
6018 }
6019
6020 return false;
6021 }
6022
Chalard Jean5fb43c72022-09-08 19:03:14 +09006023 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6024 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006025
Chalard Jean5fb43c72022-09-08 19:03:14 +09006026 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6027 if (null == nai) return;
6028
6029 if (nai.setEvaluated()) {
6030 // If setEvaluated() returned true, the network never had any form of connectivity.
6031 // This may have an impact on request matching if bad WiFi avoidance is off and the
6032 // network was found not to have Internet access.
6033 nai.updateScoreForNetworkAgentUpdate();
6034 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006035
6036 // Also, if this is WiFi and it should be preferred actively, now is the time to
6037 // prompt the user that they walked past and connected to a bad WiFi.
6038 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6039 && !avoidBadWifi()
6040 && activelyPreferBadWifi()) {
6041 // The notification will be removed if the network validates or disconnects.
6042 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6043 return;
6044 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006045 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006046
Chalard Jean5fb43c72022-09-08 19:03:14 +09006047 if (!shouldPromptUnvalidated(nai)) return;
6048
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006049 // Stop automatically reconnecting to this network in the future. Automatically connecting
6050 // to a network that provides no or limited connectivity is not useful, because the user
6051 // cannot use that network except through the notification shown by this method, and the
6052 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006053 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006054
Chalard Jean254bd162022-08-25 13:04:51 +09006055 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006056 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006057 } else {
6058 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6059 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006060 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006061
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006062 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6063 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006064 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006065
lucaslin2240ef62019-03-12 13:08:03 +08006066 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6067 return;
6068 }
6069
6070 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006071 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006072 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006073 }
6074
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006075 @Override
6076 public int getMultipathPreference(Network network) {
6077 enforceAccessPermission();
6078
6079 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006080 if (nai != null && nai.networkCapabilities
6081 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006082 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6083 }
6084
Aaron Huang9a57acf2020-12-08 10:03:29 +08006085 final NetworkPolicyManager netPolicyManager =
6086 mContext.getSystemService(NetworkPolicyManager.class);
6087
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006088 final long token = Binder.clearCallingIdentity();
6089 final int networkPreference;
6090 try {
6091 networkPreference = netPolicyManager.getMultipathPreference(network);
6092 } finally {
6093 Binder.restoreCallingIdentity(token);
6094 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006095 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006096 return networkPreference;
6097 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006098 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6099 }
6100
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006101 @Override
6102 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006103 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006104 }
6105
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006106 private class InternalHandler extends Handler {
6107 public InternalHandler(Looper looper) {
6108 super(looper);
6109 }
6110
6111 @Override
6112 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006113 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006114 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006115 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006116 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006117 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006118 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006119 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006120 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006121 break;
6122 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006123 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006124 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006125 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006126 break;
6127 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006128 case EVENT_REGISTER_NETWORK_PROVIDER: {
6129 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006130 break;
6131 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006132 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6133 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006134 break;
6135 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006136 case EVENT_REGISTER_NETWORK_OFFER: {
6137 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6138 break;
6139 }
6140 case EVENT_UNREGISTER_NETWORK_OFFER: {
6141 final NetworkOfferInfo offer =
6142 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6143 if (null != offer) {
6144 handleUnregisterNetworkOffer(offer);
6145 }
6146 break;
6147 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006148 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006149 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6150 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6151 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006152 break;
6153 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006154 case EVENT_REGISTER_NETWORK_REQUEST:
6155 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006156 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006157 break;
6158 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006159 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6160 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006161 handleRegisterNetworkRequestWithIntent(msg);
6162 break;
6163 }
Erik Kline155a59a2015-11-25 12:49:38 +09006164 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6165 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6166 handleTimedOutNetworkRequest(nri);
6167 break;
6168 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006169 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6170 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6171 break;
6172 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006173 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006174 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6175 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006176 break;
6177 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006178 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006179 Network network = (Network) msg.obj;
6180 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006181 break;
6182 }
lucaslin2240ef62019-03-12 13:08:03 +08006183 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6184 Network network = (Network) msg.obj;
6185 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6186 toBool(msg.arg2));
6187 break;
6188 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006189 case EVENT_SET_AVOID_UNVALIDATED: {
6190 handleSetAvoidUnvalidated((Network) msg.obj);
6191 break;
6192 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006193 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6194 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006195 break;
6196 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006197 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6198 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006199 break;
6200 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006201 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6202 // handler thread.
6203 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006204 mKeepaliveTracker.handleStartKeepalive(msg);
6205 break;
6206 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006207 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006208 final AutomaticOnOffKeepalive ki =
6209 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6210 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006211
chiachangwang676c84e2023-02-14 09:22:05 +00006212 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006213 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006214 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006215 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006216 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6217 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006218 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6219 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006220 }
6221 }
6222
6223 // If the network no longer exists, then the keepalive should have been
6224 // cleaned up already. There is no point trying to resume keepalives.
6225 if (!networkFound) return;
6226
chiachangwang676c84e2023-02-14 09:22:05 +00006227 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006228 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00006229 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006230 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006231 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006232 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006233 }
6234 break;
6235 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006236 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006237 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006238 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6239 (IBinder) msg.obj);
6240 if (ki == null) {
6241 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006242 return;
6243 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006244 final int reason = msg.arg2;
6245 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006246 break;
6247 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006248 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6249 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6250 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006251 break;
6252 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006253 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6254 handlePrivateDnsSettingsChanged();
6255 break;
dalyk1720e542018-03-05 12:42:22 -05006256 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6257 handlePrivateDnsValidationUpdate(
6258 (PrivateDnsValidationUpdate) msg.obj);
6259 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006260 case EVENT_UID_BLOCKED_REASON_CHANGED:
6261 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006262 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006263 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6264 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6265 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006266 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006267 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6268 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006269 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006270 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006271 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006272 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006273 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6274 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006275 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006276 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006277 }
lucaslin1193a5d2021-01-21 02:04:15 +08006278 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006279 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006280 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006281 break;
paulhu51f77dc2021-06-07 02:34:20 +00006282 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6283 handleMobileDataPreferredUidsChanged();
6284 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006285 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6286 final long timeMs = ((Long) msg.obj).longValue();
6287 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6288 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006289 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6290 handleIngressRateLimitChanged();
6291 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006292 case EVENT_USER_DOES_NOT_WANT:
6293 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6294 if (nai == null) break;
6295 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006296 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006297 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006298 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6299 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6300 break;
chiachangwange0192a72023-02-06 13:25:01 +00006301 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6302 final long time = ((Long) msg.obj).longValue();
6303 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6304 break;
6305 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006306 case EVENT_UID_FROZEN_STATE_CHANGED:
6307 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6308 handleFrozenUids(args.mUids, args.mFrozenStates);
6309 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006310 }
6311 }
6312 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006313
Lorenzo Colittid6459092016-07-04 12:55:44 +09006314 @Override
markchien5776f962019-12-16 20:15:20 +08006315 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006316 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006317 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006318 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6319 Context.TETHERING_SERVICE);
6320 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006321 }
6322
Lorenzo Colittid6459092016-07-04 12:55:44 +09006323 @Override
markchien5776f962019-12-16 20:15:20 +08006324 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006325 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006326 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006327 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6328 Context.TETHERING_SERVICE);
6329 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006330 }
6331
Lorenzo Colittid6459092016-07-04 12:55:44 +09006332 @Override
markchien5776f962019-12-16 20:15:20 +08006333 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006334 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006335 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006336 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6337 Context.TETHERING_SERVICE);
6338 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006339 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006340
markchien5776f962019-12-16 20:15:20 +08006341
Lorenzo Colittid6459092016-07-04 12:55:44 +09006342 @Override
markchien5776f962019-12-16 20:15:20 +08006343 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006344 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006345 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006346 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6347 Context.TETHERING_SERVICE);
6348
6349 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006350 }
6351
Lorenzo Colittid6459092016-07-04 12:55:44 +09006352 @Override
markchien5776f962019-12-16 20:15:20 +08006353 @Deprecated
6354 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006355 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006356 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6357 Context.TETHERING_SERVICE);
6358
6359 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006360 }
6361
Udam Saini8f7d6a72017-06-07 12:06:28 -07006362 @Override
markchien5776f962019-12-16 20:15:20 +08006363 @Deprecated
6364 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006365 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006366 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6367 Context.TETHERING_SERVICE);
6368 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006369 }
6370
Robert Greenwalte0b00512014-07-02 09:59:16 -07006371 // Called when we lose the default network and have no replacement yet.
6372 // This will automatically be cleared after X seconds or a new default network
6373 // becomes CONNECTED, whichever happens first. The timer is started by the
6374 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006375 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006376 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006377 if (mNetTransitionWakeLock.isHeld()) {
6378 return;
6379 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006380 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006381 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6382 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006383 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006384 mWakelockLogs.log("ACQUIRE for " + forWhom);
6385 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006386 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006387 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006388 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006389 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006390
Hugo Benichi471b62a2017-03-30 23:18:10 +09006391 // Called when we gain a new default network to release the network transition wakelock in a
6392 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6393 // message is cancelled.
6394 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006395 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006396 if (!mNetTransitionWakeLock.isHeld()) {
6397 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006398 }
6399 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006400 // Cancel self timeout on wakelock hold.
6401 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6402 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6403 mHandler.sendMessageDelayed(msg, 1000);
6404 }
6405
6406 // Called when either message of ensureNetworkTransitionWakelock or
6407 // scheduleReleaseNetworkTransitionWakelock is processed.
6408 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6409 String event = eventName(eventId);
6410 synchronized (this) {
6411 if (!mNetTransitionWakeLock.isHeld()) {
6412 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006413 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006414 return;
6415 }
6416 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006417 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6418 mTotalWakelockDurationMs += lockDuration;
6419 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6420 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006421 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006422 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006423 }
6424
Robert Greenwalt986c7412010-09-08 15:24:47 -07006425 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006426 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006427 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006428 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006429 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006430 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006431 }
6432
Lorenzo Colittid6459092016-07-04 12:55:44 +09006433 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006434 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006435 enforceAccessPermission();
6436 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006437 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006438 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006439
6440 final NetworkAgentInfo nai;
6441 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006442 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006443 } else {
6444 nai = getNetworkAgentInfoForNetwork(network);
6445 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006446
6447 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006448 mHandler.obtainMessage(
6449 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006450 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006451
Hugo Benichid6b510a2017-04-06 17:22:18 +09006452 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006453 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006454 if (nai == null
6455 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006456 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006457 return;
6458 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006459 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006460 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006461 mConnectivityDiagnosticsHandler.sendMessage(
6462 mConnectivityDiagnosticsHandler.obtainMessage(
6463 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6464 new ReportedNetworkConnectivityInfo(
6465 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006466 return;
6467 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006468 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006469 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006470 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006471 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006472 // Validating a network that has not yet connected could result in a call to
6473 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006474 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006475 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006476 }
paulhu7aeba372020-12-30 00:42:19 +08006477 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6478 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006479 return;
6480 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006481
6482 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6483 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6484 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6485 // completed.
6486 mConnectivityDiagnosticsHandler.sendMessage(
6487 mConnectivityDiagnosticsHandler.obtainMessage(
6488 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6489 new ReportedNetworkConnectivityInfo(
6490 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006491 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006492 }
6493
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006494 // TODO: call into netd.
6495 private boolean queryUserAccess(int uid, Network network) {
6496 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6497 if (nai == null) return false;
6498
6499 // Any UID can use its default network.
6500 if (nai == getDefaultNetworkForUid(uid)) return true;
6501
6502 // Privileged apps can use any network.
6503 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6504 return true;
6505 }
6506
6507 // An unprivileged UID can use a VPN iff the VPN applies to it.
6508 if (nai.isVPN()) {
6509 return nai.networkCapabilities.appliesToUid(uid);
6510 }
6511
6512 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6513 // sockets, i.e., if it is the owner.
6514 final NetworkAgentInfo vpn = getVpnForUid(uid);
6515 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6516 && uid != vpn.networkCapabilities.getOwnerUid()) {
6517 return false;
6518 }
6519
6520 // The UID's permission must be at least sufficient for the network. Since the restricted
6521 // permission was already checked above, that just leaves background networks.
6522 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6523 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6524 }
6525
6526 // Unrestricted network. Anyone gets to use it.
6527 return true;
6528 }
6529
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006530 /**
6531 * Returns information about the proxy a certain network is using. If given a null network, it
6532 * it will return the proxy for the bound network for the caller app or the default proxy if
6533 * none.
6534 *
6535 * @param network the network we want to get the proxy information for.
6536 * @return Proxy information if a network has a proxy configured, or otherwise null.
6537 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006538 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006539 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006540 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006541 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006542 if (network == null) {
6543 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006544 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006545 true);
6546 if (activeNetwork == null) {
6547 return null;
6548 }
6549 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006550 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006551 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6552 // caller may not have.
6553 return getLinkPropertiesProxyInfo(network);
6554 }
6555 // No proxy info available if the calling UID does not have network access.
6556 return null;
6557 }
6558
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006559
6560 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006561 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6562 if (nai == null) return null;
6563 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006564 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6565 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006566 }
6567 }
6568
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006569 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006570 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006571 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006572 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006573 }
6574
Chalard Jean777e2e52018-06-07 18:02:37 +09006575 @Override
6576 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006577 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006578 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006579 }
6580
Aaron Huang9fe47be2021-06-08 13:11:45 +08006581 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006582 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006583 final NetworkAgentInfo nai = getDefaultNetwork();
6584 // TODO : this method should check that net == nai.network, unfortunately at this point
6585 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6586 // is only ever installed on the default network so in practice this is okay.
6587 if (null == nai) return;
6588 // PAC proxies only work on the default network. Therefore, only the default network
6589 // should have its link properties fixed up for PAC proxies.
6590 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6591 if (nai.everConnected()) {
6592 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6593 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006594 }
6595
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006596 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6597 // when any network changes proxy.
6598 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6599 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006600 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6601 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006602 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6603
Chalard Jean7d97afc2018-06-07 17:41:29 +09006604 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006605 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006606 }
6607 }
6608
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006609 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006610 final private HashMap<Uri, Integer> mUriEventMap;
6611 final private Context mContext;
6612 final private Handler mHandler;
6613
6614 SettingsObserver(Context context, Handler handler) {
6615 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006616 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006617 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006618 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006619 }
6620
Erik Kline05f2b402015-04-30 12:58:40 +09006621 void observe(Uri uri, int what) {
6622 mUriEventMap.put(uri, what);
6623 final ContentResolver resolver = mContext.getContentResolver();
6624 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006625 }
6626
6627 @Override
6628 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006629 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006630 }
6631
6632 @Override
6633 public void onChange(boolean selfChange, Uri uri) {
6634 final Integer what = mUriEventMap.get(uri);
6635 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006636 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006637 } else {
6638 loge("No matching event to send for URI=" + uri);
6639 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006640 }
6641 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006642
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006643 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006644 Log.d(TAG, s);
6645 }
6646
6647 private static void logw(String s) {
6648 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006649 }
6650
Daniel Brightf9e945b2020-06-15 16:10:01 -07006651 private static void logwtf(String s) {
6652 Log.wtf(TAG, s);
6653 }
6654
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006655 private static void logwtf(String s, Throwable t) {
6656 Log.wtf(TAG, s, t);
6657 }
6658
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006659 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006660 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006661 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006662
Hugo Benichi39621362017-02-11 17:04:43 +09006663 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006664 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006665 }
6666
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006667 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006668 * Return the information of all ongoing VPNs.
6669 *
6670 * <p>This method is used to update NetworkStatsService.
6671 *
6672 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006673 */
junyulai2050bed2021-01-23 09:46:34 +08006674 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006675 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006676 if (mLockdownEnabled) {
6677 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006678 }
junyulai2050bed2021-01-23 09:46:34 +08006679 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006680 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006681 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006682 if (info != null) {
6683 infoList.add(info);
6684 }
6685 }
junyulai2050bed2021-01-23 09:46:34 +08006686 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006687 }
6688
6689 /**
6690 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006691 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006692 */
junyulai2050bed2021-01-23 09:46:34 +08006693 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006694 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006695 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6696 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006697 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6698 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6699 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006700 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6701 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006702 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006703 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006704 }
6705 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006706
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006707 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006708
6709 List<String> interfaces = new ArrayList<>();
6710 for (Network network : underlyingNetworks) {
6711 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6712 if (underlyingNai == null) continue;
6713 LinkProperties lp = underlyingNai.linkProperties;
6714 for (String iface : lp.getAllInterfaceNames()) {
6715 if (!TextUtils.isEmpty(iface)) {
6716 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006717 }
6718 }
Benedict Wong34857f82019-06-12 17:46:15 +00006719 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006720
6721 if (interfaces.isEmpty()) return null;
6722
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006723 // Must be non-null or NetworkStatsService will crash.
6724 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6725 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006726 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006727 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006728
junyulai2050bed2021-01-23 09:46:34 +08006729 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6730 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006731 }
6732
James Mattisd31bdfa2020-12-23 16:37:26 -08006733 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006734 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6735 Network[] underlyingNetworks) {
6736 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006737 if (underlyingNetworks == null && defaultNetwork != null) {
6738 // null underlying networks means to track the default.
6739 underlyingNetworks = new Network[] { defaultNetwork };
6740 }
6741 return underlyingNetworks;
6742 }
6743
6744 // Returns true iff |network| is an underlying network of |nai|.
6745 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6746 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6747 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006748 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006749 final Network[] underlying = underlyingNetworksOrDefault(
6750 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006751 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006752 }
6753
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006754 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006755 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006756 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006757 * When underlying networks change, such networks may have to update capabilities to reflect
6758 * things like the metered bit, their transports, and so on. The capabilities are calculated
6759 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006760 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006761 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006762 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006763 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006764 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006765 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006766 }
6767 }
6768 }
6769
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006770 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6771 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6772 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6773 // a VPN is not up.
6774 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6775 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6776 for (UidRange range : blockedUidRanges) {
6777 if (range.contains(uid)) return true;
6778 }
6779 return false;
6780 }
6781
6782 @Override
6783 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006784 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006785 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6786 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6787 }
6788
6789 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6790 if (DBG) {
6791 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6792 + Arrays.toString(ranges));
6793 }
6794 // Cannot use a Set since the list of UID ranges might contain duplicates.
6795 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6796 for (int i = 0; i < ranges.length; i++) {
6797 if (requireVpn) {
6798 newVpnBlockedUidRanges.add(ranges[i]);
6799 } else {
6800 newVpnBlockedUidRanges.remove(ranges[i]);
6801 }
6802 }
6803
6804 try {
6805 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6806 } catch (RemoteException | ServiceSpecificException e) {
6807 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6808 + Arrays.toString(ranges) + "): netd command failed: " + e);
6809 }
6810
Chalard Jeandf29a852023-05-29 17:02:43 +09006811 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006812 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6813 }
6814
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006815 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6816 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006817 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6818 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006819 }
6820
6821 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6822 }
6823
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006824 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006825 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006826 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006827 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006828 }
6829
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006830 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6831 return mLockdownEnabled
6832 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6833 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006834 }
6835
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006836 private NetworkAgentInfo getLegacyLockdownNai() {
6837 if (!mLockdownEnabled) {
6838 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006839 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006840 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006841 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6842 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006843
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006844 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006845 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6846 // a local variable. There is no need to make a copy because its contents cannot change.
6847 final Network[] underlying = nai.declaredUnderlyingNetworks;
6848 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006849 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006850 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006851
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006852 // The legacy lockdown VPN always uses the default network.
6853 // If the VPN's underlying network is no longer the current default network, it means that
6854 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006855 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6856 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006857 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006858 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006859 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006860 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006861
6862 return nai;
6863 };
6864
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006865 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6866 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6867 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006868 private DetailedState getLegacyLockdownState(DetailedState origState) {
6869 if (origState != DetailedState.CONNECTED) {
6870 return origState;
6871 }
6872 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6873 ? DetailedState.CONNECTING
6874 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006875 }
6876
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006877 private void filterForLegacyLockdown(NetworkInfo ni) {
6878 if (!mLockdownEnabled || !ni.isConnected()) return;
6879 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6880 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6881 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6882 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6883 // network, this time with a state of CONNECTED.
6884 //
6885 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6886 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6887 // is not too far off the truth, since an always-on VPN, when not connected, is always
6888 // trying to reconnect.
6889 if (getLegacyLockdownNai() == null) {
6890 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6891 }
6892 }
6893
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006894 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006895 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006896 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006897 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006898 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6899 return;
6900 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006901 final long ident = Binder.clearCallingIdentity();
6902 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006903 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006904 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006905 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006906 } finally {
6907 Binder.restoreCallingIdentity(ident);
6908 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006909 }
Wink Savillecb117d32013-08-29 14:57:08 -07006910
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006911 @Override
6912 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006913 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006914 final long ident = Binder.clearCallingIdentity();
6915 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006916 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006917 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006918 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6919 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006920 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006921 } finally {
6922 Binder.restoreCallingIdentity(ident);
6923 }
6924 }
6925
James Mattis02220e22021-03-13 19:27:21 -08006926 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006927 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6928 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6929 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006930 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006931 }
6932
James Mattis02220e22021-03-13 19:27:21 -08006933 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006934 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006935 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006936 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6937 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006938 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006939 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6940 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6941 }
junyulaid91e7052020-08-28 13:44:33 +08006942 }
6943
James Mattis02220e22021-03-13 19:27:21 -08006944 private void onPackageChanged(@NonNull final String packageName) {
6945 // This is necessary in case a package is added or removed, but also when it's replaced to
6946 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6947 // as one in the preferences, then it should follow the same routing as that other package,
6948 // which means updating the rules is never to be needed in this case (whether it joins or
6949 // leaves a UID with a preference).
6950 if (isMappedInOemNetworkPreference(packageName)) {
6951 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6952 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006953
6954 // Invalidates cache entry when the package is updated.
6955 synchronized (mSelfCertifiedCapabilityCache) {
6956 mSelfCertifiedCapabilityCache.remove(packageName);
6957 }
James Mattis02220e22021-03-13 19:27:21 -08006958 }
6959
6960 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006961 @Override
6962 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006963 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006964 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006965 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006966
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006967 // User should be filled for below intents, check the existence.
6968 if (user == null) {
6969 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6970 return;
6971 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006972
Lorenzo Colitticd675292021-02-04 17:32:07 +09006973 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006974 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006975 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006976 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006977 } else {
junyulaid91e7052020-08-28 13:44:33 +08006978 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006979 }
6980 }
6981 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006982
James Mattis02220e22021-03-13 19:27:21 -08006983 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6984 @Override
6985 public void onReceive(Context context, Intent intent) {
6986 ensureRunningOnConnectivityServiceThread();
6987 switch (intent.getAction()) {
6988 case Intent.ACTION_PACKAGE_ADDED:
6989 case Intent.ACTION_PACKAGE_REMOVED:
6990 case Intent.ACTION_PACKAGE_REPLACED:
6991 onPackageChanged(intent.getData().getSchemeSpecificPart());
6992 break;
6993 default:
6994 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6995 }
6996 }
6997 };
6998
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006999 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007000 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007001
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007002 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007003 public final String name;
7004 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007005 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007006 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007007
lifraf3a3492021-03-10 13:58:14 +08007008 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7009 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007010 this.name = name;
7011 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007012 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007013 mDeathRecipient = deathRecipient;
7014
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007015 if (mDeathRecipient == null) {
7016 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007017 }
7018 }
7019
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007020 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007021 try {
7022 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7023 } catch (RemoteException e) {
7024 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007025 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007026 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007027 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007028
James Mattis4fce5d12020-11-12 15:53:42 -08007029 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7030 for (int i = 0; i < requests.size(); i++) {
7031 ensureNetworkRequestHasType(requests.get(i));
7032 }
7033 }
7034
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007035 private void ensureNetworkRequestHasType(NetworkRequest request) {
7036 if (request.type == NetworkRequest.Type.NONE) {
7037 throw new IllegalArgumentException(
7038 "All NetworkRequests in ConnectivityService must have a type");
7039 }
7040 }
7041
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007042 /**
7043 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007044 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007045 */
James Mattis258ea3c2020-11-15 15:04:40 -08007046 @VisibleForTesting
7047 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007048 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7049 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007050 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007051
James Mattisa076c532020-12-02 14:12:41 -08007052 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7053 void setSatisfier(
7054 @Nullable final NetworkAgentInfo satisfier,
7055 @Nullable final NetworkRequest activeRequest) {
7056 mSatisfier = satisfier;
7057 mActiveRequest = activeRequest;
7058 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007059
James Mattisd31bdfa2020-12-23 16:37:26 -08007060 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007061 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007062 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007063 private NetworkAgentInfo mSatisfier;
7064 NetworkAgentInfo getSatisfier() {
7065 return mSatisfier;
7066 }
7067
7068 // The request in mRequests assigned to a network agent. This is null if none of the
7069 // requests in mRequests can be satisfied. This member has the constraint of only being
7070 // accessible on the handler thread.
7071 @Nullable
7072 private NetworkRequest mActiveRequest;
7073 NetworkRequest getActiveRequest() {
7074 return mActiveRequest;
7075 }
7076
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007077 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007078 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007079 @Nullable
7080 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007081
7082 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007083 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007084 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007085 final int mPid;
7086 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007087 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007088 @Nullable
7089 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007090
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007091 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007092 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007093
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007094 // Effective UID of this request. This is different from mUid when a privileged process
7095 // files a request on behalf of another UID. This UID is used to determine blocked status,
7096 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7097 // maximum limit of registered callbacks per UID.
7098 final int mAsUid;
7099
paulhu48291862021-07-14 14:53:57 +08007100 // Preference order of this request.
7101 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007102
James Mattis3ce3d3c2021-02-09 18:18:28 -08007103 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7104 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7105 // maintained for keying off of. This is only a concern when the original nri
7106 // mNetworkRequests changes which happens currently for apps that register callbacks to
7107 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7108 // that match the per-app default nri that currently tracks the calling app's uid so that
7109 // callbacks are fired at the appropriate time. When the callbacks fire,
7110 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7111 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7112 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7113 @NonNull
7114 private final NetworkRequest mNetworkRequestForCallback;
7115 NetworkRequest getNetworkRequestForCallback() {
7116 return mNetworkRequestForCallback;
7117 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007118
James Mattisd31bdfa2020-12-23 16:37:26 -08007119 /**
7120 * Get the list of UIDs this nri applies to.
7121 */
7122 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007123 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007124 // networkCapabilities.getUids() returns a defensive copy.
7125 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007126 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7127 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007128 }
7129
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007130 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7131 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007132 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007133 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007134 }
7135
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007136 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007137 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007138 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007139 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007140 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007141 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007142 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007143 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007144 mBinder = null;
7145 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007146 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007147 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007148 mPerUidCounter = getRequestCounter(this);
7149 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007150 /**
7151 * Location sensitive data not included in pending intent. Only included in
7152 * {@link NetworkCallback}.
7153 */
7154 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007155 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007156 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007157 }
7158
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007159 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007160 @Nullable final IBinder binder,
7161 @NetworkCallback.Flag int callbackFlags,
7162 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007163 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7164 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007165 }
7166
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007167 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007168 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007169 @Nullable final IBinder binder,
7170 @NetworkCallback.Flag int callbackFlags,
7171 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007172 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007173 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007174 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007175 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007176 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007177 mBinder = binder;
7178 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007179 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007180 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007181 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007182 mPerUidCounter = getRequestCounter(this);
7183 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007184 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007185 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007186 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007187 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007188 }
7189
James Mattis3ce3d3c2021-02-09 18:18:28 -08007190 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7191 @NonNull final List<NetworkRequest> r) {
7192 super();
7193 ensureAllNetworkRequestsHaveType(r);
7194 mRequests = initializeRequests(r);
7195 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007196 final NetworkAgentInfo satisfier = nri.getSatisfier();
7197 if (null != satisfier) {
7198 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7199 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007200 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007201 // As this code creates a new NRI with a new set of requests, figure out which of
7202 // the list of requests should be the active request. It is always the first
7203 // request of the list that can be satisfied by the satisfier since the order of
7204 // requests is a priority order.
7205 // Note even in the presence of a satisfier there may not be an active request,
7206 // when the satisfier is the no-service network.
7207 NetworkRequest activeRequest = null;
7208 for (final NetworkRequest candidate : r) {
7209 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7210 activeRequest = candidate;
7211 break;
7212 }
7213 }
7214 setSatisfier(satisfier, activeRequest);
7215 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007216 mMessenger = nri.mMessenger;
7217 mBinder = nri.mBinder;
7218 mPid = nri.mPid;
7219 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007220 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007221 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007222 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007223 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007224 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007225 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007226 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007227 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007228 }
7229
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007230 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007231 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007232 }
7233
paulhue9913722021-05-26 15:19:20 +08007234 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007235 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007236 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007237 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007238 }
7239
James Mattis2516da32021-01-31 17:06:19 -08007240 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7241 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7242 // false.
7243 boolean isBeingSatisfied() {
7244 return (null != mSatisfier && null != mActiveRequest);
7245 }
7246
James Mattis3d229892020-11-16 16:46:28 -08007247 boolean isMultilayerRequest() {
7248 return mRequests.size() > 1;
7249 }
7250
James Mattis45d81842021-01-10 14:24:24 -08007251 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7252 // Creating a defensive copy to prevent the sender from modifying the list being
7253 // reflected in the return value of this method.
7254 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007255 return Collections.unmodifiableList(tempRequests);
7256 }
7257
James Mattisb1392002021-03-31 13:57:52 -07007258 void linkDeathRecipient() {
7259 if (null != mBinder) {
7260 try {
7261 mBinder.linkToDeath(this, 0);
7262 } catch (RemoteException e) {
7263 binderDied();
7264 }
7265 }
7266 }
7267
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007268 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007269 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007270 try {
7271 mBinder.unlinkToDeath(this, 0);
7272 } catch (NoSuchElementException e) {
7273 // Temporary workaround for b/194394697 pending analysis of additional logs
7274 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7275 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007276 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007277 }
7278
paulhu48291862021-07-14 14:53:57 +08007279 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7280 // Compare two preference orders.
7281 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007282 }
7283
paulhu48291862021-07-14 14:53:57 +08007284 int getPreferenceOrderForNetd() {
7285 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7286 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7287 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007288 }
paulhu48291862021-07-14 14:53:57 +08007289 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007290 }
7291
James Mattis4fce5d12020-11-12 15:53:42 -08007292 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007293 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007294 // As an immutable collection, mRequests cannot change by the time the
7295 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7296 // is acceptable. Use handleReleaseNetworkRequest and not directly
7297 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7298 // the app already unregistered the request.
7299 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7300 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007301 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007302
James Mattis4fce5d12020-11-12 15:53:42 -08007303 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007304 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007305 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7306 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007307 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007308 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007309 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007310 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007311 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007312 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007313 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007314 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007315 }
7316
Junyu Lai00d92df2022-07-05 11:01:52 +08007317 // Keep backward compatibility since the ServiceSpecificException is used by
7318 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7319 public static class RequestInfoPerUidCounter extends PerUidCounter {
7320 RequestInfoPerUidCounter(int maxCountPerUid) {
7321 super(maxCountPerUid);
7322 }
7323
7324 @Override
7325 public synchronized void incrementCountOrThrow(int uid) {
7326 try {
7327 super.incrementCountOrThrow(uid);
7328 } catch (IllegalStateException e) {
7329 throw new ServiceSpecificException(
7330 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7331 "Uid " + uid + " exceeded its allotted requests limit");
7332 }
7333 }
7334
7335 @Override
7336 public synchronized void decrementCountOrThrow(int uid) {
7337 throw new UnsupportedOperationException("Use decrementCount instead.");
7338 }
7339
7340 public synchronized void decrementCount(int uid) {
7341 try {
7342 super.decrementCountOrThrow(uid);
7343 } catch (IllegalStateException e) {
7344 logwtf("Exception when decrement per uid request count: ", e);
7345 }
7346 }
7347 }
7348
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007349 // This checks that the passed capabilities either do not request a
7350 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007351 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007352 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007353 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007354 throw new SecurityException("Insufficient permissions to request a specific SSID");
7355 }
paulhu1a407652019-03-22 16:35:06 +08007356
7357 if (nc.hasSignalStrength()
7358 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7359 throw new SecurityException(
7360 "Insufficient permissions to request a specific signal strength");
7361 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007362 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007363
junyulai2217bec2021-04-14 23:33:31 +08007364 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007365 enforceNetworkFactoryPermission();
7366 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007367 }
7368
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007369 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007370 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007371 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007372 // mNetworkRequests may contain the same value multiple times in case of
7373 // multilayer requests. It won't matter in this case because the thresholds
7374 // will then be the same and be deduplicated as they enter the `thresholds` set.
7375 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007376 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7377 for (final NetworkRequest req : nri.mRequests) {
7378 if (req.networkCapabilities.hasSignalStrength()
7379 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7380 thresholds.add(req.networkCapabilities.getSignalStrength());
7381 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007382 }
7383 }
7384 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007385 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007386 }
7387
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007388 private void updateSignalStrengthThresholds(
7389 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007390 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007391
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007392 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007393 String detail;
7394 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7395 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7396 } else {
7397 detail = reason;
7398 }
7399 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007400 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007401 }
7402
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007403 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007404 }
7405
Chalard Jeandd421992021-12-16 23:16:02 +09007406 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007407 if (nc == null) {
7408 return;
7409 }
7410 NetworkSpecifier ns = nc.getNetworkSpecifier();
7411 if (ns == null) {
7412 return;
7413 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007414 if (ns instanceof MatchAllNetworkSpecifier) {
7415 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7416 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007417 }
7418
Chalard Jeandd421992021-12-16 23:16:02 +09007419 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007420 ensureValidNetworkSpecifier(nc);
7421 if (nc.isPrivateDnsBroken()) {
7422 throw new IllegalArgumentException("Can't request broken private DNS");
7423 }
Chalard Jeande665262022-02-25 16:12:12 +09007424 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007425 throw new IllegalArgumentException("Can't request access UIDs");
7426 }
lucasline117e2e2019-10-22 18:27:33 +08007427 }
7428
Chalard Jeandd421992021-12-16 23:16:02 +09007429 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7430 ensureListenableCapabilities(nc);
7431 final String badCapability = nc.describeFirstNonRequestableCapability();
7432 if (badCapability != null) {
7433 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7434 }
7435 }
7436
Chiachang Wang3bc52762021-11-25 14:17:57 +08007437 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7438 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007439 private boolean isTargetSdkAtleast(int version, int callingUid,
7440 @NonNull String callingPackageName) {
7441 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007442 final PackageManager pm =
7443 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007444 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007445 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007446 if (callingVersion < version) return false;
7447 } catch (PackageManager.NameNotFoundException e) { }
7448 return true;
7449 }
7450
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007451 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007452 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007453 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007454 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007455 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007456 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007457 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7458 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007459 throw new SecurityException("Insufficient permissions to specify legacy type");
7460 }
markchienfac84a22020-03-18 21:16:15 +08007461 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007462 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007463 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007464 // Privileged callers can track the default network of another UID by passing in a UID.
7465 if (asUid != Process.INVALID_UID) {
7466 enforceSettingsPermission();
7467 } else {
7468 asUid = callingUid;
7469 }
junyulaiad010792021-01-11 16:53:38 +08007470 final NetworkRequest.Type reqType;
7471 try {
7472 reqType = NetworkRequest.Type.values()[reqTypeInt];
7473 } catch (ArrayIndexOutOfBoundsException e) {
7474 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7475 }
7476 switch (reqType) {
7477 case TRACK_DEFAULT:
7478 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007479 // is unused and will be replaced by ones appropriate for the UID (usually, the
7480 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007481 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007482 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007483 enforceAccessPermission();
7484 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007485 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007486 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007487 networkCapabilities = new NetworkCapabilities(defaultNc);
7488 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007489 case BACKGROUND_REQUEST:
7490 enforceNetworkStackOrSettingsPermission();
7491 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007492 case REQUEST:
7493 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7494 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007495 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007496 // TODO: this is incorrect. We mark the request as metered or not depending on
7497 // the state of the app when the request is filed, but we never change the
7498 // request if the app changes network state. http://b/29964605
7499 enforceMeteredApnPolicy(networkCapabilities);
7500 break;
junyulai1b1c8742021-03-12 20:05:08 +08007501 case LISTEN_FOR_BEST:
7502 enforceAccessPermission();
7503 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7504 break;
junyulaiad010792021-01-11 16:53:38 +08007505 default:
7506 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007507 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007508 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007509 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007510 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007511
junyulai1b1c8742021-03-12 20:05:08 +08007512 // Enforce FOREGROUND if the caller does not have permission to use background network.
7513 if (reqType == LISTEN_FOR_BEST) {
7514 restrictBackgroundRequestForCaller(networkCapabilities);
7515 }
7516
7517 // Set the UID range for this request to the single UID of the requester, unless the
7518 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007519 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7520 // are no visible methods to set the UIDs, an app could use reflection to try and get
7521 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007522 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007523 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7524 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007525
Etan Cohen85000162017-02-05 10:42:27 -08007526 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007527 throw new IllegalArgumentException("Bad timeout specified");
7528 }
Etan Cohen9786d922015-11-18 10:56:15 -08007529
James Mattis3ce3d3c2021-02-09 18:18:28 -08007530 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007531 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007532 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007533 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007534 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007535 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007536
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007537 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7538 // copied from the default request above. (This is necessary to ensure, for example, that
7539 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7540 // changes don't alter request matching.
7541 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7542 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007543 throw new IllegalStateException(
7544 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007545 + networkCapabilities + " vs. " + defaultNc);
7546 }
7547
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007548 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007549 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007550 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007551 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007552 }
7553 return networkRequest;
7554 }
7555
James Mattis3ce3d3c2021-02-09 18:18:28 -08007556 /**
7557 * Return the nri to be used when registering a network request. Specifically, this is used with
7558 * requests registered to track the default request. If there is currently a per-app default
7559 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7560 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007561 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7562 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007563 * @param nr the network request for the nri.
7564 * @param msgr the messenger for the nri.
7565 * @param binder the binder for the nri.
7566 * @param callingAttributionTag the calling attribution tag for the nri.
7567 * @return the nri to register.
7568 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007569 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007570 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007571 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007572 @Nullable String callingAttributionTag) {
7573 final List<NetworkRequest> requests;
7574 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7575 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007576 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007577 } else {
7578 requests = Collections.singletonList(nr);
7579 }
Roshan Pius951c0032020-12-22 15:10:42 -08007580 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007581 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007582 }
7583
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007584 private boolean shouldCheckCapabilitiesDeclaration(
7585 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7586 @NonNull final String callingPackageName) {
7587 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7588 // Only run the check if the change is enabled.
7589 if (!mDeps.isChangeEnabled(
7590 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7591 callingPackageName, user)) {
7592 return false;
7593 }
7594
7595 return networkCapabilities.hasCapability(
7596 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7597 || networkCapabilities.hasCapability(
7598 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7599 }
7600
7601 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7602 @NonNull final NetworkCapabilities networkCapabilities) {
7603 // This check is added to fix the linter error for "current min is 30", which is not going
7604 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007605 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007606 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7607 return;
7608 }
7609 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007610 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007611 try {
7612 synchronized (mSelfCertifiedCapabilityCache) {
7613 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7614 callerPackageName);
7615 if (applicationNetworkCapabilities == null) {
7616 final PackageManager packageManager = mContext.getPackageManager();
7617 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7618 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7619 callerPackageName
7620 );
7621 final XmlResourceParser parser = packageManager
7622 .getResourcesForApplication(callerPackageName)
7623 .getXml(networkSliceProperty.getResourceId());
7624 applicationNetworkCapabilities =
7625 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7626 mSelfCertifiedCapabilityCache.put(callerPackageName,
7627 applicationNetworkCapabilities);
7628 }
7629
7630 }
7631 } catch (PackageManager.NameNotFoundException ne) {
7632 throw new SecurityException(
7633 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7634 + " property");
7635 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7636 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007637 } finally {
7638 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007639 }
7640
7641 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7642 networkCapabilities);
7643 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007644 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007645 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007646 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7647 callingPackageName)) {
7648 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7649 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007650 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007651 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7652 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7653 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7654 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007655 }
junyulai96bd9fe2022-03-08 17:36:42 +08007656 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007657 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007658 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007659 }
7660 }
7661
fenglu3f357402015-03-20 11:29:56 -07007662 @Override
fenglub00f4882015-04-21 17:12:05 -07007663 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007664 enforceAccessPermission();
7665 NetworkAgentInfo nai = null;
7666 if (network == null) {
7667 return false;
7668 }
7669 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007670 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007671 }
7672 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007673 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007674 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007675 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007676 Integer uidReqs = mBandwidthRequests.get(uid);
7677 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007678 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007679 }
7680 mBandwidthRequests.put(uid, ++uidReqs);
7681 }
fenglu3f357402015-03-20 11:29:56 -07007682 return true;
7683 }
7684 return false;
7685 }
7686
Felipe Leme0a5ae422016-06-20 16:36:29 -07007687 private boolean isSystem(int uid) {
7688 return uid < Process.FIRST_APPLICATION_UID;
7689 }
fenglu3f357402015-03-20 11:29:56 -07007690
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007691 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007692 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007693 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007694 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007695 return;
7696 }
Hugo Benichi39621362017-02-11 17:04:43 +09007697 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7698 // Policy already enforced.
7699 return;
7700 }
paulhuaf50d7d2020-12-24 19:47:34 +08007701 final long ident = Binder.clearCallingIdentity();
7702 try {
7703 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7704 // If UID is restricted, don't allow them to bring up metered APNs.
7705 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7706 }
7707 } finally {
7708 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007709 }
7710 }
7711
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007712 @Override
7713 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007714 PendingIntent operation, @NonNull String callingPackageName,
7715 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007716 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007717 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007718 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007719 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007720 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007721 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007722 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007723 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007724 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007725 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7726 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007727
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007728 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007729 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007730 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7731 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007732 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007733 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7734 nri));
7735 return networkRequest;
7736 }
7737
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007738 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7739 mHandler.sendMessageDelayed(
7740 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007741 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007742 }
7743
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007744 @Override
7745 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007746 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007747 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007748 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007749 }
7750
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007751 // In order to implement the compatibility measure for pre-M apps that call
7752 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7753 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7754 // This ensures it has permission to do so.
7755 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7756 if (nc == null) {
7757 return false;
7758 }
7759 int[] transportTypes = nc.getTransportTypes();
7760 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7761 return false;
7762 }
7763 try {
7764 mContext.enforceCallingOrSelfPermission(
7765 android.Manifest.permission.ACCESS_WIFI_STATE,
7766 "ConnectivityService");
7767 } catch (SecurityException e) {
7768 return false;
7769 }
7770 return true;
7771 }
7772
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007773 @Override
7774 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007775 Messenger messenger, IBinder binder,
7776 @NetworkCallback.Flag int callbackFlags,
7777 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007778 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007779 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7780 enforceAccessPermission();
7781 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007782
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007783 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007784 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007785 Binder.getCallingPid(), callingUid, callingPackageName);
7786 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007787 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7788 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7789 // onLost and onAvailable callbacks when networks move in and out of the background.
7790 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7791 // can't request networks.
7792 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007793 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007794
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007795 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007796 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007797 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007798 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007799 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007800 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007801
7802 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7803 return networkRequest;
7804 }
7805
7806 @Override
7807 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007808 PendingIntent operation, @NonNull String callingPackageName,
7809 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007810 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007811 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007812 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7813 enforceAccessPermission();
7814 }
Chalard Jeandd421992021-12-16 23:16:02 +09007815 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007816 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007817 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007818 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007819 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007820
7821 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007822 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007823 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7824 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007825 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007826
WeiZhang1cc3f172021-06-03 19:02:04 -05007827 mHandler.sendMessage(mHandler.obtainMessage(
7828 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007829 }
7830
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007831 /** Returns the next Network provider ID. */
7832 public final int nextNetworkProviderId() {
7833 return mNextNetworkProviderId.getAndIncrement();
7834 }
7835
Erik Kline0c04b742016-07-07 16:50:58 +09007836 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007837 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007838 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007839 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007840 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007841 }
7842
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007843 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7844 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007845 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7846 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7847 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007848 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007849 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007850 return;
7851 }
7852
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007853 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7854 mNetworkProviderInfos.put(npi.messenger, npi);
7855 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007856 }
7857
7858 @Override
7859 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007860 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007861 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007862 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007863 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007864 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7865 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007866 }
7867
7868 @Override
7869 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007870 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007871 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007872 }
7873
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007874 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007875 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007876 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7877 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007878 Objects.requireNonNull(score);
7879 Objects.requireNonNull(caps);
7880 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007881 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007882 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007883 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7884 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007885 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7886 }
7887
Chalard Jeanbb902a52021-08-18 01:35:19 +09007888 private void updateOfferScore(final NetworkOffer offer) {
7889 final boolean yieldToBadWiFi =
7890 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7891 final NetworkOffer newOffer = new NetworkOffer(
7892 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7893 offer.caps, offer.callback, offer.providerId);
7894 if (offer.equals(newOffer)) return;
7895 handleRegisterNetworkOffer(newOffer);
7896 }
7897
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007898 @Override
7899 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007900 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007901 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7902 }
7903
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007904 private void handleUnregisterNetworkProvider(Messenger messenger) {
7905 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7906 if (npi == null) {
7907 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007908 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007909 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007910 // Unregister all the offers from this provider
7911 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7912 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007913 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007914 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7915 toRemove.add(noi);
7916 }
7917 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007918 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007919 handleUnregisterNetworkOffer(noi);
7920 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007921 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007922 }
7923
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007924 @Override
James Mattisf7027322020-12-13 16:28:14 -08007925 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007926 if (request.hasTransport(TRANSPORT_TEST)) {
7927 enforceNetworkFactoryOrTestNetworksPermission();
7928 } else {
7929 enforceNetworkFactoryPermission();
7930 }
James Mattisf7027322020-12-13 16:28:14 -08007931 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7932 if (nri != null) {
7933 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7934 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7935 mHandler.post(() -> handleReleaseNetworkRequest(
7936 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7937 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007938 }
7939
Paul Jensen1f567382015-02-13 14:18:39 -05007940 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7941 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007942 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007943 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007944 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007945 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007946 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007947
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007948 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007949 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007950 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007951
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007952 // UID ranges for users that are currently blocked by VPNs.
7953 // This array is accessed and iterated on multiple threads without holding locks, so its
7954 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7955 // (on the handler thread).
7956 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7957
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007958 // Must only be accessed on the handler thread
7959 @NonNull
7960 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7961
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007962 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007963 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007964
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007965 // Current OEM network preferences. This object must only be written to on the handler thread.
7966 // Since it is immutable and always non-null, other threads may read it if they only care
7967 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007968 @NonNull
7969 private OemNetworkPreferences mOemNetworkPreferences =
7970 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007971 // Current per-profile network preferences. This object follows the same threading rules as
7972 // the OEM network preferences above.
7973 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007974 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7975 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007976
lucaslin3ba7cc22022-12-19 02:35:33 +00007977 // Current VPN network preferences. This object follows the same threading rules as the OEM
7978 // network preferences above.
7979 @NonNull
7980 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7981 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7982
paulhu51f77dc2021-06-07 02:34:20 +00007983 // A set of UIDs that should use mobile data preferentially if available. This object follows
7984 // the same threading rules as the OEM network preferences above.
7985 @NonNull
7986 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7987
James Mattiscb1e0362021-04-06 17:07:42 -07007988 // OemNetworkPreferences activity String log entries.
7989 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7990 @NonNull
7991 private final LocalLog mOemNetworkPreferencesLogs =
7992 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7993
James Mattis02220e22021-03-13 19:27:21 -08007994 /**
7995 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7996 * @param packageName the package name to check existence of a mapping for.
7997 * @return true if a mapping exists, false otherwise
7998 */
7999 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8000 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8001 }
8002
James Mattise3ef1912020-12-20 11:09:58 -08008003 // The always-on request for an Internet-capable network that apps without a specific default
8004 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008005 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008006 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008007 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008008 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008009 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008010 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008011 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008012
James Mattisd31bdfa2020-12-23 16:37:26 -08008013 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8014 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8015 }
8016
8017 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008018 * Return the default network request currently tracking the given uid.
8019 * @param uid the uid to check.
8020 * @return the NetworkRequestInfo tracking the given uid.
8021 */
8022 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008023 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008024 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008025 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008026 // Checking the first request is sufficient as only multilayer requests will have more
8027 // than one request and for multilayer, all requests will track the same uids.
8028 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008029 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008030 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008031 highestPriorityNri = nri;
8032 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008033 }
8034 }
paulhuaa0743d2021-05-26 21:56:03 +08008035 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008036 }
8037
8038 /**
8039 * Get a copy of the network requests of the default request that is currently tracking the
8040 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008041 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8042 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008043 * @param requestorUid the uid to check the default for.
8044 * @param requestorPackageName the requestor's package name.
8045 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8046 */
8047 @NonNull
8048 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008049 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008050 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008051 getDefaultRequestTrackingUid(asUid).mRequests,
8052 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008053 }
8054
8055 /**
8056 * Copy the given nri's NetworkRequest collection.
8057 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008058 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8059 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008060 * @param requestorUid the uid to set on the copied collection.
8061 * @param requestorPackageName the package name to set on the copied collection.
8062 * @return the copied NetworkRequest collection.
8063 */
8064 @NonNull
8065 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008066 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8067 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008068 final List<NetworkRequest> requests = new ArrayList<>();
8069 for (final NetworkRequest nr : requestsToCopy) {
8070 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008071 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008072 nr.legacyType, nextNetworkRequestId(), nr.type));
8073 }
8074 return requests;
8075 }
8076
8077 @NonNull
8078 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008079 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8080 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008081 // These capabilities are for a TRACK_DEFAULT callback, so:
8082 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8083 // mDefaultRequest and a per-UID default request.
8084 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008085 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008086 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008087 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8088 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008089 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008090 restrictRequestUidsForCallerAndSetRequestorInfo(
8091 netCap, requestorUid, requestorPackageName);
8092 return netCap;
8093 }
8094
8095 /**
8096 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8097 * @param nr the network request to check for equality against.
8098 * @return the nri if one exists, null otherwise.
8099 */
8100 @Nullable
8101 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8102 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8103 if (nri.getNetworkRequestForCallback().equals(nr)) {
8104 return nri;
8105 }
8106 }
8107 return null;
8108 }
8109
8110 /**
8111 * Check if an nri is currently being managed by per-app default networking.
8112 * @param nri the nri to check.
8113 * @return true if this nri is currently being managed by per-app default networking.
8114 */
8115 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8116 // nri.mRequests.get(0) is only different from the original request filed in
8117 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8118 // functionality therefore if these two don't match, it means this particular nri is
8119 // currently being managed by a per-app default.
8120 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8121 }
8122
8123 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008124 * Determine if an nri is a managed default request that disallows default networking.
8125 * @param nri the request to evaluate
8126 * @return true if device-default networking is disallowed
8127 */
8128 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8129 // Check if this nri is a managed default that supports the default network at its
8130 // lowest priority request.
8131 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8132 final NetworkCapabilities lowestPriorityNetCap =
8133 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8134 return isPerAppDefaultRequest(nri)
8135 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8136 lowestPriorityNetCap));
8137 }
8138
Erik Kline05f2b402015-04-30 12:58:40 +09008139 // Request used to optionally keep mobile data active even when higher
8140 // priority networks like Wi-Fi are active.
8141 private final NetworkRequest mDefaultMobileDataRequest;
8142
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008143 // Request used to optionally keep wifi data active even when higher
8144 // priority networks like ethernet are active.
8145 private final NetworkRequest mDefaultWifiRequest;
8146
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008147 // Request used to optionally keep vehicle internal network always active
8148 private final NetworkRequest mDefaultVehicleRequest;
8149
James Mattisd31bdfa2020-12-23 16:37:26 -08008150 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8151 // network with no service. This NAI should never be matched against, nor should any public API
8152 // ever return the associated network. For this reason, this NAI is not in the list of available
8153 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8154 // default requests that don't support using the device default network which will ultimately
8155 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8156 @VisibleForTesting
8157 final NetworkAgentInfo mNoServiceNetwork;
8158
Chalard Jean5b409c72021-02-04 13:12:59 +09008159 // The NetworkAgentInfo currently satisfying the default request, if any.
8160 private NetworkAgentInfo getDefaultNetwork() {
8161 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008162 }
8163
James Mattis2516da32021-01-31 17:06:19 -08008164 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008165 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008166 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8167 // Currently, all network requests will have the same uids therefore checking the first
8168 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008169 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008170 if (null == uids) {
8171 continue;
8172 }
8173 for (final UidRange range : uids) {
8174 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008175 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008176 highestPriorityNri = nri;
8177 }
James Mattis2516da32021-01-31 17:06:19 -08008178 }
8179 }
8180 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008181 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008182 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008183 }
8184
Varun Ananddf569952019-02-06 10:13:38 -08008185 @Nullable
8186 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8187 return nai != null ? nai.network : null;
8188 }
8189
8190 private void ensureRunningOnConnectivityServiceThread() {
8191 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8192 throw new IllegalStateException(
8193 "Not running on ConnectivityService thread: "
8194 + Thread.currentThread().getName());
8195 }
8196 }
8197
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008198 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008199 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8200 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008201 }
8202
Chalard Jean29d06db2018-05-02 21:14:54 +09008203 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008204 * Returns whether local agents are supported on this device.
8205 *
8206 * Local agents are supported from U on TVs, and from V on all devices.
8207 */
8208 @VisibleForTesting
8209 public boolean areLocalAgentsSupported() {
8210 final PackageManager pm = mContext.getPackageManager();
8211 // Local agents are supported starting on U on TVs and on V on everything else.
8212 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8213 }
8214
8215 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008216 * Register a new agent with ConnectivityService to handle a network.
8217 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008218 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008219 * @param networkInfo the initial info associated with this network. It can be updated later :
8220 * see {@link #updateNetworkInfo}.
8221 * @param linkProperties the initial link properties of this network. They can be updated
8222 * later : see {@link #updateLinkProperties}.
8223 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008224 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008225 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008226 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008227 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008228 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008229 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008230 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008231 public Network registerNetworkAgent(INetworkAgent na,
8232 NetworkInfo networkInfo,
8233 LinkProperties linkProperties,
8234 NetworkCapabilities networkCapabilities,
8235 @NonNull NetworkScore initialScore,
8236 @Nullable LocalNetworkConfig localNetworkConfig,
8237 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008238 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008239 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8240 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8241 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008242 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008243 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008244 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008245 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008246 } else {
8247 enforceNetworkFactoryPermission();
8248 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008249 final boolean hasLocalCap =
8250 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8251 if (hasLocalCap && !areLocalAgentsSupported()) {
8252 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8253 throw new IllegalArgumentException("Local agents are not supported in this version");
8254 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008255 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8256 if (hasLocalCap != hasLocalNetworkConfig) {
8257 throw new IllegalArgumentException(null != localNetworkConfig
8258 ? "Only local network agents can have a LocalNetworkConfig"
8259 : "Local network agents must have a LocalNetworkConfig"
8260 );
8261 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008262
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008263 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008264 final long token = Binder.clearCallingIdentity();
8265 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008266 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008267 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8268 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008269 } finally {
8270 Binder.restoreCallingIdentity(token);
8271 }
8272 }
8273
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008274 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008275 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008276 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8277 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008278 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008279
Chalard Jeandbc46952022-02-02 00:14:18 +09008280 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8281 // and mutate them at any time.
8282 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8283 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8284 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008285 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008286
Chalard Jean366c5252022-01-25 18:27:53 +09008287 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008288 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008289 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8290 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008291 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008292 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008293 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8294 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8295 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008296
Chalard Jeandbc46952022-02-02 00:14:18 +09008297 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008298 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008299 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008300 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008301 mDeps.getNetworkStack().makeNetworkMonitor(
8302 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008303 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8304 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008305 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008306 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008307 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008308 }
8309
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008310 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008311 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008312 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008313 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008314 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008315 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8316 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8317 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008318
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008319 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008320
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008321 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008322 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008323 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008324 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008325
8326 try {
8327 networkMonitor.start();
8328 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008329 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008330 }
Chalard Jean366c5252022-01-25 18:27:53 +09008331
Chalard Jean1e4c2182023-10-06 18:45:53 +09008332 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008333 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008334 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008335 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008336 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008337 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008338 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008339 }
8340
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008341 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8342 @NonNull public final NetworkOffer offer;
8343
8344 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8345 this.offer = offer;
8346 }
8347
8348 @Override
8349 public void binderDied() {
8350 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8351 }
8352 }
8353
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008354 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8355 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8356 if (npi.providerId == providerId) return true;
8357 }
8358 return false;
8359 }
8360
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008361 /**
8362 * Register or update a network offer.
8363 * @param newOffer The new offer. If the callback member is the same as an existing
8364 * offer, it is an update of that offer.
8365 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008366 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008367 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8368 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008369 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008370 // This may actually happen if a provider updates its score or registers and then
8371 // immediately unregisters. The offer would still be in the handler queue, but the
8372 // provider would have been removed.
8373 if (DBG) log("Received offer from an unregistered provider");
8374 return;
8375 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008376 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8377 if (null != existingOffer) {
8378 handleUnregisterNetworkOffer(existingOffer);
8379 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008380 if (DBG) {
8381 // handleUnregisterNetworkOffer has already logged the old offer
8382 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8383 }
8384 } else {
8385 if (DBG) {
8386 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8387 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008388 }
8389 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8390 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008391 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008392 } catch (RemoteException e) {
8393 noi.binderDied();
8394 return;
8395 }
8396 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008397 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008398 }
8399
8400 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8401 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008402 if (DBG) {
8403 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8404 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008405
8406 // If the provider removes the offer and dies immediately afterwards this
8407 // function may be called twice in a row, but the array will no longer contain
8408 // the offer.
8409 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008410 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008411 }
8412
8413 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8414 @NonNull final INetworkOfferCallback callback) {
8415 ensureRunningOnConnectivityServiceThread();
8416 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008417 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008418 }
8419 return null;
8420 }
8421
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008422 /**
8423 * Called when receiving LinkProperties directly from a NetworkAgent.
8424 * Stores into |nai| any data coming from the agent that might also be written to the network's
8425 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8426 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008427 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008428 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008429 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8430 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008431 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008432 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008433 }
8434
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008435 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008436 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008437 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008438
Lorenzo Colittid523d142020-04-01 20:16:30 +09008439 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8440 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8441 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008442 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008443
Suprabh Shukla1e312032023-01-24 03:36:37 -08008444 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008445
8446 // update filtering rules, need to happen after the interface update so netd knows about the
8447 // new interface (the interface name -> index map becomes initialized)
8448 updateVpnFiltering(newLp, oldLp, networkAgent);
8449
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008450 updateMtu(newLp, oldLp);
8451 // TODO - figure out what to do for clat
8452// for (LinkProperties lp : newLp.getStackedLinks()) {
8453// updateMtu(lp, null);
8454// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008455 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008456 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008457 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8458 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008459
Erik Klineb9888902016-04-05 13:30:49 +09008460 updateRoutes(newLp, oldLp, netId);
8461 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008462 // Make sure LinkProperties represents the latest private DNS status.
8463 // This does not need to be done before updateDnses because the
8464 // LinkProperties are not the source of the private DNS configuration.
8465 // updateDnses will fetch the private DNS configuration from DnsManager.
8466 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008467
Chalard Jean5b409c72021-02-04 13:12:59 +09008468 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008469 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008470 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008471 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008472 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008473
8474 updateWakeOnLan(newLp);
8475
Hai Shalome58bdc62021-01-11 18:45:34 -08008476 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8477 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8478 // does, it needs to be merged here.
8479 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8480 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008481
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008482 // TODO - move this check to cover the whole function
8483 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008484 synchronized (networkAgent) {
8485 networkAgent.linkProperties = newLp;
8486 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008487 // Start or stop DNS64 detection and 464xlat according to network state.
8488 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008489 // Notify NSS when relevant events happened. Currently, NSS only cares about
8490 // interface changed to update clat interfaces accounting.
8491 final boolean interfacesChanged = oldLp == null
8492 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8493 if (interfacesChanged) {
8494 notifyIfacesChangedForNetworkStats();
8495 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008496 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8497 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008498 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008499 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008500
8501 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008502 }
8503
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008504 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8505 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8506 }
8507
Hai Shalome58bdc62021-01-11 18:45:34 -08008508 /**
8509 * @param naData captive portal data from NetworkAgent
8510 * @param apiData captive portal data from capport API
8511 */
8512 @Nullable
8513 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8514 CaptivePortalData apiData) {
8515 if (naData == null || apiData == null) {
8516 return naData == null ? apiData : naData;
8517 }
8518 final CaptivePortalData.Builder captivePortalBuilder =
8519 new CaptivePortalData.Builder(naData);
8520
8521 if (apiData.isCaptive()) {
8522 captivePortalBuilder.setCaptive(true);
8523 }
8524 if (apiData.isSessionExtendable()) {
8525 captivePortalBuilder.setSessionExtendable(true);
8526 }
8527 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8528 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8529 // otherwise data would be inconsistent. Prefer the capport API info if present,
8530 // as it can generally be refreshed more often.
8531 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8532 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8533 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8534 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8535 // No source has time / bytes remaining information: surface the newest refresh time
8536 // for other fields
8537 captivePortalBuilder.setRefreshTime(
8538 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8539 }
8540
Hai Shalom7c6ab402021-02-04 19:34:06 -08008541 // Prioritize the user portal URL from the network agent if the source is authenticated.
8542 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8543 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8544 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8545 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008546 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008547 // Prioritize the venue information URL from the network agent if the source is
8548 // authenticated.
8549 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8550 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8551 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8552 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008553 }
8554 return captivePortalBuilder.build();
8555 }
8556
Suprabh Shukla53e16392023-04-26 18:47:36 -07008557 @VisibleForTesting
8558 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008559 // This needs to be kept in sync and backwards compatible with the decoding logic in
8560 // NetdEventListenerService, which is non-mainline code.
8561 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8562 }
8563
Suprabh Shukla75642282023-04-25 23:15:43 -07008564 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8565 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8566 return true;
8567 }
8568 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8569 return true;
8570 }
8571 return false;
8572 }
8573
Suprabh Shukla1e312032023-01-24 03:36:37 -08008574 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008575 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008576 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008577 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008578 return;
8579 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008580
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008581 // Mask/mark of zero will not detect anything interesting.
8582 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008583 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008584 return;
8585 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008586
Suprabh Shukla1e312032023-01-24 03:36:37 -08008587 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008588 try {
8589 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008590 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008591 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008592 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008593 }
8594 } catch (Exception e) {
8595 loge("Exception modifying wakeup packet monitoring: " + e);
8596 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008597 }
8598
Junyu Lai970963e2022-10-25 15:46:47 +08008599 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008600 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008601 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008602 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008603 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008604 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008605 for (final String iface : interfaceDiff.added) {
8606 try {
8607 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008608 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008609 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008610 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008611 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008612 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008613 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008614 }
Paul Jensenbff73492014-04-28 10:33:11 -04008615 }
8616 }
Chalard Jean9589e722019-11-19 19:03:53 +09008617 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008618 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008619 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008620 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008621 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008622 } catch (Exception e) {
8623 loge("Exception removing interface: " + e);
8624 }
8625 }
8626 }
8627
Paul Jensene0fd4a82014-08-06 15:51:33 -04008628 /**
8629 * Have netd update routes from oldLp to newLp.
8630 * @return true if routes changed between oldLp and newLp
8631 */
Junyu Lai970963e2022-10-25 15:46:47 +08008632 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8633 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008634 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008635 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8636 new CompareOrUpdateResult<>(
8637 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008638 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008639 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008640
8641 // add routes before removing old in case it helps with continuous connectivity
8642
Chalard Jean9dd11612018-06-04 16:52:49 +09008643 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008644 for (RouteInfo route : routeDiff.added) {
8645 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008646 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008647 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008648 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008649 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008650 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008651 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008652 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008653 }
8654 }
8655 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008656 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008657 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008658 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008659 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008660 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008661 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008662 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008663 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008664 }
8665 }
8666
8667 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008668 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008669 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008670 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008671 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008672 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008673 }
8674 }
Tyler Weare4314862019-12-05 14:55:30 -08008675
8676 for (RouteInfo route : routeDiff.updated) {
8677 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8678 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008679 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008680 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008681 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008682 }
8683 }
8684 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8685 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008686 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008687
Junyu Lai970963e2022-10-25 15:46:47 +08008688 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8689 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008690 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8691 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008692 }
Erik Klineb9888902016-04-05 13:30:49 +09008693
Erik Kline31b4a9e2018-01-11 21:07:29 +09008694 if (DBG) {
8695 final Collection<InetAddress> dnses = newLp.getDnsServers();
8696 log("Setting DNS servers for network " + netId + " to " + dnses);
8697 }
Erik Klineb9888902016-04-05 13:30:49 +09008698 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008699 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008700 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008701 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008702 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008703 }
Erik Kline54e35c02017-04-07 15:29:29 +09008704 }
8705
Junyu Lai970963e2022-10-25 15:46:47 +08008706 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8707 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008708 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8709 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008710 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8711 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008712
8713 if (!wasFiltering && !needsFiltering) {
8714 // Nothing to do.
8715 return;
8716 }
8717
8718 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8719 // Nothing changed.
8720 return;
8721 }
8722
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008723 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008724 if (ranges == null || ranges.isEmpty()) {
8725 return;
8726 }
8727
Qingxi Libb8da982020-01-17 17:54:27 -08008728 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008729 // TODO: this create a window of opportunity for apps to receive traffic between the time
8730 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008731 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008732 // old rules are being removed.
8733 if (wasFiltering) {
8734 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8735 }
8736 if (needsFiltering) {
8737 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8738 }
8739 }
8740
Valentin Iftime9fa35092019-09-24 13:32:13 +02008741 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008742 if (mWolSupportedInterfaces == null) {
8743 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008744 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008745 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008746 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8747 }
8748
Luke Huangb913c812018-08-24 20:33:16 +08008749 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008750 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008751 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008752 }
8753 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008754 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008755 }
Luke Huangb913c812018-08-24 20:33:16 +08008756 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008757 }
8758
Chalard Jean62edfd82019-12-02 18:39:29 +09008759 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8760 @NonNull final NetworkCapabilities newNc) {
8761 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8762 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008763 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008764 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008765 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008766 } catch (RemoteException | ServiceSpecificException e) {
8767 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008768 }
8769 }
8770 }
8771
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008772 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008773 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008774 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008775 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008776 underlyingNetworks = underlyingNetworksOrDefault(
8777 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008778 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008779 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8780 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008781 // metered if any underlying is metered, or originally declared metered by the agent.
8782 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008783 boolean roaming = false; // roaming if any underlying is roaming
8784 boolean congested = false; // congested if any underlying is congested
8785 boolean suspended = true; // suspended if all underlying are suspended
8786
8787 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008788 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008789 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008790 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008791 for (Network underlyingNetwork : underlyingNetworks) {
8792 final NetworkAgentInfo underlying =
8793 getNetworkAgentInfoForNetwork(underlyingNetwork);
8794 if (underlying == null) continue;
8795
8796 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8797 hadUnderlyingNetworks = true;
8798 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008799 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008800 }
8801
8802 // Merge capabilities of this underlying network. For bandwidth, assume the
8803 // worst case.
8804 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8805 underlyingCaps.getLinkDownstreamBandwidthKbps());
8806 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8807 underlyingCaps.getLinkUpstreamBandwidthKbps());
8808 // If this underlying network is metered, the VPN is metered (it may cost money
8809 // to send packets on this network).
8810 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8811 // If this underlying network is roaming, the VPN is roaming (the billing structure
8812 // is different than the usual, local one).
8813 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8814 // If this underlying network is congested, the VPN is congested (the current
8815 // condition of the network affects the performance of this network).
8816 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8817 // If this network is not suspended, the VPN is not suspended (the VPN
8818 // is able to transfer some data).
8819 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008820 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008821 }
8822 }
8823 if (!hadUnderlyingNetworks) {
8824 // No idea what the underlying networks are; assume reasonable defaults
8825 metered = true;
8826 roaming = false;
8827 congested = false;
8828 suspended = false;
8829 }
8830
Chalard Jean1d420b32022-10-12 16:39:37 +09008831 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008832 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8833 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8834 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8835 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8836 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8837 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008838 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008839 }
8840
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008841 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008842 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8843 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8844 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008845 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008846 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008847 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008848 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008849 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8850 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008851 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008852 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008853 if (nai.everConnected()
8854 && !nai.isVPN()
8855 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008856 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008857 // does not cause any request (that is not a listen) currently matching that agent to
8858 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008859 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008860 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008861 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008862 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008863 }
8864
Paul Jensen53f08952015-06-16 14:27:36 -04008865 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008866 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008867 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008868 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008869 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008870 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008871 }
Chalard Jean254bd162022-08-25 13:04:51 +09008872 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008873 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008874 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008875 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008876 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008877 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008878 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008879 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008880 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008881 }
Chalard Jean254bd162022-08-25 13:04:51 +09008882 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008883 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8884 } else {
8885 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8886 }
lucasline117e2e2019-10-22 18:27:33 +08008887 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008888
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008889 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008890 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8891 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008892 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008893 }
8894
Lorenzo Colittibd079452021-07-02 11:47:57 +09008895 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008896 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008897 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008898 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008899 }
8900
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008901 return newNc;
8902 }
8903
Lorenzo Colitti44840702021-01-11 22:27:57 +09008904 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8905 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8906 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8907 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8908 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8909 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8910 if (prevSuspended != suspended) {
8911 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8912 // onResumed have been removed.
8913 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8914 : ConnectivityManager.CALLBACK_RESUMED);
8915 }
8916 if (prevSuspended != suspended || prevRoaming != roaming) {
8917 // updateNetworkInfo will mix in the suspended info from the capabilities and
8918 // take appropriate action for the network having possibly changed state.
8919 updateNetworkInfo(nai, nai.networkInfo);
8920 }
8921 }
8922
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008923 /**
8924 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8925 *
8926 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8927 * capabilities we manage and store in {@code nai}, such as validated status and captive
8928 * portal status)
8929 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8930 * potentially triggers rematches.
8931 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8932 * change.)
8933 *
8934 * @param oldScore score of the network before any of the changes that prompted us
8935 * to call this function.
8936 * @param nai the network having its capabilities updated.
8937 * @param nc the new network capabilities.
8938 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008939 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008940 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008941 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008942 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008943 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8944 if (null != differences) {
8945 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8946 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008947 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008948 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008949
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008950 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008951 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008952 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008953
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008954 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008955 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8956 // the change we're processing can't affect any requests, it can only affect the listens
8957 // on this network. We might have been called by rematchNetworkAndRequests when a
8958 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008959 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008960 } else {
8961 // If the requestable capabilities have changed or the score changed, we can't have been
8962 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008963 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008964 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008965 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008966 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008967
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008968 final boolean oldMetered = prevNc.isMetered();
8969 final boolean newMetered = newNc.isMetered();
8970 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008971
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008972 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008973 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8974 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008975 }
junyulaif2c67e42018-08-07 19:50:45 +08008976
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008977 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8978 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008979
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008980 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008981 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008982 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008983 }
8984
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008985 // This network might have been underlying another network. Propagate its capabilities.
8986 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008987
Ken Chen5a35cf92023-10-07 07:54:22 +08008988 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08008989 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08008990 }
lucaslin53e8a262021-06-08 01:43:59 +08008991
8992 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008993 }
8994
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008995 /** Convenience method to update the capabilities for a given network. */
8996 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008997 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008998 }
8999
Chalard Jean1e4c2182023-10-06 18:45:53 +09009000 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009001 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009002 @Nullable final LocalNetworkConfig oldConfig,
9003 @NonNull final LocalNetworkConfig newConfig) {
9004 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009005 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9006 return;
9007 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009008
Chalard Jean4fe23392023-10-17 23:02:27 +09009009 if (VDBG) {
9010 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9011 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009012 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
9013 // TODO : apply the diff for multicast routing.
9014 configBuilder.setUpstreamMulticastRoutingConfig(
9015 newConfig.getUpstreamMulticastRoutingConfig());
9016 configBuilder.setDownstreamMulticastRoutingConfig(
9017 newConfig.getDownstreamMulticastRoutingConfig());
9018
9019 final NetworkRequest oldRequest =
9020 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9021 final NetworkCapabilities oldCaps =
9022 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9023 final NetworkRequestInfo oldNri =
9024 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9025 final NetworkAgentInfo oldSatisfier =
9026 null == oldNri ? null : oldNri.getSatisfier();
9027 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9028 final NetworkCapabilities newCaps =
9029 (null == newRequest) ? null : newRequest.networkCapabilities;
9030 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9031 if (null != oldRequest && requestUpdated) {
9032 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9033 if (null == newRequest && null != oldSatisfier) {
9034 // If there is an old satisfier, but no new request, then remove the old upstream.
9035 removeLocalNetworkUpstream(nai, oldSatisfier);
9036 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009037 // When there is a new request, the rematch sees the new request and sends the
9038 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9039 // But here there is no new request, so the rematch won't see anything. Send
9040 // callbacks to apps now to tell them about the loss of upstream.
9041 notifyNetworkCallbacks(nai,
9042 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009043 return;
9044 }
9045 }
9046 if (null != newRequest && requestUpdated) {
9047 // File the new request if :
9048 // - it has changed (requestUpdated), or
9049 // - it's the first time this local info (null == oldConfig)
9050 // is updated and the request has not been filed yet.
9051 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9052 // upstream (the best) but never request it to be brought up.
9053 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9054 nextNetworkRequestId(), LISTEN_FOR_BEST);
9055 configBuilder.setUpstreamSelector(nr);
9056 final NetworkRequestInfo nri = new NetworkRequestInfo(
9057 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9058 0 /* callbackFlags */, null /* attributionTag */);
9059 if (null != oldSatisfier) {
9060 // Set the old satisfier in the new NRI so that the rematch will see any changes
9061 nri.setSatisfier(oldSatisfier, nr);
9062 }
9063 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009064 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9065 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9066 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009067 handleRegisterNetworkRequest(nri);
9068 } else {
9069 configBuilder.setUpstreamSelector(oldRequest);
9070 nai.localNetworkConfig = configBuilder.build();
9071 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009072 }
9073
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009074 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009075 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009076 *
9077 * Ingress interface filtering enforces that all apps under the given network can only receive
9078 * packets from the network's interface (and loopback). This is important for VPNs because
9079 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9080 * non-VPN interfaces.
9081 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009082 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009083 * 1. the network is an app VPN (not legacy VPN)
9084 * 2. the VPN does not allow bypass
9085 * 3. the VPN is fully-routed
9086 * 4. the VPN interface is non-null
9087 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009088 * @see INetd#firewallAddUidInterfaceRules
9089 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009090 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009091 @Nullable
9092 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009093 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009094 if (nc == null || lp == null) return null;
9095 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009096 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009097 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009098 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009099 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009100 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009101 && !lp.hasExcludeRoute()) {
9102 return lp.getInterfaceName();
9103 }
9104 return null;
9105 }
9106
9107 /**
9108 * Returns whether we need to set interface filtering rule or not
9109 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009110 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009111 String isolationIface) {
9112 // Allow rules are always needed if VPN isolation is enabled.
9113 if (isolationIface != null) return true;
9114
9115 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9116 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9117 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009118 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009119 }
9120
Chiachang Wang28afaff2020-12-10 22:24:47 +08009121 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9122 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9123 int index = 0;
9124 for (UidRange range : ranges) {
9125 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9126 index++;
9127 }
9128 return stableRanges;
9129 }
9130
Chalard Jeane6c95272022-01-25 21:04:21 +09009131 private static UidRangeParcel[] intsToUidRangeStableParcels(
9132 final @NonNull ArraySet<Integer> uids) {
9133 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9134 int index = 0;
9135 for (int uid : uids) {
9136 stableRanges[index] = new UidRangeParcel(uid, uid);
9137 index++;
9138 }
9139 return stableRanges;
9140 }
9141
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009142 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9143 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9144 for (int i = 0; i < ranges.length; i++) {
9145 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9146 }
9147 return stableRanges;
9148 }
9149
Motomu Utsumi93a22182023-03-16 17:04:21 +09009150 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009151 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009152 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9153 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009154 if (mDeps.isAtLeastU()) {
9155 final Set<Integer> exemptUidSet = new ArraySet<>();
9156 for (final int uid: exemptUids) {
9157 exemptUidSet.add(uid);
9158 }
9159 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9160 } else {
9161 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9162 }
Ken Chen5e65a852020-12-24 12:59:10 +08009163 } catch (Exception e) {
9164 loge("Exception in socket destroy: ", e);
9165 }
9166 }
9167 }
9168
paulhuaa0743d2021-05-26 21:56:03 +08009169 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009170 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009171 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9172 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9173 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009174 exemptUids[0] = VPN_UID;
9175 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009176 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9177
Motomu Utsumi6345e462023-03-13 13:24:50 +09009178 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009179 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009180 try {
9181 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009182 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009183 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009184 } else {
paulhu0e79d952021-06-09 16:11:35 +08009185 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009186 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009187 }
9188 } catch (Exception e) {
9189 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9190 " on netId " + nai.network.netId + ". " + e);
9191 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009192 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009193 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009194 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009195
lucaslin53e8a262021-06-08 01:43:59 +08009196 private boolean isProxySetOnAnyDefaultNetwork() {
9197 ensureRunningOnConnectivityServiceThread();
9198 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9199 final NetworkAgentInfo nai = nri.getSatisfier();
9200 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9201 return true;
9202 }
9203 }
9204 return false;
9205 }
9206
9207 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9208 NetworkCapabilities newNc) {
9209 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9210 // the proxy might be changed since the default network satisfied by the apps might also
9211 // changed.
9212 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9213 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009214 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9215 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009216 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009217 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9218 mProxyTracker.sendProxyBroadcast();
9219 }
9220 }
9221
Chalard Jeane6c95272022-01-25 21:04:21 +09009222 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9223 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009224 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9225 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009226 if (null == prevRanges) prevRanges = new ArraySet<>();
9227 if (null == newRanges) newRanges = new ArraySet<>();
9228 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9229
9230 prevRanges.removeAll(newRanges);
9231 newRanges.removeAll(prevRangesCopy);
9232
9233 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009234 // When updating the VPN uid routing rules, add the new range first then remove the old
9235 // range. If old range were removed first, there would be a window between the old
9236 // range being removed and the new range being added, during which UIDs contained
9237 // in both ranges are not subject to any VPN routing rules. Adding new range before
9238 // removing old range works because, unlike the filtering rules below, it's possible to
9239 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009240 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9241 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9242 // [1-5] & [1-2],[4-5] == [3]
9243 // Then we can do:
9244 // maybeCloseSockets([3])
9245 // mNetd.networkAddUidRanges([1-2],[4-5])
9246 // mNetd.networkRemoveUidRanges([1-5])
9247 // maybeCloseSockets([3])
9248 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9249 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009250 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009251 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009252 }
9253 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009254 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009255 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009256 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9257 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009258 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9259 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009260 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009261 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009262 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9263 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9264 // were added first and then newRanges got removed later, there would be only one uid
9265 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9266 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9267 // Note that this is in contrast with the (more robust) update of VPN routing rules
9268 // above, where the addition of new ranges happens before the removal of old ranges.
9269 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9270 // to be removed will never overlap with the new range to be added.
9271 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009272 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9273 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009274 }
9275 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009276 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009277 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009278 } catch (Exception e) {
9279 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009280 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009281 }
9282 }
9283
Chalard Jeande665262022-02-25 16:12:12 +09009284 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009285 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9286 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009287 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9288 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009289 if (prevEmpty && newEmpty) return;
9290
9291 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009292 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009293 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009294 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009295
9296 if (prevUids.equals(newUids)) return;
9297
9298 // This implementation is very simple and vastly faster for sets of Integers than
9299 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9300 // a key computed from the value and has storage for that.
9301 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9302 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9303 toRemove.removeAll(newUids);
9304 toAdd.removeAll(prevUids);
9305
9306 try {
9307 if (!toAdd.isEmpty()) {
9308 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9309 nai.network.netId,
9310 intsToUidRangeStableParcels(toAdd),
9311 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9312 }
9313 if (!toRemove.isEmpty()) {
9314 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9315 nai.network.netId,
9316 intsToUidRangeStableParcels(toRemove),
9317 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9318 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009319 } catch (ServiceSpecificException e) {
9320 // Has the interface disappeared since the network was built ?
9321 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009322 } catch (RemoteException e) {
9323 // Netd died. This usually causes a runtime restart anyway.
9324 }
9325 }
9326
Junyu Lai2ed7d412022-10-07 16:52:21 +08009327 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9328 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009329 ensureRunningOnConnectivityServiceThread();
9330
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009331 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009332 // Ignore updates for disconnected networks
9333 return;
9334 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009335 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009336 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009337 + "; created=" + nai.getCreatedTime()
9338 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009339 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009340 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9341 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009342 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009343 }
9344
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009345 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9346 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009347 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009348 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009349 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009350 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9351 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9352 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009353 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9354 // need to be sent as a separate extra.
9355 final NetworkRequest req = nri.isMultilayerRequest()
9356 ? nri.getActiveRequest()
9357 // Non-multilayer listen requests do not have an active request
9358 : nri.mRequests.get(0);
9359 if (req == null) {
9360 Log.wtf(TAG, "No request in NRI " + nri);
9361 }
9362 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009363 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009364 sendIntent(nri.mPendingIntent, intent);
9365 }
9366 // else not handled
9367 }
9368
Michael Groover73f69482023-01-27 11:01:25 -06009369 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9370 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009371 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9372 mPendingIntentWakeLock.acquire();
9373 try {
9374 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009375 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009376 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009377 // Explicitly disallow the receiver from starting activities, to prevent apps from
9378 // utilizing the PendingIntent as a backdoor to do this.
9379 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9380 }
9381 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9382 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009383 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009384 } catch (PendingIntent.CanceledException e) {
9385 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9386 mPendingIntentWakeLock.release();
9387 releasePendingNetworkRequest(pendingIntent);
9388 }
9389 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9390 }
9391
9392 @Override
9393 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9394 String resultData, Bundle resultExtras) {
9395 if (DBG) log("Finished sending " + pendingIntent);
9396 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009397 // Release with a delay so the receiving client has an opportunity to put in its
9398 // own request.
9399 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009400 }
9401
Chalard Jean22350c92023-10-07 19:21:45 +09009402 @Nullable
9403 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9404 if (!nai.isLocalNetwork()) return null;
9405 final Network upstream;
9406 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9407 if (null == selector) {
9408 upstream = null;
9409 } else {
9410 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9411 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9412 upstream = (null == satisfier) ? null : satisfier.network;
9413 }
9414 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9415 }
9416
Chalard Jean46bfbf02022-02-02 00:56:25 +09009417 // networkAgent is only allowed to be null if notificationType is
9418 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9419 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009420 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009421 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009422 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009423 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009424 // Default request has no msgr. Also prevents callbacks from being invoked for
9425 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9426 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9427 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009428 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009429 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009430 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009431 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009432 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009433 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009434 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009435 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9436 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009437 }
Roshan Pius951c0032020-12-22 15:10:42 -08009438 final boolean includeLocationSensitiveInfo =
9439 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009440 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009441 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009442 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009443 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009444 networkCapabilitiesRestrictedForCallerPermissions(
9445 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9446 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009447 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009448 nri.mCallingAttributionTag);
9449 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009450 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9451 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009452 // The local network info is often null, so can't use the static putParcelable
9453 // method here.
9454 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9455 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009456 // For this notification, arg1 contains the blocked status.
9457 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009458 break;
9459 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009460 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009461 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009462 break;
9463 }
9464 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009465 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009466 final NetworkCapabilities netCap =
9467 networkCapabilitiesRestrictedForCallerPermissions(
9468 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9469 putParcelable(
9470 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009471 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009472 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009473 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009474 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009475 break;
9476 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009477 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009478 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9479 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009480 break;
9481 }
junyulaif2c67e42018-08-07 19:50:45 +08009482 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009483 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009484 msg.arg1 = arg1;
9485 break;
9486 }
Chalard Jean22350c92023-10-07 19:21:45 +09009487 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9488 if (!networkAgent.isLocalNetwork()) {
9489 Log.wtf(TAG, "Callback for local info for a non-local network");
9490 return;
9491 }
9492 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9493 break;
9494 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009495 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009496 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009497 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009498 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009499 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009500 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009501 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009502 }
James Mattis45d81842021-01-10 14:24:24 -08009503 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009504 } catch (RemoteException e) {
9505 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009506 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009507 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009508 }
9509
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009510 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9511 bundle.putParcelable(t.getClass().getSimpleName(), t);
9512 }
9513
Chalard Jean0702f982021-09-16 21:50:07 +09009514 /**
9515 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9516 *
9517 * When a request should be assigned to a new network, it is normally lingered to give
9518 * time for apps to gracefully migrate their connections. When both networks are on the same
9519 * radio, but that radio can't do time-sharing efficiently, this may end up being
9520 * counter-productive because any traffic on the old network may drastically reduce the
9521 * performance of the new network.
9522 * The stack supports a configuration to let modem vendors state that their radio can't
9523 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9524 * from one cell network to another can't be done gracefully.
9525 *
9526 * @param oldNai the old network serving the request
9527 * @param newNai the new network serving the request
9528 * @return whether the switch can be graceful
9529 */
9530 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9531 @NonNull final NetworkAgentInfo newSatisfier) {
9532 if (mCellularRadioTimesharingCapable) return true;
9533 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9534 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9535 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9536 }
9537
Paul Jensenaf94b982014-09-30 15:37:41 -04009538 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009539 if (nai.numRequestNetworkRequests() != 0) {
9540 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9541 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009542 // Ignore listening and track default requests.
9543 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009544 loge("Dead network still had at least " + nr);
9545 break;
9546 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009547 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009548 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009549 }
9550
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009551 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9552 if (oldNetwork == null) {
9553 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9554 return;
9555 }
Chalard Jean49707572019-12-10 21:07:02 +09009556 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009557
9558 // If we get here it means that the last linger timeout for this network expired. So there
9559 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009560 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009561
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009562 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009563 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009564 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009565 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009566 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009567 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009568 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009569 }
9570
James Mattise3ef1912020-12-20 11:09:58 -08009571 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9572 boolean isDefaultChanged = false;
9573 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9574 final NetworkReassignment.RequestReassignment reassignment =
9575 changes.getReassignment(defaultRequestInfo);
9576 if (null == reassignment) {
9577 continue;
9578 }
9579 // reassignment only contains those instances where the satisfying network changed.
9580 isDefaultChanged = true;
9581 // Notify system services of the new default.
9582 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9583 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009584
James Mattise3ef1912020-12-20 11:09:58 -08009585 if (isDefaultChanged) {
9586 // Hold a wakelock for a short time to help apps in migrating to a new default.
9587 scheduleReleaseNetworkTransitionWakelock();
9588 }
9589 }
9590
Aaron Huang9fe47be2021-06-08 13:11:45 +08009591 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9592 if (null == oldDefaultNetwork) return;
9593 // The network stopped being the default. If it was using a PAC proxy, then the
9594 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9595 // to the local proxy server, which would forward them over the newly default network.
9596 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9597 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9598 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9599 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9600 }
9601
James Mattise3ef1912020-12-20 11:09:58 -08009602 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9603 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9604 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9605 if (DBG) {
9606 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9607 }
Chalard Jean8e382112019-12-03 20:45:30 +09009608
James Mattisd31bdfa2020-12-23 16:37:26 -08009609 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9610 if (newDefaultNetwork != null) {
9611 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009612 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009613
James Mattisd31bdfa2020-12-23 16:37:26 -08009614 // Set an app level managed default and return since further processing only applies to the
9615 // default network.
9616 if (mDefaultRequest != nri) {
9617 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9618 return;
9619 }
9620
9621 makeDefaultNetwork(newDefaultNetwork);
9622
James Mattise3ef1912020-12-20 11:09:58 -08009623 if (oldDefaultNetwork != null) {
9624 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9625 }
9626 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009627 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009628 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009629 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009630 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009631 updateTcpBufferSizes(null != newDefaultNetwork
9632 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009633 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009634 }
9635
James Mattisd31bdfa2020-12-23 16:37:26 -08009636 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9637 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9638 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9639 try {
9640 if (VDBG) {
9641 log("Setting default network for " + nri
9642 + " using UIDs " + nri.getUids()
9643 + " with old network " + (oldDefaultNetwork != null
9644 ? oldDefaultNetwork.network().getNetId() : "null")
9645 + " and new network " + (newDefaultNetwork != null
9646 ? newDefaultNetwork.network().getNetId() : "null"));
9647 }
9648 if (nri.getUids().isEmpty()) {
9649 throw new IllegalStateException("makeDefaultForApps called without specifying"
9650 + " any applications to set as the default." + nri);
9651 }
9652 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009653 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009654 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009655 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009656 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009657 }
9658 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009659 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009660 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009661 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009662 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009663 }
9664 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009665 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009666 }
9667 }
9668
Junyu Lai35665cc2022-12-19 17:37:48 +08009669 /**
9670 * Collect restricted uid ranges for the given network and UserHandle, these uids
9671 * are not restricted for matched enterprise networks but being restricted for non-matched
9672 * enterprise networks and non-enterprise networks.
9673 */
9674 @NonNull
9675 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9676 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9677 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9678 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9679 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9680
9681 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9682 // The NC is built from a `ProfileNetworkPreference` which has only one
9683 // enterprise ID, so it's guaranteed to have exactly one.
9684 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9685 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9686 continue;
9687 }
9688 }
9689
9690 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9691 pref.capabilities.getUidRanges())) {
9692 throw new IllegalArgumentException(
9693 "Overlapping uid range in preference: " + pref);
9694 }
9695 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9696 }
9697 return restrictedUidRanges;
9698 }
9699
9700 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009701 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009702 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009703
Junyu Lai35665cc2022-12-19 17:37:48 +08009704 ensureRunningOnConnectivityServiceThread();
9705 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9706 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9707 .getUserHandles(true /* excludeDying */);
9708 if (users.isEmpty()) {
9709 throw new IllegalStateException("No user is available");
9710 }
9711
9712 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9713 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9714 for (final UserHandle user : users) {
9715 final ArraySet<UidRange> restrictedUidRanges =
9716 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9717 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9718 UidRange.createForUser(user), restrictedUidRanges));
9719 }
9720
9721 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9722 configs.add(new NativeUidRangeConfig(
9723 nai.network.netId, rangesParcel, 0 /* subPriority */));
9724 }
9725
9726 // The netd API replaces the previous configs with the current configs.
9727 // Thus, for network disconnection or preference removal, no need to
9728 // unset previous config. Instead, collecting all currently needed
9729 // configs and issue to netd.
9730 try {
9731 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9732 } catch (ServiceSpecificException e) {
9733 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009734 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009735 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009736 // Netd died. This will cause a runtime restart anyway.
9737 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009738 }
9739 }
9740
James Mattisd31bdfa2020-12-23 16:37:26 -08009741 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9742 try {
9743 if (null != newDefaultNetwork) {
9744 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9745 } else {
9746 mNetd.networkClearDefault();
9747 }
9748 } catch (RemoteException | ServiceSpecificException e) {
9749 loge("Exception setting default network :" + e);
9750 }
9751 }
9752
Chalard Jean05cbe972019-12-09 11:50:38 +09009753 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009754 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009755 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009756 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009757 processNewlySatisfiedListenRequests(nai);
9758 }
9759
9760 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009761 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9762 if (nri.isMultilayerRequest()) {
9763 continue;
9764 }
9765 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009766 if (!nr.isListen()) continue;
9767 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009768 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009769 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9770 }
9771 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009772 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009773
Chalard Jeancd397a22019-11-22 22:33:33 +09009774 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009775 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9776 if (nri.isMultilayerRequest()) {
9777 continue;
9778 }
9779 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009780 if (!nr.isListen()) continue;
9781 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9782 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009783 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009784 }
9785 }
9786 }
9787
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009788 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009789 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009790 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009791 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009792 @Nullable public final NetworkRequest mOldNetworkRequest;
9793 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009794 @Nullable public final NetworkAgentInfo mOldNetwork;
9795 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009796 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009797 @Nullable final NetworkRequest oldNetworkRequest,
9798 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009799 @Nullable final NetworkAgentInfo oldNetwork,
9800 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009801 mNetworkRequestInfo = networkRequestInfo;
9802 mOldNetworkRequest = oldNetworkRequest;
9803 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009804 mOldNetwork = oldNetwork;
9805 mNewNetwork = newNetwork;
9806 }
Chalard Jean49707572019-12-10 21:07:02 +09009807
9808 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009809 final NetworkRequest requestToShow = null != mNewNetworkRequest
9810 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9811 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009812 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9813 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009814 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009815 }
9816
Chalard Jean46a62372019-12-10 21:25:24 +09009817 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009818
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009819 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009820 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009821 }
9822
9823 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009824 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009825 // The code is never supposed to add two reassignments of the same request. Make
9826 // sure this stays true, but without imposing this expensive check on all
9827 // reassignments on all user devices.
9828 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009829 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009830 throw new IllegalStateException("Trying to reassign ["
9831 + reassignment + "] but already have ["
9832 + existing + "]");
9833 }
9834 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009835 }
Chalard Jean46a62372019-12-10 21:25:24 +09009836 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009837 }
9838
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009839 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009840 // the passed request.
9841 @Nullable
9842 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009843 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009844 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009845 }
9846 return null;
9847 }
Chalard Jean49707572019-12-10 21:07:02 +09009848
9849 public String toString() {
9850 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9851 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009852 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009853 for (final RequestReassignment rr : getRequestReassignments()) {
9854 sj.add(rr.toString());
9855 }
9856 return sj.toString();
9857 }
9858
9859 public String debugString() {
9860 final StringBuilder sb = new StringBuilder();
9861 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009862 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009863 for (final RequestReassignment rr : getRequestReassignments()) {
9864 sb.append("\n ").append(rr);
9865 }
9866 return sb.append("\n").toString();
9867 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009868 }
9869
Chalard Jean24344d72019-12-04 13:32:31 +09009870 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009871 @Nullable final NetworkRequest previousRequest,
9872 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009873 @Nullable final NetworkAgentInfo previousSatisfier,
9874 @Nullable final NetworkAgentInfo newSatisfier,
9875 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009876 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009877 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009878 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009879 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009880 log(" accepting network in place of " + previousSatisfier.toShortString()
9881 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009882 }
James Mattisa076c532020-12-02 14:12:41 -08009883 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009884 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009885 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009886 // If this network switch can't be supported gracefully, the request is not
9887 // lingered. This allows letting go of the network sooner to reclaim some
9888 // performance on the new network, since the radio can't do both at the same
9889 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009890 //
9891 // Also don't linger the request if the old network has been destroyed.
9892 // A destroyed network does not provide actual network connectivity, so
9893 // lingering it is not useful. In particular this ensures that a destroyed
9894 // network is outscored by its replacement,
9895 // then it is torn down immediately instead of being lingered, and any apps that
9896 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009897 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9898 }
Chalard Jean24344d72019-12-04 13:32:31 +09009899 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +09009900 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009901 }
junyulai0ac374f2020-12-14 18:41:52 +08009902
9903 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9904 // and immediately satisfies a request then remove the timer. This will happen for
9905 // all networks except in the case of an underlying network for a VCN.
9906 if (newSatisfier.isNascent()) {
9907 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009908 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009909 }
9910
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009911 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009912 newSatisfier.unlingerRequest(newRequest.requestId);
9913 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009914 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009915 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009916 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009917 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009918 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009919 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009920 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009921 }
James Mattisa076c532020-12-02 14:12:41 -08009922 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009923 }
James Mattisa076c532020-12-02 14:12:41 -08009924 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009925 }
9926
James Mattisa076c532020-12-02 14:12:41 -08009927 /**
9928 * This function is triggered when something can affect what network should satisfy what
9929 * request, and it computes the network reassignment from the passed collection of requests to
9930 * network match to the one that the system should now have. That data is encoded in an
9931 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9932 * satisfier.
9933 *
9934 * After the reassignment is computed, it is applied to the state objects.
9935 *
9936 * @param networkRequests the nri objects to evaluate for possible network reassignment
9937 * @return NetworkReassignment listing of proposed network assignment changes
9938 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009939 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009940 private NetworkReassignment computeNetworkReassignment(
9941 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009942 final NetworkReassignment changes = new NetworkReassignment();
9943
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009944 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009945 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009946 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009947 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009948 }
Chalard Jean857a1712019-12-10 21:08:07 +09009949
James Mattisa076c532020-12-02 14:12:41 -08009950 for (final NetworkRequestInfo nri : networkRequests) {
9951 // Non-multilayer listen requests can be ignored.
9952 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9953 continue;
9954 }
9955 NetworkAgentInfo bestNetwork = null;
9956 NetworkRequest bestRequest = null;
9957 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009958 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009959 // Stop evaluating as the highest possible priority request is satisfied.
9960 if (null != bestNetwork) {
9961 bestRequest = req;
9962 break;
9963 }
9964 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009965 if (null == bestNetwork && isDefaultBlocked(nri)) {
9966 // Remove default networking if disallowed for managed default requests.
9967 bestNetwork = mNoServiceNetwork;
9968 }
9969 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009970 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009971 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009972 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009973 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009974 }
9975 return changes;
9976 }
9977
James Mattisa076c532020-12-02 14:12:41 -08009978 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9979 return new HashSet<>(mNetworkRequests.values());
9980 }
9981
Paul Jensenc88b39b2015-06-16 14:27:36 -04009982 /**
James Mattisa076c532020-12-02 14:12:41 -08009983 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009984 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009985 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009986 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009987 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9988 }
9989
9990 /**
9991 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9992 * being disconnected.
9993 */
9994 private void rematchNetworksAndRequests(
9995 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9996 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009997 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009998 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009999 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010000 final long computed = SystemClock.elapsedRealtime();
10001 applyNetworkReassignment(changes, start);
10002 final long applied = SystemClock.elapsedRealtime();
10003 issueNetworkNeeds();
10004 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010005 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010006 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10007 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010008 log(changes.debugString());
10009 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010010 // Shorter form, only one line of log
10011 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10012 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010013 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010014 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010015
Chalard Jean1e4c2182023-10-06 18:45:53 +090010016 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10017 @Nullable final NetworkAgentInfo nai2) {
10018 if (null == nai1) return null == nai2;
10019 if (null == nai2) return false;
10020 return nai1.linkProperties.getInterfaceName()
10021 .equals(nai2.linkProperties.getInterfaceName());
10022 }
10023
Chalard Jeand7f762d2019-12-10 19:01:29 +090010024 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010025 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010026 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010027
10028 // Since most of the time there are only 0 or 1 background networks, it would probably
10029 // be more efficient to just use an ArrayList here. TODO : measure performance
10030 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10031 for (final NetworkAgentInfo nai : nais) {
10032 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10033 }
10034
Chalard Jeand7f762d2019-12-10 19:01:29 +090010035 // First, update the lists of satisfied requests in the network agents. This is necessary
10036 // because some code later depends on this state to be correct, most prominently computing
10037 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010038 for (final NetworkReassignment.RequestReassignment event :
10039 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010040 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10041 event.mOldNetworkRequest, event.mNewNetworkRequest,
10042 event.mOldNetwork, event.mNewNetwork,
10043 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010044 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010045
James Mattise3ef1912020-12-20 11:09:58 -080010046 // Process default network changes if applicable.
10047 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010048
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010049 // Notify requested networks are available after the default net is switched, but
10050 // before LegacyTypeTracker sends legacy broadcasts
10051 for (final NetworkReassignment.RequestReassignment event :
10052 changes.getRequestReassignments()) {
10053 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010054 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010055 } else {
James Mattisa076c532020-12-02 14:12:41 -080010056 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010057 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010058 }
10059 }
10060
junyulai0ac374f2020-12-14 18:41:52 +080010061 // Update the inactivity state before processing listen callbacks, because the background
10062 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010063 // just yet though, because they have to be sent after the listens are processed to keep
10064 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010065 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010066 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010067 // Rematching may have altered the inactivity state of some networks, so update all
10068 // inactivity timers. updateInactivityState reads the state from the network agent
10069 // and does nothing if the state has not changed : the source of truth is controlled
10070 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10071 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010072 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010073 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010074 }
10075 }
10076
Chalard Jeanb10ab412019-12-11 14:12:30 +090010077 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010078 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010079 // Process listen requests and update capabilities if the background state has
10080 // changed for this network. For consistency with previous behavior, send onLost
10081 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010082 processNewlyLostListenRequests(nai);
10083 if (oldBackground != nai.isBackgroundNetwork()) {
10084 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010085 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010086 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010087 }
10088
junyulai0ac374f2020-12-14 18:41:52 +080010089 for (final NetworkAgentInfo nai : inactiveNetworks) {
10090 // For nascent networks, if connecting with no foreground request, skip broadcasting
10091 // LOSING for backward compatibility. This is typical when mobile data connected while
10092 // wifi connected with mobile data always-on enabled.
10093 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010094 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010095 }
10096
Chalard Jean1e4c2182023-10-06 18:45:53 +090010097 // Update forwarding rules for the upstreams of local networks. Do this after sending
10098 // onAvailable so that clients understand what network this is about.
10099 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10100 if (!nai.isLocalNetwork()) continue;
10101 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10102 if (null == nr) continue; // No upstream for this local network
10103 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10104 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10105 if (null == change) continue; // No change in upstreams for this network
10106 final String fromIface = nai.linkProperties.getInterfaceName();
10107 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10108 || change.mOldNetwork.isDestroyed()) {
10109 // There can be a change with the same interface name if the new network is the
10110 // replacement for the old network that was unregisteredAfterReplacement.
10111 try {
10112 if (null != change.mOldNetwork) {
10113 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10114 change.mOldNetwork.linkProperties.getInterfaceName());
10115 }
10116 // If the new upstream is already destroyed, there is no point in setting up
10117 // a forward (in fact, it might forward to the interface for some new network !)
10118 // Later when the upstream disconnects CS will try to remove the forward, which
10119 // is ignored with a benign log by RoutingCoordinatorService.
10120 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10121 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10122 change.mNewNetwork.linkProperties.getInterfaceName());
10123 }
10124 } catch (final RemoteException e) {
10125 loge("Can't update forwarding rules", e);
10126 }
10127 }
Chalard Jean22350c92023-10-07 19:21:45 +090010128 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010129 }
10130
James Mattise3ef1912020-12-20 11:09:58 -080010131 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010132
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010133 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010134 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010135 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010136 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010137 // This network has active linger timers and no requests, but is not
10138 // lingering. Linger it.
10139 //
10140 // One way (the only way?) this can happen if this network is unvalidated
10141 // and became unneeded due to another network improving its score to the
10142 // point where this network will no longer be able to satisfy any requests
10143 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010144 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010145 notifyNetworkLosing(nai, now);
10146 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010147 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010148 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010149 teardownUnneededNetwork(nai);
10150 }
10151 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010152 }
10153 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010154
Chalard Jean62edfd82019-12-02 18:39:29 +090010155 /**
10156 * Apply a change in background state resulting from rematching networks with requests.
10157 *
10158 * During rematch, a network may change background states by starting to satisfy or stopping
10159 * to satisfy a foreground request. Listens don't count for this. When a network changes
10160 * background states, its capabilities need to be updated and callbacks fired for the
10161 * capability change.
10162 *
10163 * @param nai The network that changed background states
10164 */
10165 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10166 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10167 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10168 updateNetworkPermissions(nai, newNc);
10169 nai.getAndSetNetworkCapabilities(newNc);
10170 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10171 }
10172
Chalard Jeanf0344532019-11-19 19:23:38 +090010173 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010174 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010175 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010176 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10177 changes.getReassignment(mDefaultRequest);
10178 final NetworkAgentInfo oldDefaultNetwork =
10179 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10180 final NetworkAgentInfo newDefaultNetwork =
10181 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010182
Chalard Jean5b409c72021-02-04 13:12:59 +090010183 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010184 // Maintain the illusion : since the legacy API only understands one network at a time,
10185 // if the default network changed, apps should see a disconnected broadcast for the
10186 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010187 if (oldDefaultNetwork != null) {
10188 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10189 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010190 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010191 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010192 // The new default network can be newly null if and only if the old default
10193 // network doesn't satisfy the default request any more because it lost a
10194 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010195 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010196 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010197 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010198 }
10199 }
10200
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010201 // Now that all the callbacks have been sent, send the legacy network broadcasts
10202 // as needed. This is necessary so that legacy requests correctly bind dns
10203 // requests to this network. The legacy users are listening for this broadcast
10204 // and will generally do a dns request so they can ensureRouteToHost and if
10205 // they do that before the callbacks happen they'll use the default network.
10206 //
10207 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10208 // callbacks, but if apps can receive the broadcast before the callback, they still might
10209 // have an inconsistent view of networking.
10210 //
10211 // This *does* introduce a race where if the user uses the new api
10212 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10213 // they may get old info. Reverse this after the old startUsing api is removed.
10214 // This is on top of the multiple intent sequencing referenced in the todo above.
10215 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010216 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010217 addNetworkToLegacyTypeTracker(nai);
10218 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010219 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010220 }
10221
Chalard Jean0354d8c2021-01-12 10:58:56 +090010222 private void issueNetworkNeeds() {
10223 ensureRunningOnConnectivityServiceThread();
10224 for (final NetworkOfferInfo noi : mNetworkOffers) {
10225 issueNetworkNeeds(noi);
10226 }
10227 }
10228
10229 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10230 ensureRunningOnConnectivityServiceThread();
10231 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10232 informOffer(nri, noi.offer, mNetworkRanker);
10233 }
10234 }
10235
10236 /**
10237 * Inform a NetworkOffer about any new situation of a request.
10238 *
10239 * This function handles updates to offers. A number of events may happen that require
10240 * updating the registrant for this offer about the situation :
10241 * • The offer itself was updated. This may lead the offer to no longer being able
10242 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10243 * or conversely being strengthened enough to beat the satisfier (and therefore
10244 * start being needed)
10245 * • The network satisfying a request changed (including cases where the request
10246 * starts or stops being satisfied). The new network may be a stronger or weaker
10247 * match than the old one, possibly affecting whether the offer is needed.
10248 * • The network satisfying a request updated their score. This may lead the offer
10249 * to no longer be able to beat it if the current satisfier got better, or
10250 * conversely start being a good choice if the current satisfier got weaker.
10251 *
10252 * @param nri The request
10253 * @param offer The offer. This may be an updated offer.
10254 */
10255 private static void informOffer(@NonNull NetworkRequestInfo nri,
10256 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10257 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10258 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010259
10260 // Multi-layer requests have a currently active request, the one being satisfied.
10261 // Since the system will try to bring up a better network than is currently satisfying
10262 // the request, NetworkProviders need to be told the offers matching the requests *above*
10263 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10264 // not needed, and the offer is needed for the active request iff the offer can beat
10265 // the satisfier.
10266 // For non-multilayer requests, the logic above gracefully degenerates to only the
10267 // last case.
10268 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10269 // providers that the offer is needed for this request, until the active request is found.
10270 // In a second phase, deal with the currently active request. In a third phase, inform
10271 // the providers that offer is unneeded for the remaining requests.
10272
10273 // First phase : inform providers of all requests above the active request.
10274 int i;
10275 for (i = 0; nri.mRequests.size() > i; ++i) {
10276 final NetworkRequest request = nri.mRequests.get(i);
10277 if (activeRequest == request) break; // Found the active request : go to phase 2
10278 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10279 // Since this request is higher-priority than the one currently satisfied, if the
10280 // offer can satisfy it, the provider should try and bring up the network for sure ;
10281 // no need to even ask the ranker – an offer that can satisfy is always better than
10282 // no network. Hence tell the provider so unless it already knew.
10283 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10284 offer.onNetworkNeeded(request);
10285 }
10286 }
10287
10288 // Second phase : deal with the active request (if any)
10289 if (null != activeRequest && activeRequest.isRequest()) {
10290 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010291 // If an offer can satisfy the request, it is considered needed if it is currently
10292 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010293 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010294 && satisfier.factorySerialNumber == offer.providerId
10295 && activeRequest.canBeSatisfiedBy(offer.caps);
10296 final boolean newNeeded = currentlyServing
10297 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010298 if (newNeeded != oldNeeded) {
10299 if (newNeeded) {
10300 offer.onNetworkNeeded(activeRequest);
10301 } else {
10302 // The offer used to be able to beat the satisfier. Now it can't.
10303 offer.onNetworkUnneeded(activeRequest);
10304 }
10305 }
10306 }
10307
10308 // Third phase : inform the providers that the offer isn't needed for any request
10309 // below the active one.
10310 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10311 final NetworkRequest request = nri.mRequests.get(i);
10312 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10313 // Since this request is lower-priority than the one currently satisfied, if the
10314 // offer can satisfy it, the provider should not try and bring up the network.
10315 // Hence tell the provider so unless it already knew.
10316 if (offer.neededFor(request)) {
10317 offer.onNetworkUnneeded(request);
10318 }
10319 }
10320 }
10321
Chalard Jean61c79252019-11-07 23:07:32 +090010322 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10323 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10324 NetworkRequest nr = nai.requestAt(i);
10325 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10326 // legacy type tracker filters out repeat adds
10327 mLegacyTypeTracker.add(nr.legacyType, nai);
10328 }
10329 }
10330
10331 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010332 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010333 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10334 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10335 if (nai.isVPN()) {
10336 mLegacyTypeTracker.add(TYPE_VPN, nai);
10337 }
10338 }
10339
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010340 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010341 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010342 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010343 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010344 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010345 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010346
Chalard Jean254bd162022-08-25 13:04:51 +090010347 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010348 // Don't repeat publish.
10349 if (newInetCondition == mDefaultInetConditionPublished) return;
10350
10351 mDefaultInetConditionPublished = newInetCondition;
10352 sendInetConditionBroadcast(nai.networkInfo);
10353 }
10354
Chalard Jeand61375d2020-01-14 22:46:36 +090010355 @NonNull
10356 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10357 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010358 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010359 final boolean suspended =
10360 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10361 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10362 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10363 // state. This is because the network could have been suspended before connecting,
10364 // or it could be disconnecting while being suspended, and in both these cases
10365 // the state should not be overridden. Note that the only detailed state that
10366 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10367 // worry about multiple different substates of CONNECTED.
10368 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10369 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010370 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10371 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10372 // network agent is created, then goes to suspended, then goes out of suspended without
10373 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010374 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010375 ? NetworkInfo.DetailedState.CONNECTED
10376 : NetworkInfo.DetailedState.CONNECTING,
10377 info.getReason(),
10378 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010379 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010380 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010381 return newInfo;
10382 }
10383
10384 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10385 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10386
Erik Kline99f301b2017-02-15 19:59:17 +090010387 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010388 NetworkInfo oldInfo = null;
10389 synchronized (networkAgent) {
10390 oldInfo = networkAgent.networkInfo;
10391 networkAgent.networkInfo = newInfo;
10392 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010393
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010394 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010395 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10396 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010397 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010398
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010399 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010400 // A network that has just connected has zero requests and is thus a foreground network.
10401 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10402
Luke Huangfdd11f82019-04-09 18:41:49 +080010403 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010404
10405 networkAgent.setCreated();
10406
10407 // If the network is created immediately on register, then apply the LinkProperties now.
10408 // Otherwise, this is done further down when the network goes into connected state.
10409 // Applying the LinkProperties means that the network is ready to carry traffic -
10410 // interfaces and routing rules have been added, DNS servers programmed, etc.
10411 // For VPNs, this must be done before the capabilities are updated, because as soon as
10412 // that happens, UIDs are routed to the network.
10413 if (shouldCreateNetworksImmediately()) {
10414 applyInitialLinkProperties(networkAgent);
10415 }
10416
10417 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10418 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010419 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010420 // Initialize the network's capabilities to their starting values according to the
10421 // underlying networks. This ensures that the capabilities are correct before
10422 // anything happens to the network.
10423 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010424 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010425 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010426 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010427 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010428 }
10429
Chalard Jean254bd162022-08-25 13:04:51 +090010430 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10431 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010432
lucaslin45e639b2019-04-03 17:09:28 +080010433 // NetworkCapabilities need to be set before sending the private DNS config to
10434 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010435 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10436
Erik Kline9a62f012018-03-21 07:18:33 -070010437 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010438 if (!shouldCreateNetworksImmediately()) {
10439 applyInitialLinkProperties(networkAgent);
10440 } else {
10441 // The network was created when the agent registered, and the LinkProperties are
10442 // already up-to-date. However, updateLinkProperties also makes some changes only
10443 // when the network connects. Apply those changes here. On T and below these are
10444 // handled by the applyInitialLinkProperties call just above.
10445 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10446 // If something depends on both LinkProperties and connected state, it should be in
10447 // this method as well.
10448 networkAgent.clatd.update();
10449 updateProxy(networkAgent.linkProperties, null);
10450 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010451
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010452 // If a rate limit has been configured and is applicable to this network (network
10453 // provides internet connectivity), apply it. The tc police filter cannot be attached
10454 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010455 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010456 // Note: in case of a system server crash, the NetworkController constructor in netd
10457 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10458 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10459 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10460 mIngressRateLimit);
10461 }
10462
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010463 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10464 // command must be sent after updating LinkProperties to maximize chances of
10465 // NetworkMonitor seeing the correct LinkProperties when starting.
10466 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010467 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010468 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010469 }
Chalard Jeand4900722022-02-06 12:25:38 +090010470 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10471 params.networkAgentConfig = networkAgent.networkAgentConfig;
10472 params.networkCapabilities = networkAgent.networkCapabilities;
10473 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10474 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010475 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10476 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10477 // call that would cause a Log.wtf to be emitted from the system_server process, and
10478 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10479 // process to check the interface version, just use an SDK check. NetworkStack will
10480 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010481 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010482 networkAgent.networkMonitor().notifyNetworkConnected(params);
10483 } else {
10484 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10485 params.networkCapabilities);
10486 }
Chalard Jean0f141332023-06-05 19:26:17 +090010487 final long evaluationDelay;
10488 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10489 // If the network is anything other than pure wifi, use the default timeout.
10490 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10491 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10492 // If the network is explicitly selected, use the default timeout because it's
10493 // shorter and the user is likely staring at the screen expecting it to validate
10494 // right away.
10495 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10496 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10497 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10498 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10499 } else {
10500 // It's wifi, automatically connected, and bad wifi is preferred : use the
10501 // longer timeout to avoid the device switching to captive portals with bad
10502 // signal or very slow response.
10503 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10504 }
10505 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010506
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010507 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10508 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10509 // capabilities, so it only needs to be done once on initial connect, not every time the
10510 // network's capabilities change. Note that we do this before rematching the network,
10511 // so we could decide to tear it down immediately afterwards. That's fine though - on
10512 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10513 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010514 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010515
junyulai0ac374f2020-12-14 18:41:52 +080010516 // Before first rematching networks, put an inactivity timer without any request, this
10517 // allows {@code updateInactivityState} to update the state accordingly and prevent
10518 // tearing down for any {@code unneeded} evaluation in this period.
10519 // Note that the timer will not be rescheduled since the expiry time is
10520 // fixed after connection regardless of the network satisfying other requests or not.
10521 // But it will be removed as soon as the network satisfies a request for the first time.
10522 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10523 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010524 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010525
Paul Jensen05e85ee2014-09-11 11:00:39 -040010526 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010527 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010528
10529 // This has to happen after matching the requests, because callbacks are just requests.
10530 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010531 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010532 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010533 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010534 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010535 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010536 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010537 if (networkAgent.isVPN()) {
10538 // As the active or bound network changes for apps, broadcast the default proxy, as
10539 // apps may need to update their proxy data. This is called after disconnecting from
10540 // VPN to make sure we do not broadcast the old proxy data.
10541 // TODO(b/122649188): send the broadcast only to VPN users.
10542 mProxyTracker.sendProxyBroadcast();
10543 }
Chalard Jean254bd162022-08-25 13:04:51 +090010544 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10545 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010546 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010547 }
10548 }
10549
Chalard Jean28018572020-12-21 18:36:52 +090010550 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010551 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10552 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010553 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010554 }
10555
Erik Kline99f301b2017-02-15 19:59:17 +090010556 // Notify only this one new request of the current state. Transfer all the
10557 // current state by calling NetworkCapabilities and LinkProperties callbacks
10558 // so that callers can be guaranteed to have as close to atomicity in state
10559 // transfer as can be supported by this current API.
10560 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010561 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010562 if (nri.mPendingIntent != null) {
10563 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10564 // Attempt no subsequent state pushes where intents are involved.
10565 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010566 }
Erik Kline99f301b2017-02-15 19:59:17 +090010567
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010568 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010569 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010570 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10571 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10572 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010573 }
10574
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010575 // Notify the requests on this NAI that the network is now lingered.
10576 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010577 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010578 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10579 }
10580
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010581 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10582 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10583 return vpnBlocked
10584 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10585 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10586 }
10587
10588 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10589 if (blockedReasons == BLOCKED_REASON_NONE) {
10590 mUidBlockedReasons.delete(uid);
10591 } else {
10592 mUidBlockedReasons.put(uid, blockedReasons);
10593 }
10594 }
10595
junyulaif2c67e42018-08-07 19:50:45 +080010596 /**
10597 * Notify of the blocked state apps with a registered callback matching a given NAI.
10598 *
10599 * Unlike other callbacks, blocked status is different between each individual uid. So for
10600 * any given nai, all requests need to be considered according to the uid who filed it.
10601 *
10602 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010603 * @param oldMetered True if the previous network capabilities were metered.
10604 * @param newMetered True if the current network capabilities are metered.
10605 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10606 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010607 */
10608 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010609 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10610 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010611
10612 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10613 NetworkRequest nr = nai.requestAt(i);
10614 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010615
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010616 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10617 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10618 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010619 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010620 : oldVpnBlocked;
10621
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010622 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10623 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10624 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010625 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010626 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010627 }
10628 }
10629 }
10630
10631 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010632 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010633 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010634 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010635 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010636 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010637 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010638 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010639 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010640
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010641 final int oldBlockedState = getBlockedState(
10642 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10643 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10644 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010645 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010646 }
junyulaif2c67e42018-08-07 19:50:45 +080010647 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10648 NetworkRequest nr = nai.requestAt(i);
10649 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010650 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010651 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10652 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010653 }
10654 }
10655 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010656 }
10657
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010658 @VisibleForTesting
10659 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010660 // The NetworkInfo we actually send out has no bearing on the real
10661 // state of affairs. For example, if the default connection is mobile,
10662 // and a request for HIPRI has just gone away, we need to pretend that
10663 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10664 // the state to DISCONNECTED, even though the network is of type MOBILE
10665 // and is still connected.
10666 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10667 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010668 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010669 if (state != DetailedState.DISCONNECTED) {
10670 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010671 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010672 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010673 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010674 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10675 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10676 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10677 if (info.isFailover()) {
10678 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10679 nai.networkInfo.setFailover(false);
10680 }
10681 if (info.getReason() != null) {
10682 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10683 }
10684 if (info.getExtraInfo() != null) {
10685 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10686 }
10687 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010688 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010689 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010690 if (newDefaultAgent != null) {
10691 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10692 newDefaultAgent.networkInfo);
10693 } else {
10694 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10695 }
10696 }
10697 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10698 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010699 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010700 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010701 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010702 }
10703 }
10704 }
10705
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010706 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010707 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010708 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010709 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010710 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010711 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10712 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010713 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10714 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010715 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010716 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010717 } else {
10718 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10719 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010720 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010721 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010722
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010723 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10724 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10725 }
10726
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010727 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010728 * Returns the list of all interfaces that could be used by network traffic that does not
10729 * explicitly specify a network. This includes the default network, but also all VPNs that are
10730 * currently connected.
10731 *
10732 * Must be called on the handler thread.
10733 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010734 @NonNull
10735 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010736 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010737 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010738 final Set<Integer> activeNetIds = new ArraySet<>();
10739 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10740 if (nri.isBeingSatisfied()) {
10741 activeNetIds.add(nri.getSatisfier().network().netId);
10742 }
10743 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010744 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010745 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010746 defaultNetworks.add(nai.network);
10747 }
10748 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010749 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010750 }
10751
10752 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010753 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10754 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010755 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010756 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010757 ensureRunningOnConnectivityServiceThread();
10758 String activeIface = null;
10759 LinkProperties activeLinkProperties = getActiveLinkProperties();
10760 if (activeLinkProperties != null) {
10761 activeIface = activeLinkProperties.getInterfaceName();
10762 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010763
junyulai2050bed2021-01-23 09:46:34 +080010764 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010765 try {
junyulaide41fc22021-01-22 22:46:01 +080010766 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010767 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010768 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10769 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010770 } catch (Exception ignored) {
10771 }
10772 }
10773
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010774 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010775 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010776 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010777 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010778 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010779
10780 if (!TextUtils.isEmpty(settingUrl)) {
10781 return settingUrl;
10782 }
10783
10784 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010785 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010786 if (!TextUtils.isEmpty(settingUrl)) {
10787 return settingUrl;
10788 }
10789
10790 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010791 }
10792
10793 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010794 public void startNattKeepalive(Network network, int intervalSeconds,
10795 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010796 enforceKeepalivePermission();
10797 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010798 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010799 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10800 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010801 // false and set the underpinned network to null because there is no way and no
10802 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10803 // deprecated method.
10804 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010805 }
10806
10807 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010808 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010809 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010810 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010811 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010812 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010813 mKeepaliveTracker.startNattKeepalive(
10814 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010815 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10816 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010817 } finally {
10818 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10819 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010820 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10821 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010822 }
10823 }
junyulaid05a1922019-01-15 11:32:44 +080010824 }
10825
10826 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010827 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010828 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010829 try {
10830 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010831 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010832 mKeepaliveTracker.startTcpKeepalive(
10833 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10834 } finally {
10835 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10836 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010837 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10838 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010839 }
10840 }
junyulai0835a1e2019-01-08 20:04:33 +080010841 }
10842
10843 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010844 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010845 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010846 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10847 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010848 }
10849
10850 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010851 public int[] getSupportedKeepalives() {
10852 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10853 // Backwards compatibility with CTS 13
10854 android.Manifest.permission.QUERY_ALL_PACKAGES);
10855
10856 return BinderUtils.withCleanCallingIdentity(() ->
10857 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10858 }
10859
10860 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010861 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010862 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010863
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010864 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010865 final long token = Binder.clearCallingIdentity();
10866 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010867 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10868 UserHandle.getUserHandleForUid(uid))) {
10869 return;
10870 }
10871
Heemin Seogdb8489d2019-06-12 09:21:44 -070010872 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10873 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010874
10875 // Turn airplane mode off
10876 setAirplaneMode(false);
10877
10878 // restore private DNS settings to default mode (opportunistic)
10879 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10880 UserHandle.getUserHandleForUid(uid))) {
10881 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10882 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10883 }
10884
10885 Settings.Global.putString(mContext.getContentResolver(),
10886 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010887 } finally {
10888 Binder.restoreCallingIdentity(token);
10889 }
Stuart Scottd5463642015-04-02 18:00:02 -070010890 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010891
Ricky Wai7097cc92018-01-23 04:09:45 +000010892 @Override
10893 public byte[] getNetworkWatchlistConfigHash() {
10894 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10895 if (nwm == null) {
10896 loge("Unable to get NetworkWatchlistManager");
10897 return null;
10898 }
10899 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10900 return nwm.getWatchlistConfigHash();
10901 }
10902
Hugo Benichibe0c7652016-05-31 16:28:06 +090010903 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010904 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010905 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010906 }
Hugo Benichif4210292017-04-21 15:07:12 +090010907
10908 private static boolean toBool(int encodedBoolean) {
10909 return encodedBoolean != 0; // Only 0 means false.
10910 }
10911
10912 private static int encodeBool(boolean b) {
10913 return b ? 1 : 0;
10914 }
mswest4632928412018-03-12 10:34:34 -070010915
10916 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010917 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10918 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10919 @NonNull String[] args) {
10920 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10921 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010922 }
10923
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010924 private Boolean parseBooleanArgument(final String arg) {
10925 if ("true".equals(arg)) {
10926 return true;
10927 } else if ("false".equals(arg)) {
10928 return false;
10929 } else {
10930 return null;
10931 }
10932 }
10933
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010934 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010935 @Override
10936 public int onCommand(String cmd) {
10937 if (cmd == null) {
10938 return handleDefaultCommands(cmd);
10939 }
10940 final PrintWriter pw = getOutPrintWriter();
10941 try {
10942 switch (cmd) {
10943 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010944 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10945 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010946 final String action = getNextArg();
10947 if ("enable".equals(action)) {
10948 setAirplaneMode(true);
10949 return 0;
10950 } else if ("disable".equals(action)) {
10951 setAirplaneMode(false);
10952 return 0;
10953 } else if (action == null) {
10954 final ContentResolver cr = mContext.getContentResolver();
10955 final int enabled = Settings.Global.getInt(cr,
10956 Settings.Global.AIRPLANE_MODE_ON);
10957 pw.println(enabled == 0 ? "disabled" : "enabled");
10958 return 0;
10959 } else {
10960 onHelp();
10961 return -1;
10962 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010963 case "set-chain3-enabled": {
10964 final Boolean enabled = parseBooleanArgument(getNextArg());
10965 if (null == enabled) {
10966 onHelp();
10967 return -1;
10968 }
10969 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
10970 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10971 enabled);
10972 return 0;
10973 }
10974 case "get-chain3-enabled": {
10975 final boolean chainEnabled = getFirewallChainEnabled(
10976 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
10977 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
10978 return 0;
10979 }
10980 case "set-package-networking-enabled": {
10981 final Boolean enabled = parseBooleanArgument(getNextArg());
10982 final String packageName = getNextArg();
10983 if (null == enabled || null == packageName) {
10984 onHelp();
10985 return -1;
10986 }
10987 // Throws NameNotFound if the package doesn't exist.
10988 final int appId = setPackageFirewallRule(
10989 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10990 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
10991 final String msg = (enabled ? "Enabled" : "Disabled")
10992 + " networking for " + packageName + ", appId " + appId;
10993 Log.i(TAG, msg);
10994 pw.println(msg);
10995 return 0;
10996 }
10997 case "get-package-networking-enabled": {
10998 final String packageName = getNextArg();
10999 final int rule = getPackageFirewallRule(
11000 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11001 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11002 pw.println(packageName + ":" + "allow");
11003 } else if (FIREWALL_RULE_DENY == rule) {
11004 pw.println(packageName + ":" + "deny");
11005 } else {
11006 throw new IllegalStateException("Unknown rule " + rule + " for package "
11007 + packageName);
11008 }
11009 return 0;
11010 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011011 case "reevaluate":
11012 // Usage : adb shell cmd connectivity reevaluate <netId>
11013 // If netId is omitted, then reevaluate the default network
11014 final String netId = getNextArg();
11015 final NetworkAgentInfo nai;
11016 if (null == netId) {
11017 // Note that the command is running on the wrong thread to call this,
11018 // so this could in principle return stale data. But it can't crash.
11019 nai = getDefaultNetwork();
11020 } else {
11021 // If netId can't be parsed, this throws NumberFormatException, which
11022 // is passed back to adb who prints it.
11023 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11024 }
11025 if (null == nai) {
11026 pw.println("Unknown network (net ID not found or no default network)");
11027 return 0;
11028 }
11029 Log.d(TAG, "Reevaluating network " + nai.network);
11030 reportNetworkConnectivity(nai.network, !nai.isValidated());
11031 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011032 case "bpf-get-cgroup-program-id": {
11033 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11034 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11035 // for more detail.
11036 // If type can't be parsed, this throws NumberFormatException, which
11037 // is passed back to adb who prints it.
11038 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011039 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011040 pw.println(ret);
11041 return 0;
11042 }
mswest4632928412018-03-12 10:34:34 -070011043 default:
11044 return handleDefaultCommands(cmd);
11045 }
11046 } catch (Exception e) {
11047 pw.println(e);
11048 }
11049 return -1;
11050 }
11051
11052 @Override
11053 public void onHelp() {
11054 PrintWriter pw = getOutPrintWriter();
11055 pw.println("Connectivity service commands:");
11056 pw.println(" help");
11057 pw.println(" Print this help text.");
11058 pw.println(" airplane-mode [enable|disable]");
11059 pw.println(" Turn airplane mode on or off.");
11060 pw.println(" airplane-mode");
11061 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011062 pw.println(" set-chain3-enabled [true|false]");
11063 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11064 pw.println(" get-chain3-enabled");
11065 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11066 pw.println(" set-package-networking-enabled [true|false] [package name]");
11067 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11068 + " no effect if the chain is disabled.");
11069 pw.println(" get-package-networking-enabled [package name]");
11070 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011071 }
11072 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011073
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011074 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011075 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11076 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11077 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011078 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011079 }
11080
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011081 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11082 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011083 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11084 final TransportInfo newInfo = nc.getTransportInfo();
11085 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11086 return;
11087 }
11088 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011089 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011090 }
11091 }
11092
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011093 /**
11094 * @param connectionInfo the connection to resolve.
11095 * @return {@code uid} if the connection is found and the app has permission to observe it
11096 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11097 * connection is not found.
11098 */
11099 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011100 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11101 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11102 }
11103
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011104 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011105 connectionInfo.local, connectionInfo.remote);
11106
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011107 if (uid == INVALID_UID) return uid; // Not found.
11108
11109 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11110 // VPN, if any, that applies to the UID that owns the connection.
11111 if (checkNetworkStackPermission()) return uid;
11112
11113 final NetworkAgentInfo vpn = getVpnForUid(uid);
11114 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011115 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011116 return INVALID_UID;
11117 }
11118
11119 return uid;
11120 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011121
Benedict Wong493e04b2018-11-09 14:45:34 -080011122 /**
11123 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11124 *
11125 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11126 */
11127 @Override
11128 public IBinder startOrGetTestNetworkService() {
11129 synchronized (mTNSLock) {
11130 TestNetworkService.enforceTestNetworkPermissions(mContext);
11131
11132 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011133 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011134 }
11135
11136 return mTNS;
11137 }
11138 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011139
Cody Kesting73708bf2019-12-18 10:57:50 -080011140 /**
11141 * Handler used for managing all Connectivity Diagnostics related functions.
11142 *
11143 * @see android.net.ConnectivityDiagnosticsManager
11144 *
11145 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11146 */
11147 @VisibleForTesting
11148 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011149 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11150
Cody Kesting73708bf2019-12-18 10:57:50 -080011151 /**
11152 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11153 * android.net.ConnectivityDiagnosticsManager}.
11154 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11155 * NetworkRequestInfo to be registered
11156 */
11157 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11158
11159 /**
11160 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11161 * android.net.ConnectivityDiagnosticsManager}.
11162 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11163 * arg1 = the uid of the caller
11164 */
11165 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11166
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011167 /**
11168 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011169 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011170 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11171 * NetworkMonitor.
11172 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011173 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011174 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011175
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011176 /**
11177 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11178 * been detected on the network.
11179 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11180 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11181 * arg2 = NetID.
11182 * data = PersistableBundle of extras passed from NetworkMonitor.
11183 */
11184 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11185
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011186 /**
11187 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11188 * the platform. This event will invoke {@link
11189 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11190 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011191 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011192 */
11193 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11194
Cody Kesting73708bf2019-12-18 10:57:50 -080011195 private ConnectivityDiagnosticsHandler(Looper looper) {
11196 super(looper);
11197 }
11198
11199 @Override
11200 public void handleMessage(Message msg) {
11201 switch (msg.what) {
11202 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11203 handleRegisterConnectivityDiagnosticsCallback(
11204 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11205 break;
11206 }
11207 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11208 handleUnregisterConnectivityDiagnosticsCallback(
11209 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11210 break;
11211 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011212 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011213 final ConnectivityReportEvent reportEvent =
11214 (ConnectivityReportEvent) msg.obj;
11215
Aaron Huang959d3642021-01-21 15:47:41 +080011216 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011217 break;
11218 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011219 case EVENT_DATA_STALL_SUSPECTED: {
11220 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011221 final Pair<Long, PersistableBundle> arg =
11222 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011223 if (nai == null) break;
11224
Aaron Huang959d3642021-01-21 15:47:41 +080011225 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011226 break;
11227 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011228 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011229 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011230 break;
11231 }
11232 default: {
11233 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11234 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011235 }
11236 }
11237 }
11238
11239 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11240 @VisibleForTesting
11241 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11242 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11243 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011244 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011245
11246 @VisibleForTesting
11247 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011248 @NonNull IConnectivityDiagnosticsCallback cb,
11249 @NonNull NetworkRequestInfo nri,
11250 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011251 mCb = cb;
11252 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011253 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011254 }
11255
11256 @Override
11257 public void binderDied() {
11258 log("ConnectivityDiagnosticsCallback IBinder died.");
11259 unregisterConnectivityDiagnosticsCallback(mCb);
11260 }
11261 }
11262
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011263 /**
11264 * Class used for sending information from {@link
11265 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11266 */
11267 private static class NetworkTestedResults {
11268 private final int mNetId;
11269 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011270 @Nullable private final String mRedirectUrl;
11271
11272 private NetworkTestedResults(
11273 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11274 mNetId = netId;
11275 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011276 mRedirectUrl = redirectUrl;
11277 }
11278 }
11279
11280 /**
11281 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11282 * ConnectivityDiagnosticsHandler}.
11283 */
11284 private static class ConnectivityReportEvent {
11285 private final long mTimestampMillis;
11286 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011287 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011288
Aaron Huang959d3642021-01-21 15:47:41 +080011289 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11290 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011291 mTimestampMillis = timestampMillis;
11292 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011293 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011294 }
11295 }
11296
Cody Kestingf1120be2020-08-03 18:01:40 -070011297 /**
11298 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11299 * ConnectivityDiagnosticsHandler}.
11300 */
11301 private static class ReportedNetworkConnectivityInfo {
11302 public final boolean hasConnectivity;
11303 public final boolean isNetworkRevalidating;
11304 public final int reporterUid;
11305 @NonNull public final NetworkAgentInfo nai;
11306
11307 private ReportedNetworkConnectivityInfo(
11308 boolean hasConnectivity,
11309 boolean isNetworkRevalidating,
11310 int reporterUid,
11311 @NonNull NetworkAgentInfo nai) {
11312 this.hasConnectivity = hasConnectivity;
11313 this.isNetworkRevalidating = isNetworkRevalidating;
11314 this.reporterUid = reporterUid;
11315 this.nai = nai;
11316 }
11317 }
11318
Cody Kesting73708bf2019-12-18 10:57:50 -080011319 private void handleRegisterConnectivityDiagnosticsCallback(
11320 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11321 ensureRunningOnConnectivityServiceThread();
11322
11323 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011324 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011325 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11326
James Mattis64b8b0f2020-11-24 17:40:49 -080011327 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11328 // confusing for these networks to change when an NRI is satisfied in another layer.
11329 if (nri.isMultilayerRequest()) {
11330 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11331 + "network requests.");
11332 }
11333
Cody Kesting73708bf2019-12-18 10:57:50 -080011334 // This means that the client registered the same callback multiple times. Do
11335 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011336 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011337 if (VDBG) log("Diagnostics callback is already registered");
11338
11339 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11340 // incremented when the NetworkRequestInfo is created as part of
11341 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011342 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011343 return;
11344 }
11345
Cody Kesting31f1ff62020-03-05 10:46:02 -080011346 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011347
11348 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011349 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011350 } catch (RemoteException e) {
11351 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011352 return;
11353 }
11354
11355 // Once registered, provide ConnectivityReports for matching Networks
11356 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11357 synchronized (mNetworkForNetId) {
11358 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11359 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011360 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11361 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011362 matchingNetworks.add(nai);
11363 }
11364 }
11365 }
11366 for (final NetworkAgentInfo nai : matchingNetworks) {
11367 final ConnectivityReport report = nai.getConnectivityReport();
11368 if (report == null) {
11369 continue;
11370 }
11371 if (!checkConnectivityDiagnosticsPermissions(
11372 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11373 continue;
11374 }
11375
11376 try {
11377 cb.onConnectivityReportAvailable(report);
11378 } catch (RemoteException e) {
11379 // Exception while sending the ConnectivityReport. Move on to the next network.
11380 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011381 }
11382 }
11383
11384 private void handleUnregisterConnectivityDiagnosticsCallback(
11385 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11386 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011387 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011388
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011389 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11390 mConnectivityDiagnosticsCallbacks.remove(iCb);
11391 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011392 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11393 return;
11394 }
11395
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011396 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011397
Cody Kesting70fa2b22020-12-02 12:16:56 -080011398 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11399 // (if the Binder died)
11400 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11401 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011402 return;
11403 }
11404
Cody Kesting46cb1672020-03-04 13:35:20 -080011405 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11406 // incremented when the NetworkRequestInfo is created as part of
11407 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011408 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011409
Cody Kesting31f1ff62020-03-05 10:46:02 -080011410 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011411 }
11412
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011413 private void handleNetworkTestedWithExtras(
11414 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11415 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011416 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011417 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011418 final ConnectivityReport report =
11419 new ConnectivityReport(
11420 reportEvent.mNai.network,
11421 reportEvent.mTimestampMillis,
11422 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011423 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011424 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011425 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011426
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011427 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011428 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011429 for (final IConnectivityDiagnosticsCallback cb : results) {
11430 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011431 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011432 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011433 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011434 }
11435 }
11436 }
11437
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011438 private void handleDataStallSuspected(
11439 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11440 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011441 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011442 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011443 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011444 new DataStallReport(
11445 nai.network,
11446 timestampMillis,
11447 detectionMethod,
11448 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011449 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011450 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011451 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011452 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011453 for (final IConnectivityDiagnosticsCallback cb : results) {
11454 try {
11455 cb.onDataStallSuspected(report);
11456 } catch (RemoteException ex) {
11457 loge("Error invoking onDataStallSuspected", ex);
11458 }
11459 }
11460 }
11461
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011462 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011463 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11464 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11465 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11466
11467 // If the Network is being re-validated as a result of this call to
11468 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11469 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011470 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011471 getMatchingPermissionedCallbacks(
11472 nai,
11473 reportedNetworkConnectivityInfo.isNetworkRevalidating
11474 ? Process.INVALID_UID
11475 : reportedNetworkConnectivityInfo.reporterUid);
11476
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011477 for (final IConnectivityDiagnosticsCallback cb : results) {
11478 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011479 cb.onNetworkConnectivityReported(
11480 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011481 } catch (RemoteException ex) {
11482 loge("Error invoking onNetworkConnectivityReported", ex);
11483 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011484
11485 // If the Network isn't re-validating, also provide the cached report. If there is no
11486 // cached report, the Network is still being validated and a report will be sent once
11487 // validation is complete. Note that networks which never undergo validation will still
11488 // have a cached ConnectivityReport with RESULT_SKIPPED.
11489 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11490 try {
11491 cb.onConnectivityReportAvailable(cachedReport);
11492 } catch (RemoteException ex) {
11493 loge("Error invoking onConnectivityReportAvailable", ex);
11494 }
11495 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011496 }
11497 }
11498
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011499 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011500 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11501 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011502 sanitized.setUids(null);
11503 sanitized.setAdministratorUids(new int[0]);
11504 sanitized.setOwnerUid(Process.INVALID_UID);
11505 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011506 }
11507
Cody Kestingf1120be2020-08-03 18:01:40 -070011508 /**
11509 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11510 *
11511 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11512 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011513 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011514 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011515 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011516 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011517 mConnectivityDiagnosticsCallbacks.entrySet()) {
11518 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11519 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011520
James Mattis64b8b0f2020-11-24 17:40:49 -080011521 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011522 if (!nai.satisfies(nri.mRequests.get(0))) {
11523 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011524 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011525
11526 // UID for this callback must either be:
11527 // - INVALID_UID (which sends callbacks to all UIDs), or
11528 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11529 // notified as a result)
11530 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11531 continue;
11532 }
11533
11534 if (!checkConnectivityDiagnosticsPermissions(
11535 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11536 continue;
11537 }
11538
11539 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011540 }
11541 return results;
11542 }
11543
Cody Kesting7474f672021-05-11 14:22:40 -070011544 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11545 @NonNull NetworkAgentInfo nai) {
11546 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11547 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11548 }
11549
Cody Kesting160ef392021-05-05 13:17:22 -070011550 private boolean hasLocationPermission(String packageName, int uid) {
11551 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11552 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11553 // call in a try-catch.
11554 try {
11555 if (!mLocationPermissionChecker.checkLocationPermission(
11556 packageName, null /* featureId */, uid, null /* message */)) {
11557 return false;
11558 }
11559 } catch (SecurityException e) {
11560 return false;
11561 }
11562
11563 return true;
11564 }
11565
11566 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11567 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011568 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011569 && virtual.networkCapabilities.getOwnerUid() == uid
11570 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11571 return true;
11572 }
11573 }
11574
11575 return false;
11576 }
11577
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011578 @VisibleForTesting
11579 boolean checkConnectivityDiagnosticsPermissions(
11580 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11581 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11582 return true;
11583 }
11584
Cody Kesting160ef392021-05-05 13:17:22 -070011585 // Administrator UIDs also contains the Owner UID
11586 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11587 if (!CollectionUtils.contains(administratorUids, callbackUid)
11588 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011589 return false;
11590 }
11591
Cody Kesting7474f672021-05-11 14:22:40 -070011592 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11593 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011594 }
11595
Cody Kestingd199a9d2019-12-17 12:55:28 -080011596 @Override
11597 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011598 @NonNull IConnectivityDiagnosticsCallback callback,
11599 @NonNull NetworkRequest request,
11600 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011601 Objects.requireNonNull(callback, "callback must not be null");
11602 Objects.requireNonNull(request, "request must not be null");
11603 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11604
Cody Kesting73708bf2019-12-18 10:57:50 -080011605 if (request.legacyType != TYPE_NONE) {
11606 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11607 + " Please use NetworkCapabilities instead.");
11608 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011609 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011610 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011611
11612 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11613 // and administrator uids to be safe.
11614 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011615 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011616
11617 final NetworkRequest requestWithId =
11618 new NetworkRequest(
11619 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11620
11621 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11622 //
11623 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11624 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11625 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011626 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011627 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011628 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011629
11630 mConnectivityDiagnosticsHandler.sendMessage(
11631 mConnectivityDiagnosticsHandler.obtainMessage(
11632 ConnectivityDiagnosticsHandler
11633 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11634 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011635 }
11636
11637 @Override
11638 public void unregisterConnectivityDiagnosticsCallback(
11639 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011640 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011641 mConnectivityDiagnosticsHandler.sendMessage(
11642 mConnectivityDiagnosticsHandler.obtainMessage(
11643 ConnectivityDiagnosticsHandler
11644 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011645 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011646 0,
11647 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011648 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011649
Yan Yanfe96dde2022-12-05 23:00:01 +000011650 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11651 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11652 if (underlyingNetworks == null) return false;
11653
11654 for (Network network : underlyingNetworks) {
11655 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11656 return true;
11657 }
11658 }
11659 return false;
11660 }
11661
Cody Kestingf53a0752020-04-15 12:33:28 -070011662 @Override
11663 public void simulateDataStall(int detectionMethod, long timestampMillis,
11664 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011665 Objects.requireNonNull(network, "network must not be null");
11666 Objects.requireNonNull(extras, "extras must not be null");
11667
paulhu3ffffe72021-09-16 10:15:22 +080011668 enforceAnyPermissionOf(mContext,
11669 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011670 android.Manifest.permission.NETWORK_STACK);
11671 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011672 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11673 throw new SecurityException(
11674 "Data Stall simulation is only possible for test networks or networks built on"
11675 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011676 }
11677
11678 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011679 if (nai == null
11680 || (nai.creatorUid != mDeps.getCallingUid()
11681 && nai.creatorUid != Process.SYSTEM_UID)) {
11682 throw new SecurityException(
11683 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011684 }
11685
Cody Kesting652e3ec2020-05-21 12:08:21 -070011686 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11687 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11688 // Data Stall information as a DataStallReportParcelable and passing to
11689 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11690 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011691 final DataStallReportParcelable p = new DataStallReportParcelable();
11692 p.timestampMillis = timestampMillis;
11693 p.detectionMethod = detectionMethod;
11694
11695 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11696 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11697 }
11698 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11699 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11700 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11701 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11702 }
11703
Serik Beketayevec8ad212020-12-07 22:43:07 -080011704 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011705 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011706
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011707 /**
11708 * Class to hold the information for network activity change event from idle timers
11709 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11710 */
11711 private static final class NetworkActivityParams {
11712 public final boolean isActive;
11713 // Label used for idle timer. Transport type is used as label.
11714 // label is int since NMS was using the identifier as int, and it has not been changed
11715 public final int label;
11716 public final long timestampNs;
11717 // Uid represents the uid that was responsible for waking the radio.
11718 // -1 for no uid and uid is -1 if isActive is false.
11719 public final int uid;
11720
11721 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11722 this.isActive = isActive;
11723 this.label = label;
11724 this.timestampNs = timestampNs;
11725 this.uid = uid;
11726 }
11727 }
11728
lucaslin66f44212021-02-23 01:12:55 +080011729 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11730 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011731 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011732 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011733 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11734 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011735 }
lucaslin37a16d92021-01-21 19:48:09 +080011736
11737 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011738 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011739 mHandler.post(() -> {
11740 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011741 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011742 }
11743 });
lucaslin37a16d92021-01-21 19:48:09 +080011744 }
11745
11746 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011747 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011748 mHandler.post(() -> {
11749 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011750 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011751 }
11752 });
lucaslin66f44212021-02-23 01:12:55 +080011753 }
11754 }
11755
lucaslin1a8b4c62021-01-21 02:02:55 +080011756 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11757
11758 /**
11759 * Class used for updating network activity tracking with netd and notify network activity
11760 * changes.
11761 */
11762 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011763 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011764 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011765 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011766 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011767 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11768 new RemoteCallbackList<>();
11769 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011770 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011771 // If there is no default network, default network is considered active to keep the existing
11772 // behavior. Initial value is used until first connect to the default network.
11773 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011774 // Key is netId. Value is configured idle timer information.
11775 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011776
Chalard Jean46bfbf02022-02-02 00:56:25 +090011777 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011778 public final int timeout;
11779 public final int transportType;
11780
11781 IdleTimerParams(int timeout, int transport) {
11782 this.timeout = timeout;
11783 this.transportType = transport;
11784 }
11785 }
11786
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011787 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011788 @NonNull Handler handler) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011789 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011790 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011791 mHandler = handler;
11792 }
11793
11794 private void ensureRunningOnConnectivityServiceThread() {
11795 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11796 throw new IllegalStateException("Not running on ConnectivityService thread: "
11797 + Thread.currentThread().getName());
11798 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011799 }
11800
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011801 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011802 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011803 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011804 // This activity change is not for the current default network.
11805 // This can happen if netd callback post activity change event message but
11806 // the default network is lost before processing this message.
11807 return;
11808 }
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011809 sendDataActivityBroadcast(transportTypeToLegacyType(activityParams.label),
11810 activityParams.isActive, activityParams.timestampNs);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011811 mIsDefaultNetworkActive = activityParams.isActive;
11812 if (mIsDefaultNetworkActive) {
11813 reportNetworkActive();
lucaslin66f44212021-02-23 01:12:55 +080011814 }
11815 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011816
lucaslin1193a5d2021-01-21 02:04:15 +080011817 private void reportNetworkActive() {
11818 final int length = mNetworkActivityListeners.beginBroadcast();
11819 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11820 try {
11821 for (int i = 0; i < length; i++) {
11822 try {
11823 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11824 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011825 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011826 }
11827 }
11828 } finally {
11829 mNetworkActivityListeners.finishBroadcast();
11830 }
11831 }
11832
lucaslin1a8b4c62021-01-21 02:02:55 +080011833 // This is deprecated and only to support legacy use cases.
11834 private int transportTypeToLegacyType(int type) {
11835 switch (type) {
11836 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011837 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011838 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011839 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011840 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011841 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011842 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011843 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011844 default:
11845 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11846 }
11847 return ConnectivityManager.TYPE_NONE;
11848 }
11849
11850 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11851 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11852 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11853 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11854 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11855 final long ident = Binder.clearCallingIdentity();
11856 try {
11857 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11858 RECEIVE_DATA_ACTIVITY_CHANGE,
11859 null /* resultReceiver */,
11860 null /* scheduler */,
11861 0 /* initialCode */,
11862 null /* initialData */,
11863 null /* initialExtra */);
11864 } finally {
11865 Binder.restoreCallingIdentity(ident);
11866 }
11867 }
11868
11869 /**
11870 * Setup data activity tracking for the given network.
11871 *
11872 * Every {@code setupDataActivityTracking} should be paired with a
11873 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090011874 *
11875 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080011876 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090011877 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011878 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011879 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011880
11881 final int timeout;
11882 final int type;
11883
11884 if (networkAgent.networkCapabilities.hasTransport(
11885 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11886 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011887 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011888 10);
11889 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11890 } else if (networkAgent.networkCapabilities.hasTransport(
11891 NetworkCapabilities.TRANSPORT_WIFI)) {
11892 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011893 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011894 15);
11895 type = NetworkCapabilities.TRANSPORT_WIFI;
11896 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011897 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080011898 }
11899
lucaslinb961efc2021-01-21 02:03:17 +080011900 updateRadioPowerState(true /* isActive */, type);
11901
lucaslin1a8b4c62021-01-21 02:02:55 +080011902 if (timeout > 0 && iface != null) {
11903 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011904 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, type));
Motomu Utsumic298cf02023-05-31 12:06:12 +090011905 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
Motomu Utsumi6225d572023-05-29 15:08:57 +090011906 return true;
lucaslin1a8b4c62021-01-21 02:02:55 +080011907 } catch (Exception e) {
11908 // You shall not crash!
11909 loge("Exception in setupDataActivityTracking " + e);
11910 }
11911 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011912 return false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011913 }
11914
11915 /**
11916 * Remove data activity tracking when network disconnects.
11917 */
11918 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11919 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011920 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011921 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11922
lucaslinb961efc2021-01-21 02:03:17 +080011923 if (iface == null) return;
11924
11925 final int type;
11926 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11927 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11928 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11929 type = NetworkCapabilities.TRANSPORT_WIFI;
11930 } else {
11931 return; // do not track any other networks
11932 }
11933
11934 try {
11935 updateRadioPowerState(false /* isActive */, type);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011936 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011937 if (params == null) {
11938 // IdleTimer is not added if the configured timeout is 0 or negative value
11939 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080011940 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011941 mActiveIdleTimers.remove(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011942 // The call fails silently if no idle timer setup for this interface
11943 mNetd.idletimerRemoveInterface(iface, params.timeout,
11944 Integer.toString(params.transportType));
lucaslinb961efc2021-01-21 02:03:17 +080011945 } catch (Exception e) {
11946 // You shall not crash!
11947 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011948 }
11949 }
11950
Motomu Utsumi6225d572023-05-29 15:08:57 +090011951 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
11952 boolean hasIdleTimer) {
11953 if (defaultNetwork != null) {
11954 mIsDefaultNetworkActive = true;
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011955 // Callbacks are called only when the network has the idle timer.
11956 if (hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011957 reportNetworkActive();
11958 }
11959 } else {
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011960 // If there is no default network, default network is considered active to keep the
11961 // existing behavior.
11962 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090011963 }
11964 }
11965
lucaslin1a8b4c62021-01-21 02:02:55 +080011966 /**
11967 * Update data activity tracking when network state is updated.
11968 */
11969 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11970 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011971 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi6225d572023-05-29 15:08:57 +090011972 boolean hasIdleTimer = false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011973 if (newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011974 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080011975 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011976 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
lucaslin1a8b4c62021-01-21 02:02:55 +080011977 if (oldNetwork != null) {
11978 removeDataActivityTracking(oldNetwork);
11979 }
11980 }
lucaslinb961efc2021-01-21 02:03:17 +080011981
11982 private void updateRadioPowerState(boolean isActive, int transportType) {
11983 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11984 switch (transportType) {
11985 case NetworkCapabilities.TRANSPORT_CELLULAR:
11986 bs.reportMobileRadioPowerState(isActive, NO_UID);
11987 break;
11988 case NetworkCapabilities.TRANSPORT_WIFI:
11989 bs.reportWifiRadioPowerState(isActive, NO_UID);
11990 break;
11991 default:
11992 logw("Untracked transport type:" + transportType);
11993 }
11994 }
lucaslin1193a5d2021-01-21 02:04:15 +080011995
11996 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011997 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080011998 }
11999
12000 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12001 mNetworkActivityListeners.register(l);
12002 }
12003
12004 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12005 mNetworkActivityListeners.unregister(l);
12006 }
lucaslin012f7a12021-01-21 02:04:35 +080012007
12008 public void dump(IndentingPrintWriter pw) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012009 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
12010 pw.println("Idle timers:");
12011 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012012 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12013 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12014 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012015 pw.print(" timeout="); pw.print(params.timeout);
12016 pw.print(" type="); pw.println(params.transportType);
12017 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090012018 } catch (Exception e) {
12019 // mActiveIdleTimers should only be accessed from handler thread, except dump().
12020 // As dump() is never called in normal usage, it would be needlessly expensive
12021 // to lock the collection only for its benefit.
12022 // Also, mActiveIdleTimers is not expected to be updated frequently.
12023 // So catching the exception and logging.
12024 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012025 }
12026 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012027 }
James Mattis47db0582021-01-01 14:13:35 -080012028
Daniel Brightf9e945b2020-06-15 16:10:01 -070012029 /**
12030 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12031 *
12032 * @param socketInfo the socket information
12033 * @param callback the callback to register
12034 */
12035 @Override
12036 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12037 @NonNull final IQosCallback callback) {
12038 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12039 if (nai == null || nai.networkCapabilities == null) {
12040 try {
12041 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12042 } catch (final RemoteException ex) {
12043 loge("registerQosCallbackInternal: RemoteException", ex);
12044 }
12045 return;
12046 }
12047 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12048 }
12049
12050 /**
12051 * Register a {@link IQosCallback} with base {@link QosFilter}.
12052 *
12053 * @param filter the filter to register
12054 * @param callback the callback to register
12055 * @param nai the agent information related to the filter's network
12056 */
12057 @VisibleForTesting
12058 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12059 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012060 Objects.requireNonNull(filter, "filter must be non-null");
12061 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012062
12063 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012064 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12065 // on this network is unregistered when the app loses permission or b) no QoS
12066 // callbacks are sent for restricted networks unless the app currently has permission
12067 // to access restricted networks.
12068 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012069 }
12070 mQosCallbackTracker.registerCallback(callback, filter, nai);
12071 }
12072
12073 /**
12074 * Unregisters the given callback.
12075 *
12076 * @param callback the callback to unregister
12077 */
12078 @Override
12079 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012080 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012081 mQosCallbackTracker.unregisterCallback(callback);
12082 }
James Mattis47db0582021-01-01 14:13:35 -080012083
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012084 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12085 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12086 // Enterprise device can be fully managed like device owner and such use case
12087 // also should be supported. Calling app check for work profile and fully managed device
12088 // is already done in DevicePolicyManager.
12089 // This check is an extra caution to be sure device is fully managed or not.
12090 final UserManager um = mContext.getSystemService(UserManager.class);
12091 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12092 if (um.isManagedProfile(profile.getIdentifier())) {
12093 return true;
12094 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012095 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012096 return false;
12097 }
12098
James Mattis45d81842021-01-10 14:24:24 -080012099 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012100 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012101 *
12102 * See the documentation for the individual preferences for a description of the supported
12103 * behaviors.
12104 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012105 * @param profile If the device owner is set, any profile is allowed.
12106 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012107 * @param preferences the list of profile network preferences for the
12108 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012109 * @param listener an optional listener to listen for completion of the operation.
12110 */
12111 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012112 public void setProfileNetworkPreferences(
12113 @NonNull final UserHandle profile,
12114 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012115 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012116 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012117 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012118
12119 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012120 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12121 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12122 .build();
12123 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012124 }
12125
paulhu3ffffe72021-09-16 10:15:22 +080012126 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012127 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012128 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012129 }
12130 if (profile.getIdentifier() < 0) {
12131 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12132 + "UserHandle.CURRENT not supported)");
12133 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012134 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12135 throw new IllegalArgumentException("Profile must be a managed profile "
12136 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012137 }
paulhuaa0743d2021-05-26 21:56:03 +080012138
Chalard Jean0606fc82022-12-14 20:34:43 +090012139 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012140 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012141 for (final ProfileNetworkPreference preference : preferences) {
12142 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012143 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012144 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012145 switch (preference.getPreference()) {
12146 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12147 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012148 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012149 if (preference.getPreferenceEnterpriseId() != 0) {
12150 throw new IllegalArgumentException(
12151 "Invalid enterprise identifier in setProfileNetworkPreferences");
12152 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012153 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012154 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12155 blockingNonEnterprise = true;
12156 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012157 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12158 allowFallback = false;
12159 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012160 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012161 // This code is needed even though there is a check later on,
12162 // because isRangeAlreadyInPreferenceList assumes that every preference
12163 // has a UID list.
12164 if (hasDefaultPreference) {
12165 throw new IllegalArgumentException(
12166 "Default profile preference should not be set along with other "
12167 + "preference");
12168 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012169 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12170 throw new IllegalArgumentException(
12171 "Invalid enterprise identifier in setProfileNetworkPreferences");
12172 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012173 final Set<UidRange> uidRangeSet =
12174 getUidListToBeAppliedForNetworkPreference(profile, preference);
12175 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12176 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12177 } else {
12178 throw new IllegalArgumentException(
12179 "Overlapping uid range in setProfileNetworkPreferences");
12180 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012181 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012182 nc.addEnterpriseId(
12183 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012184 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12185 break;
12186 default:
12187 throw new IllegalArgumentException(
12188 "Invalid preference in setProfileNetworkPreferences");
12189 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012190 preferenceList.add(new ProfileNetworkPreferenceInfo(
12191 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012192 if (hasDefaultPreference && preferenceList.size() > 1) {
12193 throw new IllegalArgumentException(
12194 "Default profile preference should not be set along with other preference");
12195 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012196 }
12197 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012198 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012199 }
12200
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012201 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12202 @NonNull final UserHandle profile,
12203 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12204 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012205 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12206 profileNetworkPreference.getIncludedUids());
12207
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012208 if (uidRangeSet.size() > 0) {
12209 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12210 throw new IllegalArgumentException(
12211 "Allow uid range is outside the uid range of profile.");
12212 }
12213 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012214 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012215 profileNetworkPreference.getExcludedUids());
12216 if (disallowUidRangeSet.size() > 0) {
12217 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12218 throw new IllegalArgumentException(
12219 "disallow uid range is outside the uid range of profile.");
12220 }
12221 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12222 disallowUidRangeSet);
12223 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012224 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012225 uidRangeSet.add(profileUids);
12226 }
12227 }
12228 return uidRangeSet;
12229 }
12230
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012231 private boolean isEnterpriseIdentifierValid(
12232 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012233 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012234 return true;
12235 }
12236 return false;
12237 }
12238
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012239 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012240 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012241 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012242 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012243 // The NRI for a user should contain the request for capabilities.
12244 // If fallback to default network is needed then NRI should include
12245 // the request for the default network. Create an image of it to
12246 // have the correct UIDs in it (also a request can only be part of one NRI, because
12247 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012248 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12249 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012250 if (pref.allowFallback) {
12251 nrs.add(createDefaultInternetRequestForTransport(
12252 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12253 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012254 if (VDBG) {
12255 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12256 pref.capabilities.getUids()));
12257 }
12258
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012259 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012260 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012261 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012262 result.add(nri);
12263 }
12264 return result;
12265 }
12266
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012267 /**
12268 * Compare if the given UID range sets have the same UIDs.
12269 *
12270 */
12271 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012272 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012273 @NonNull Set<UidRange> uidRangeSet) {
12274 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12275 return false;
12276 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012277 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012278 if (UidRangeUtils.doesRangeSetOverlap(
12279 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12280 return true;
12281 }
12282 }
12283 return false;
12284 }
12285
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012286 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012287 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012288 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012289 /*
12290 * handleSetProfileNetworkPreference is always called for single user.
12291 * preferenceList only contains preferences for different uids within the same user
12292 * (enforced by getUidListToBeAppliedForNetworkPreference).
12293 * Clear all the existing preferences for the user before applying new preferences.
12294 *
12295 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012296 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12297 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012298 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12299 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012300
paulhu74128522021-09-28 02:29:03 +000012301 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12302 addPerAppDefaultNetworkRequests(
12303 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012304 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012305
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012306 // Finally, rematch.
12307 rematchAllNetworksAndRequests();
12308
12309 if (null != listener) {
12310 try {
12311 listener.onComplete();
12312 } catch (RemoteException e) {
12313 loge("Listener for setProfileNetworkPreference has died");
12314 }
12315 }
12316 }
12317
paulhu51f77dc2021-06-07 02:34:20 +000012318 @VisibleForTesting
12319 @NonNull
12320 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12321 @NonNull final Set<Integer> uids) {
12322 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12323 if (uids.size() == 0) {
12324 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12325 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12326 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12327 return nris;
12328 }
12329
12330 final List<NetworkRequest> requests = new ArrayList<>();
12331 // The NRI should be comprised of two layers:
12332 // - The request for the mobile network preferred.
12333 // - The request for the default network, for fallback.
12334 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012335 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012336 requests.add(createDefaultInternetRequestForTransport(
12337 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12338 final Set<UidRange> ranges = new ArraySet<>();
12339 for (final int uid : uids) {
12340 ranges.add(new UidRange(uid, uid));
12341 }
12342 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012343 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012344 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012345 return nris;
12346 }
12347
12348 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012349 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012350 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12351 addPerAppDefaultNetworkRequests(
12352 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012353 // Finally, rematch.
12354 rematchAllNetworksAndRequests();
12355 }
12356
Patrick Rohr2857ac42022-01-21 14:58:16 +010012357 private void handleIngressRateLimitChanged() {
12358 final long oldIngressRateLimit = mIngressRateLimit;
12359 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12360 mContext);
12361 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12362 if (canNetworkBeRateLimited(networkAgent)) {
12363 // If rate limit has previously been enabled, remove the old limit first.
12364 if (oldIngressRateLimit >= 0) {
12365 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12366 }
12367 if (mIngressRateLimit >= 0) {
12368 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12369 mIngressRateLimit);
12370 }
12371 }
12372 }
12373 }
12374
12375 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012376 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012377 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012378
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012379 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12380 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12381 // internet connectivity can be rate limited.
12382 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12383 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012384 return false;
12385 }
12386
12387 final String iface = networkAgent.linkProperties.getInterfaceName();
12388 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012389 // This may happen in tests, but if there is no interface then there is nothing that
12390 // can be rate limited.
12391 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012392 return false;
12393 }
12394 return true;
12395 }
12396
James Mattis45d81842021-01-10 14:24:24 -080012397 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012398 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12399 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012400 }
12401
12402 /**
12403 * Used by automotive devices to set the network preferences used to direct traffic at an
12404 * application level as per the given OemNetworkPreferences. An example use-case would be an
12405 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12406 * vehicle via a particular network.
12407 *
12408 * Calling this will overwrite the existing preference.
12409 *
James Mattisda32cfe2021-01-26 16:23:52 -080012410 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012411 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012412 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012413 */
James Mattis47db0582021-01-01 14:13:35 -080012414 @Override
James Mattis45d81842021-01-10 14:24:24 -080012415 public void setOemNetworkPreference(
12416 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012417 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012418
James Mattisfa270db2021-05-31 17:11:10 -070012419 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12420 // Only bypass the permission/device checks if this is a valid test request.
12421 if (isValidTestOemNetworkPreference(preference)) {
12422 enforceManageTestNetworksPermission();
12423 } else {
12424 enforceAutomotiveDevice();
12425 enforceOemNetworkPreferencesPermission();
12426 validateOemNetworkPreferences(preference);
12427 }
James Mattis45d81842021-01-10 14:24:24 -080012428
James Mattis45d81842021-01-10 14:24:24 -080012429 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12430 new Pair<>(preference, listener)));
12431 }
12432
James Mattisfa270db2021-05-31 17:11:10 -070012433 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012434 * Sets the specified UIDs to get/receive the VPN as the only default network.
12435 *
12436 * Calling this will overwrite the existing network preference for this session, and the
12437 * specified UIDs won't get any default network when no VPN is connected.
12438 *
12439 * @param session The VPN session which manages the passed UIDs.
12440 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12441 * setting for this session if the array is empty. Null is not allowed, the
12442 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12443 * @hide
12444 */
12445 @Override
12446 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12447 Objects.requireNonNull(ranges);
12448 enforceNetworkStackOrSettingsPermission();
12449 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12450 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12451 throw new IllegalArgumentException(
12452 "setVpnNetworkPreference: Passed UID ranges overlap");
12453 }
12454
12455 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12456 new VpnNetworkPreferenceInfo(session,
12457 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12458 }
12459
12460 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12461 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12462
12463 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12464 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12465
12466 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12467 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12468 // Finally, rematch.
12469 rematchAllNetworksAndRequests();
12470 }
12471
12472 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12473 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12474 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12475 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12476 final List<NetworkRequest> requests = new ArrayList<>();
12477 // Request VPN only, so other networks won't be the fallback options when VPN is not
12478 // connected temporarily.
12479 requests.add(createVpnRequest());
12480 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12481 setNetworkRequestUids(requests, uidRanges);
12482 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12483 }
12484 return nris;
12485 }
12486
12487 /**
James Mattisfa270db2021-05-31 17:11:10 -070012488 * Check the validity of an OEM network preference to be used for testing purposes.
12489 * @param preference the preference to validate
12490 * @return true if this is a valid OEM network preference test request.
12491 */
12492 private boolean isValidTestOemNetworkPreference(
12493 @NonNull final OemNetworkPreferences preference) {
12494 // Allow for clearing of an existing OemNetworkPreference used for testing.
12495 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12496 // changes after this check is complete. This is an unlikely scenario as calling of this API
12497 // is controlled by the OEM therefore the added complexity is not worth adding given those
12498 // circumstances. That said, it is an edge case to be aware of hence this comment.
12499 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12500 && isTestOemNetworkPreference(mOemNetworkPreferences);
12501 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12502 }
12503
12504 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12505 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12506 return prefMap.size() == 1
12507 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12508 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12509 }
12510
James Mattis45d81842021-01-10 14:24:24 -080012511 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12512 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12513 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012514 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12515 throw new IllegalArgumentException(
12516 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12517 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012518 }
12519 }
12520 }
12521
12522 private void handleSetOemNetworkPreference(
12523 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012524 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012525 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12526 if (DBG) {
12527 log("set OEM network preferences :" + preference.toString());
12528 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012529
James Mattiscb1e0362021-04-06 17:07:42 -070012530 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012531 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12532 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12533 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012534 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012535
12536 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012537 try {
12538 listener.onComplete();
12539 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012540 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012541 }
James Mattis45d81842021-01-10 14:24:24 -080012542 }
12543 }
12544
paulhu74128522021-09-28 02:29:03 +000012545 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012546 // Skip the requests which are set by other network preference. Because the uid range rules
12547 // should stay in netd.
12548 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012549 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012550 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012551 }
12552
James Mattis3ce3d3c2021-02-09 18:18:28 -080012553 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12554 ensureRunningOnConnectivityServiceThread();
12555 mDefaultNetworkRequests.addAll(nris);
12556 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12557 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012558 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012559 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12560 nrisToRegister.addAll(
12561 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12562 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012563 }
12564
12565 /**
12566 * All current requests that are tracking the default network need to be assessed as to whether
12567 * or not the current set of per-application default requests will be changing their default
12568 * network. If so, those requests will need to be updated so that they will send callbacks for
12569 * default network changes at the appropriate time. Additionally, those requests tracking the
12570 * default that were previously updated by this flow will need to be reassessed.
12571 * @return the nris which will need to be updated.
12572 */
12573 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12574 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12575 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12576 // same nri in the map's values for each of its NetworkRequest objects.
12577 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012578 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012579 // Include this nri if it is currently being tracked.
12580 if (isPerAppTrackedNri(nri)) {
12581 defaultCallbackRequests.add(nri);
12582 continue;
12583 }
12584 // We only track callbacks for requests tracking the default.
12585 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12586 continue;
12587 }
12588 // Include this nri if it will be tracked by the new per-app default requests.
12589 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012590 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012591 if (isNriGoingToBeTracked) {
12592 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012593 }
12594 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012595 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012596 }
12597
James Mattis3ce3d3c2021-02-09 18:18:28 -080012598 /**
12599 * Create nris for those network requests that are currently tracking the default network that
12600 * are being controlled by a per-application default.
12601 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12602 * foundation when creating the nri. Important items include the calling uid's original
12603 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12604 * requests are assumed to have already been validated as needing to be updated.
12605 * @return the Set of nris to use when registering network requests.
12606 */
12607 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12608 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12609 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12610 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12611 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012612 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012613
Chalard Jean9473c982021-07-29 20:03:04 +090012614 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012615 if (trackingNri == mDefaultRequest) {
12616 callbackRequestsToRegister.add(new NetworkRequestInfo(
12617 callbackRequest,
12618 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12619 continue;
12620 }
12621
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012622 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012623 callbackRequestsToRegister.add(new NetworkRequestInfo(
12624 callbackRequest,
12625 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012626 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012627 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012628 }
12629 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012630 }
12631
Chalard Jean17215832021-03-01 14:06:28 +090012632 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12633 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012634 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012635 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012636 }
12637 }
12638
James Mattis45d81842021-01-10 14:24:24 -080012639 /**
12640 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12641 */
12642 @VisibleForTesting
12643 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012644 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012645 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012646 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012647 final SparseArray<Set<Integer>> uids =
12648 createUidsFromOemNetworkPreferences(preference);
12649 for (int i = 0; i < uids.size(); i++) {
12650 final int key = uids.keyAt(i);
12651 final Set<Integer> value = uids.valueAt(i);
12652 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12653 // No need to add an nri without any requests.
12654 if (0 == nri.mRequests.size()) {
12655 continue;
12656 }
12657 nris.add(nri);
12658 }
12659
12660 return nris;
12661 }
12662
12663 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12664 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012665 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012666 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012667 final List<UserHandle> users =
12668 mContext.getSystemService(UserManager.class).getUserHandles(true);
12669 if (null == users || users.size() == 0) {
12670 if (VDBG || DDBG) {
12671 log("No users currently available for setting the OEM network preference.");
12672 }
James Mattisb6b6a432021-06-01 22:30:36 -070012673 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012674 }
James Mattis45d81842021-01-10 14:24:24 -080012675 for (final Map.Entry<String, Integer> entry :
12676 preference.getNetworkPreferences().entrySet()) {
12677 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012678 // Add the rules for all users as this policy is device wide.
12679 for (final UserHandle user : users) {
12680 try {
12681 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12682 if (!prefToUids.contains(pref)) {
12683 prefToUids.put(pref, new ArraySet<>());
12684 }
12685 prefToUids.get(pref).add(uid);
12686 } catch (PackageManager.NameNotFoundException e) {
12687 // Although this may seem like an error scenario, it is ok that uninstalled
12688 // packages are sent on a network preference as the system will watch for
12689 // package installations associated with this network preference and update
12690 // accordingly. This is done to minimize race conditions on app install.
12691 continue;
James Mattis45d81842021-01-10 14:24:24 -080012692 }
James Mattis45d81842021-01-10 14:24:24 -080012693 }
12694 }
James Mattisb6b6a432021-06-01 22:30:36 -070012695 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012696 }
12697
12698 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12699 @OemNetworkPreferences.OemNetworkPreference final int preference,
12700 @NonNull final Set<Integer> uids) {
12701 final List<NetworkRequest> requests = new ArrayList<>();
12702 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12703 switch (preference) {
12704 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12705 requests.add(createUnmeteredNetworkRequest());
12706 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012707 requests.add(createDefaultInternetRequestForTransport(
12708 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012709 break;
12710 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12711 requests.add(createUnmeteredNetworkRequest());
12712 requests.add(createOemPaidNetworkRequest());
12713 break;
12714 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12715 requests.add(createOemPaidNetworkRequest());
12716 break;
12717 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12718 requests.add(createOemPrivateNetworkRequest());
12719 break;
James Mattisfa270db2021-05-31 17:11:10 -070012720 case OEM_NETWORK_PREFERENCE_TEST:
12721 requests.add(createUnmeteredNetworkRequest());
12722 requests.add(createTestNetworkRequest());
12723 requests.add(createDefaultRequest());
12724 break;
12725 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12726 requests.add(createTestNetworkRequest());
12727 break;
James Mattis45d81842021-01-10 14:24:24 -080012728 default:
12729 // This should never happen.
12730 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12731 + " called with invalid preference of " + preference);
12732 }
12733
James Mattisfa270db2021-05-31 17:11:10 -070012734 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012735 for (final int uid : uids) {
12736 ranges.add(new UidRange(uid, uid));
12737 }
12738 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012739 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012740 }
12741
12742 private NetworkRequest createUnmeteredNetworkRequest() {
12743 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12744 .addCapability(NET_CAPABILITY_NOT_METERED)
12745 .addCapability(NET_CAPABILITY_VALIDATED);
12746 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12747 }
12748
12749 private NetworkRequest createOemPaidNetworkRequest() {
12750 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12751 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12752 .addCapability(NET_CAPABILITY_OEM_PAID)
12753 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12754 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12755 }
12756
12757 private NetworkRequest createOemPrivateNetworkRequest() {
12758 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12759 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12760 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12761 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12762 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12763 }
12764
12765 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012766 final NetworkCapabilities netcap = new NetworkCapabilities();
12767 netcap.addCapability(NET_CAPABILITY_INTERNET);
12768 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12769 return netcap;
12770 }
12771
12772 private NetworkRequest createTestNetworkRequest() {
12773 final NetworkCapabilities netcap = new NetworkCapabilities();
12774 netcap.clearAll();
12775 netcap.addTransportType(TRANSPORT_TEST);
12776 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012777 }
James Mattis47db0582021-01-01 14:13:35 -080012778 }
markchien738ad912021-12-09 18:15:45 +080012779
Ken Chen24330172023-10-20 13:02:14 +080012780 @TargetApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080012781 @Override
Junyu Laidf210362023-10-24 02:47:50 +000012782 public void setDataSaverEnabled(final boolean enable) {
12783 enforceNetworkStackOrSettingsPermission();
12784 try {
12785 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
12786 if (!ret) {
12787 throw new IllegalStateException("Error when changing iptables: " + enable);
12788 }
12789 } catch (RemoteException e) {
12790 // Lack of permission or binder errors.
12791 throw new IllegalStateException(e);
12792 }
Ken Chen24330172023-10-20 13:02:14 +080012793
12794 try {
12795 mBpfNetMaps.setDataSaverEnabled(enable);
12796 } catch (ServiceSpecificException | UnsupportedOperationException e) {
12797 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
12798 }
Junyu Laidf210362023-10-24 02:47:50 +000012799 }
12800
12801 @Override
markchien738ad912021-12-09 18:15:45 +080012802 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12803 enforceNetworkStackOrSettingsPermission();
12804
12805 try {
12806 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012807 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012808 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012809 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012810 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012811 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012812 throw new IllegalStateException(e);
12813 }
12814 }
12815
12816 @Override
12817 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12818 enforceNetworkStackOrSettingsPermission();
12819
12820 try {
12821 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012822 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012823 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012824 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012825 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012826 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012827 throw new IllegalStateException(e);
12828 }
12829 }
markchiene1561fa2021-12-09 22:00:56 +080012830
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012831 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
12832 throws PackageManager.NameNotFoundException {
12833 final PackageManager pm = mContext.getPackageManager();
12834 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12835 if (appId < Process.FIRST_APPLICATION_UID) {
12836 throw new RuntimeException("Can't set package firewall rule for system app "
12837 + packageName + " with appId " + appId);
12838 }
12839 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
12840 final int uid = uh.getUid(appId);
12841 setUidFirewallRule(chain, uid, rule);
12842 }
12843 return appId;
12844 }
12845
markchiene1561fa2021-12-09 22:00:56 +080012846 @Override
markchien3c04e662022-03-22 16:29:56 +080012847 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012848 enforceNetworkStackOrSettingsPermission();
12849
markchien3c04e662022-03-22 16:29:56 +080012850 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12851 int firewallRule = getFirewallRuleType(chain, rule);
12852
12853 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12854 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12855 }
12856
markchiene1561fa2021-12-09 22:00:56 +080012857 try {
markchien3c04e662022-03-22 16:29:56 +080012858 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012859 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012860 throw new IllegalStateException(e);
12861 }
12862 }
markchien98a6f952022-01-13 23:43:53 +080012863
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012864 private int getPackageFirewallRule(final int chain, final String packageName)
12865 throws PackageManager.NameNotFoundException {
12866 final PackageManager pm = mContext.getPackageManager();
12867 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12868 return getUidFirewallRule(chain, appId);
12869 }
12870
Motomu Utsumi900b8062023-01-19 16:16:49 +090012871 @Override
12872 public int getUidFirewallRule(final int chain, final int uid) {
12873 enforceNetworkStackOrSettingsPermission();
12874 return mBpfNetMaps.getUidRule(chain, uid);
12875 }
12876
markchien3c04e662022-03-22 16:29:56 +080012877 private int getFirewallRuleType(int chain, int rule) {
12878 final int defaultRule;
12879 switch (chain) {
12880 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012881 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12882 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012883 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012884 defaultRule = FIREWALL_RULE_ALLOW;
12885 break;
12886 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12887 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12888 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12889 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080012890 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080012891 defaultRule = FIREWALL_RULE_DENY;
12892 break;
12893 default:
12894 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12895 }
12896 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12897
12898 return rule;
12899 }
12900
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012901 private void closeSocketsForFirewallChainLocked(final int chain)
12902 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080012903 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012904 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12905 // So, close all non-system socket owned by uids that are not explicitly allowed
12906 Set<Range<Integer>> ranges = new ArraySet<>();
12907 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12908 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12909 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12910 } else {
12911 // Denylist means the firewall allows all by default, uids must be explicitly denied
12912 // So, close socket owned by uids that are explicitly denied
12913 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12914 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12915 }
12916 }
12917
markchien98a6f952022-01-13 23:43:53 +080012918 @Override
12919 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12920 enforceNetworkStackOrSettingsPermission();
12921
12922 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012923 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012924 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012925 throw new IllegalStateException(e);
12926 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012927
Chalard Jeandf29a852023-05-29 17:02:43 +090012928 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012929 try {
12930 closeSocketsForFirewallChainLocked(chain);
12931 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12932 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12933 }
12934 }
markchien98a6f952022-01-13 23:43:53 +080012935 }
12936
markchien00a0bed2022-01-13 23:46:13 +080012937 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012938 public boolean getFirewallChainEnabled(final int chain) {
12939 enforceNetworkStackOrSettingsPermission();
12940
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012941 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012942 }
12943
12944 @Override
markchien00a0bed2022-01-13 23:46:13 +080012945 public void replaceFirewallChain(final int chain, final int[] uids) {
12946 enforceNetworkStackOrSettingsPermission();
12947
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012948 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012949 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012950
12951 @Override
12952 public IBinder getCompanionDeviceManagerProxyService() {
12953 enforceNetworkStackPermission(mContext);
12954 return mCdmps;
12955 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090012956
12957 @Override
12958 public IBinder getRoutingCoordinatorService() {
12959 enforceNetworkStackPermission(mContext);
12960 return mRoutingCoordinatorService;
12961 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012962}