blob: ada5860a0b76aa6b4c706fc27417e71049af74e3 [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;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900139import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900140import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700141import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800142import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800143import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800144import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900145import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800146import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900147import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800148import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900149import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800150import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700151import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900152import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800153import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800154import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800155import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800156import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800157import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900158import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900159import android.net.INetworkMonitor;
160import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900161import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900162import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700163import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800164import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900165import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900166import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900167import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800168import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900169import android.net.LocalNetworkConfig;
Charles He9369e612017-05-15 17:07:18 +0100170import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800171import android.net.NativeNetworkConfig;
172import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800173import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700174import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700175import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900176import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700177import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800178import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700179import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900180import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900181import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000182import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900183import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700184import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900185import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700186import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900187import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700188import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800189import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900190import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700191import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000192import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800193import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900194import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800195import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400196import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700197import android.net.QosCallbackException;
198import android.net.QosFilter;
199import android.net.QosSocketFilter;
200import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700201import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800202import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800203import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800204import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900205import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400206import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800207import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800208import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400209import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800210import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900211import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900212import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900213import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900214import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800215import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900216import android.net.networkstack.ModuleNetworkStackClient;
217import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900218import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800219import android.net.resolv.aidl.DnsHealthEventParcel;
220import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
221import android.net.resolv.aidl.Nat64PrefixEventParcel;
222import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900223import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900224import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800225import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800226import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800227import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700228import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000229import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700231import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700232import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800233import android.os.Looper;
234import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700235import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700236import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900237import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800238import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700239import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700240import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800241import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700242import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900243import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900244import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700245import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700246import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400247import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800248import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900249import android.stats.connectivity.MeteredState;
250import android.stats.connectivity.RequestType;
251import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900252import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700253import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700254import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700255import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800256import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900257import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000258import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600259import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900260import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900261import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700262import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700263import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900264import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800265
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800266import androidx.annotation.RequiresApi;
267
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900268import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400269import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400270import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700271import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900272import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900273import com.android.metrics.ConnectionDurationForTransports;
274import com.android.metrics.ConnectionDurationPerTransports;
275import com.android.metrics.ConnectivitySampleMetricsHelper;
276import com.android.metrics.ConnectivityStateSample;
277import com.android.metrics.NetworkCountForTransports;
278import com.android.metrics.NetworkCountPerTransports;
279import com.android.metrics.NetworkDescription;
280import com.android.metrics.NetworkList;
281import com.android.metrics.NetworkRequestCount;
282import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800283import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900284import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800285import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000286import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900287import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800288import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900289import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900290import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100291import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900292import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
293import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900294import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800295import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800296import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100297import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000298import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800299import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
300import com.android.networkstack.apishim.ConstantsShim;
301import com.android.networkstack.apishim.common.BroadcastOptionsShim;
302import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900303import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900304import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000305import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900306import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800307import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800308import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900309import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900310import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900311import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500312import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700313import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900314import com.android.server.connectivity.FullScore;
Junyu Laif8dba342023-10-12 17:01:03 +0800315import com.android.server.connectivity.HandlerUtils;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900316import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900317import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000318import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100319import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700320import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900321import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700322import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600323import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900324import com.android.server.connectivity.NetworkNotificationManager;
325import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900326import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900327import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900328import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700329import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900330import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900331import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700332import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800333import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000334import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800335import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600336
Josh Gao461a1222020-06-16 15:58:11 -0700337import libcore.io.IoUtils;
338
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900339import org.xmlpull.v1.XmlPullParserException;
340
The Android Open Source Project28527d22009-03-03 19:31:44 -0800341import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100342import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900343import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800344import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900345import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700346import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700347import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900348import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900349import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700350import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700351import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700352import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700353import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800354import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900355import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800356import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700357import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700358import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700359import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700360import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900361import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700362import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900363import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600364import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900365import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600366import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900367import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900368import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800369
370/**
371 * @hide
372 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800373public class ConnectivityService extends IConnectivityManager.Stub
374 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900375 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800376
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900377 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900378 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900379 private static final String NETWORK_ARG = "networks";
380 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800381 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900382
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900383 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900384 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
385 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800386
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900387 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700388
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100389 /**
390 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
391 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800392 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100393 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
394 * (preferably via runtime resource overlays).
395 */
396 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
397 "http://connectivitycheck.gstatic.com/generate_204";
398
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700399 // TODO: create better separation between radio types and network types
400
Robert Greenwalt2034b912009-08-12 16:08:25 -0700401 // how long to wait before switching back to a radio's default network
402 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
403 // system property that can override the above value
404 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
405 "android.telephony.apn-restore";
406
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900407 // How long to wait before putting up a "This network doesn't have an Internet connection,
408 // connect anyway?" dialog after the user selects a network that doesn't validate.
409 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
410
Chalard Jean5fb43c72022-09-08 19:03:14 +0900411 // How long to wait before considering that a network is bad in the absence of any form
412 // of connectivity (valid, partial, captive portal). If none has been detected after this
413 // delay, the stack considers this network bad, which may affect how it's handled in ranking
414 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900415 // Timeout in case the "actively prefer bad wifi" feature is on
416 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
417 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900418 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900419
junyulai0ac374f2020-12-14 18:41:52 +0800420 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900421 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
422 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800423 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700424
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800425 // Delimiter used when creating the broadcast delivery group for sending
426 // CONNECTIVITY_ACTION broadcast.
427 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
428
he_won.hwang881307a2022-03-15 21:23:52 +0900429 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900430 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900431
Daniel Brightf9e945b2020-06-15 16:10:01 -0700432 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900433 @VisibleForTesting
434 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700435
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900436 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700437 @VisibleForTesting
438 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900439
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900440 @VisibleForTesting
441 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800442 @VisibleForTesting
443 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900444 // True if the cell radio of the device is capable of time-sharing.
445 @VisibleForTesting
446 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900447
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800448 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800449 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800450 private final int mReleasePendingIntentDelayMs;
451
Chalard Jean46bfbf02022-02-02 00:56:25 +0900452 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900453
Motomu Utsumif360aa62023-01-30 17:52:20 +0900454 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700455
Chalard Jean9473c982021-07-29 20:03:04 +0900456 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800457 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700458 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800459 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700460
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900461 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700462
junyulaif2c67e42018-08-07 19:50:45 +0800463 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000464 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
465 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800466 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900467 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800468
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900469 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900470 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000471 private final int mWakeUpMark;
472 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000473 // The Context is created for UserHandle.ALL.
474 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900475 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900476 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700477 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700478 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800479
Chenbo Feng15416292018-11-08 17:36:21 -0800480 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800481 protected IDnsResolver mDnsResolver;
482 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800483 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700484 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900485 private final NetworkStatsManager mStatsManager;
486 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800487 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700488
Benedict Wong493e04b2018-11-09 14:45:34 -0800489 /**
490 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
491 * instances.
492 */
493 @GuardedBy("mTNSLock")
494 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800495 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800496
497 private final Object mTNSLock = new Object();
498
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700499 private String mCurrentTcpBufferSizes;
500
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900501 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000502 new Class[] {
503 ConnectivityService.class,
504 NetworkAgent.class,
505 NetworkAgentInfo.class,
506 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900507
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500508 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400509 // Tear down networks that have no chance (e.g. even if validated) of becoming
510 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500511 // all networks have been rematched against all NetworkRequests.
512 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400513 // Don't reap networks. This should be passed when some networks have not yet been
514 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500515 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900516 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500517
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900518 private enum UnneededFor {
519 LINGER, // Determine whether this network is unneeded and should be lingered.
520 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
521 }
522
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700523 /**
paulhuaa0743d2021-05-26 21:56:03 +0800524 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800525 * should have priority. The order is passed to netd which will use it together
526 * with UID ranges to generate the corresponding IP rule. This serves to
527 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800528 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800529 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000530 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800531 *
paulhu48291862021-07-14 14:53:57 +0800532 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
533 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800534 */
paulhu48291862021-07-14 14:53:57 +0800535 // Used when sending to netd to code for "no order".
536 static final int PREFERENCE_ORDER_NONE = 0;
537 // Order for requests that don't code for a per-app preference. As it is
538 // out of the valid range, the corresponding order should be
539 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800540 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800541 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800542 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800543 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
544 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800545 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800546 static final int PREFERENCE_ORDER_OEM = 10;
547 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800548 // See {@link #setProfileNetworkPreference}.
549 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800550 static final int PREFERENCE_ORDER_PROFILE = 20;
551 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800552 // better scores are connected.
553 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800554 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800555 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900556 // Preference order that signifies the network shouldn't be set as a default network for
557 // the UIDs, only give them access to it. TODO : replace this with a boolean
558 // in NativeUidRangeConfig
559 @VisibleForTesting
560 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
561 // Bound for the lowest valid preference order.
562 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800563
564 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700565 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700566 * from one net to another. Clear happens when we get a new
567 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
568 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700569 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700570 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700571
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700572 /**
573 * used internally to reload global proxy settings
574 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700575 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700576
Robert Greenwalt34848c02011-03-25 13:09:25 -0700577 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400578 * PAC manager has received new port.
579 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800580 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400581
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700582 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900583 * used internally when registering NetworkProviders
584 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700585 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900586 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700587
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700588 /**
589 * used internally when registering NetworkAgents
590 * obj = Messenger
591 */
592 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
593
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700594 /**
595 * used to add a network request
596 * includes a NetworkRequestInfo
597 */
598 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
599
600 /**
601 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900602 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700603 * cancel it.
604 * includes a NetworkRequestInfo
605 */
606 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
607
608 /**
609 * used to add a network listener - no request
610 * includes a NetworkRequestInfo
611 */
612 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
613
614 /**
615 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400616 * arg1 = UID of caller
617 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700618 */
619 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
620
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700621 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900622 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700623 * obj = Messenger
624 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900625 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700626
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700627 /**
628 * used internally to expire a wakelock when transitioning
629 * from one net to another. Expire happens when we fail to find
630 * a new network (typically after 1 minute) -
631 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
632 * a replacement network.
633 */
634 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
635
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700636 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800637 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400638 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800639 */
640 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
641
642 /**
643 * used to remove a pending intent and its associated network request.
644 * arg1 = UID of caller
645 * obj = PendingIntent
646 */
647 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
648
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900649 /**
650 * used to specify whether a network should be used even if unvalidated.
651 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
652 * arg2 = whether to remember this choice in the future (1 or 0)
653 * obj = network
654 */
655 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
656
657 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700658 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900659 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700660 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900661
Paul Jensenc8873fc2015-06-17 14:15:39 -0400662 /**
663 * used to add a network listener with a pending intent
664 * obj = NetworkRequestInfo
665 */
666 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
667
Hugo Benichid6b510a2017-04-06 17:22:18 +0900668 /**
669 * used to specify whether a network should not be penalized when it becomes unvalidated.
670 */
671 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
672
673 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700674 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900675 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700676 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900677
Erik Kline31b4a9e2018-01-11 21:07:29 +0900678 // Handle changes in Private DNS settings.
679 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
680
dalyk1720e542018-03-05 12:42:22 -0500681 // Handle private DNS validation status updates.
682 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
683
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900684 /**
685 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
686 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800687 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
688 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
689 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900690 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900691 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900692
693 /**
694 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
695 * config was resolved.
696 * obj = PrivateDnsConfig
697 * arg2 = netid
698 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900699 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900700
701 /**
702 * Request ConnectivityService display provisioning notification.
703 * arg1 = Whether to make the notification visible.
704 * arg2 = NetID.
705 * obj = Intent to be launched when notification selected by user, null if !arg1.
706 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900707 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900708
709 /**
lucaslin2240ef62019-03-12 13:08:03 +0800710 * Used to specify whether a network should be used even if connectivity is partial.
711 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
712 * false)
713 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
714 * obj = network
715 */
lucaslin444d43a2020-02-20 16:56:59 +0800716 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800717
718 /**
lucasline117e2e2019-10-22 18:27:33 +0800719 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
720 * Both of the arguments are bitmasks, and the value of bits come from
721 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900722 * arg1 = unused
723 * arg2 = netId
724 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800725 */
lucaslin444d43a2020-02-20 16:56:59 +0800726 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800727
728 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900729 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
730 * arg1 = unused
731 * arg2 = netId
732 * obj = captive portal data
733 */
lucaslin444d43a2020-02-20 16:56:59 +0800734 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900735
736 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900737 * Used by setRequireVpnForUids.
738 * arg1 = whether the specified UID ranges are required to use a VPN.
739 * obj = Array of UidRange objects.
740 */
741 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
742
743 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900744 * Used internally when setting the default networks for OemNetworkPreferences.
745 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800746 */
747 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
748
749 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800750 * Used to indicate the system default network becomes active.
751 */
752 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
753
754 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900755 * Used internally when setting a network preference for a user profile.
756 * obj = Pair<ProfileNetworkPreference, Listener>
757 */
758 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
759
760 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000761 * Event to specify that reasons for why an uid is blocked changed.
762 * arg1 = uid
763 * arg2 = blockedReasons
764 */
765 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
766
767 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900768 * Event to register a new network offer
769 * obj = NetworkOffer
770 */
771 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
772
773 /**
774 * Event to unregister an existing network offer
775 * obj = INetworkOfferCallback
776 */
777 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
778
779 /**
paulhu51f77dc2021-06-07 02:34:20 +0000780 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
781 */
782 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
783
784 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800785 * Event to set temporary allow bad wifi within a limited time to override
786 * {@code config_networkAvoidBadWifi}.
787 */
788 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
789
790 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100791 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
792 */
793 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
794
795 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900796 * The initial evaluation period is over for this network.
797 *
798 * If no form of connectivity has been found on this network (valid, partial, captive portal)
799 * then the stack will now consider it to have been determined bad.
800 */
801 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
802
803 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000804 * Used internally when the user does not want the network from captive portal app.
805 * obj = Network
806 */
807 private static final int EVENT_USER_DOES_NOT_WANT = 58;
808
809 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000810 * Event to set VPN as preferred network for specific apps.
811 * obj = VpnNetworkPreferenceInfo
812 */
813 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
814
815 /**
chiachangwange0192a72023-02-06 13:25:01 +0000816 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
817 */
818 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
819
820 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000821 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
822 */
823 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
824
825 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900826 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
827 * should be shown.
828 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900829 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900830
831 /**
832 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
833 * should be hidden.
834 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900835 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900836
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800837 /**
838 * The maximum alive time to allow bad wifi configuration for testing.
839 */
840 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
841
Patrick Rohr2857ac42022-01-21 14:58:16 +0100842 /**
chiachangwange0192a72023-02-06 13:25:01 +0000843 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
844 * testing.
845 */
846 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
847
848 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100849 * The priority of the tc police rate limiter -- smaller value is higher priority.
850 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
851 */
852 private static final short TC_PRIO_POLICE = 1;
853
854 /**
855 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
856 */
857 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700858 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100859
Hugo Benichi47011212017-03-30 10:46:05 +0900860 private static String eventName(int what) {
861 return sMagicDecoderRing.get(what, Integer.toString(what));
862 }
863
paulhua10d8212020-11-10 15:32:56 +0800864 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900865 final DnsResolverServiceManager dsm = context.getSystemService(
866 DnsResolverServiceManager.class);
867 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800868 }
869
Cody Kesting73708bf2019-12-18 10:57:50 -0800870 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900871 @VisibleForTesting
872 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700873 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700874 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700875 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700876 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800877 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
878 @VisibleForTesting
879 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
880
Erik Kline32120082017-12-13 19:40:49 +0900881 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900882 @VisibleForTesting
883 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700884
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400885 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800886 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400887
Chalard Jean46bfbf02022-02-02 00:56:25 +0900888 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800889 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700890
Chalard Jean5d70ba42018-06-07 16:44:04 +0900891 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
892 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800893 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400894
Erik Kline05f2b402015-04-30 12:58:40 +0900895 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700896
Chalard Jean46bfbf02022-02-02 00:56:25 +0900897 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400898
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700899 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900900 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700901
Valentin Iftime9fa35092019-09-24 13:32:13 +0200902 private Set<String> mWolSupportedInterfaces;
903
Roshan Pius08c94fb2020-01-16 12:17:17 -0800904 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800905 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800906 private final AppOpsManager mAppOpsManager;
907
908 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400909
chiachangwang3d60bac2023-01-17 14:38:08 +0000910 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900911 private final QosCallbackTracker mQosCallbackTracker;
912 private final NetworkNotificationManager mNotifier;
913 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900914
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700915 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800916 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700917
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900918 // Sequence number for NetworkProvider IDs.
919 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
920 NetworkProvider.FIRST_PROVIDER_ID);
921
Erik Klineedf878b2015-07-09 18:24:03 +0900922 // NetworkRequest activity String log entries.
923 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
924 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
925
Hugo Benichid159fdd2016-07-11 11:05:12 +0900926 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900927 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900928 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
929
Hugo Benichi47011212017-03-30 10:46:05 +0900930 private static final int MAX_WAKELOCK_LOGS = 20;
931 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900932 private int mTotalWakelockAcquisitions = 0;
933 private int mTotalWakelockReleases = 0;
934 private long mTotalWakelockDurationMs = 0;
935 private long mMaxWakelockDurationMs = 0;
936 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900937
Hugo Benichi208c0102016-07-28 17:53:06 +0900938 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900939
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700940 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900941 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700942
Erik Kline95ecfee2016-10-02 18:02:14 +0900943 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900944 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900945
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900946 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800947 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
948 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800949
Patrick Rohr2857ac42022-01-21 14:58:16 +0100950 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
951 // configured via {@link
952 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
953 // Only the handler thread is allowed to access this field.
954 private long mIngressRateLimit = -1;
955
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900956 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
957 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900958 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900959 @GuardedBy("mSelfCertifiedCapabilityCache")
960 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
961 mSelfCertifiedCapabilityCache = new HashMap<>();
962
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900963 // Flag to enable the feature of closing frozen app sockets.
964 private final boolean mDestroyFrozenSockets;
965
966 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
967 private final boolean mDelayDestroyFrozenSockets;
968
969 // Uids that ConnectivityService is pending to close sockets of.
970 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
971
Robert Greenwalt802c1102014-06-02 15:32:02 -0700972 /**
973 * Implements support for the legacy "one network per network type" model.
974 *
975 * We used to have a static array of NetworkStateTrackers, one for each
976 * network type, but that doesn't work any more now that we can have,
977 * for example, more that one wifi network. This class stores all the
978 * NetworkAgentInfo objects that support a given type, but the legacy
979 * API will only see the first one.
980 *
981 * It serves two main purposes:
982 *
983 * 1. Provide information about "the network for a given type" (since this
984 * API only supports one).
985 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
986 * the first network for a given type changes, or if the default network
987 * changes.
988 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900989 @VisibleForTesting
990 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900991
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900992 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900993 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900994
Robert Greenwalt802c1102014-06-02 15:32:02 -0700995 /**
996 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
997 * Each list holds references to all NetworkAgentInfos that are used to
998 * satisfy requests for that network type.
999 *
1000 * This array is built out at startup such that an unsupported network
1001 * doesn't get an ArrayList instance, making this a tristate:
1002 * unsupported, supported but not active and active.
1003 *
1004 * The actual lists are populated when we scan the network types that
1005 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001006 *
1007 * Threading model:
1008 * - addSupportedType() is only called in the constructor
1009 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1010 * They are therefore not thread-safe with respect to each other.
1011 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1012 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001013 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001014 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001015 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001016 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001017 @NonNull
1018 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001019
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001020 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1021 // an entry have no timer (equivalent to -1). Lazily loaded.
1022 @NonNull
1023 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1024
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001025 LegacyTypeTracker(@NonNull ConnectivityService service) {
1026 mService = service;
1027 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001028 }
1029
Chiachang Wang3bc52762021-11-25 14:17:57 +08001030 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1031 // addressed.
1032 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001033 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1034 final PackageManager pm = ctx.getPackageManager();
1035 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1036 addSupportedType(TYPE_WIFI);
1037 }
1038 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1039 addSupportedType(TYPE_WIFI_P2P);
1040 }
1041 if (tm.isDataCapable()) {
1042 // Telephony does not have granular support for these types: they are either all
1043 // supported, or none is supported
1044 addSupportedType(TYPE_MOBILE);
1045 addSupportedType(TYPE_MOBILE_MMS);
1046 addSupportedType(TYPE_MOBILE_SUPL);
1047 addSupportedType(TYPE_MOBILE_DUN);
1048 addSupportedType(TYPE_MOBILE_HIPRI);
1049 addSupportedType(TYPE_MOBILE_FOTA);
1050 addSupportedType(TYPE_MOBILE_IMS);
1051 addSupportedType(TYPE_MOBILE_CBS);
1052 addSupportedType(TYPE_MOBILE_IA);
1053 addSupportedType(TYPE_MOBILE_EMERGENCY);
1054 }
1055 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1056 addSupportedType(TYPE_BLUETOOTH);
1057 }
1058 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1059 // TYPE_PROXY is only used on Wear
1060 addSupportedType(TYPE_PROXY);
1061 }
1062 // Ethernet is often not specified in the configs, although many devices can use it via
1063 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001064 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001065 addSupportedType(TYPE_ETHERNET);
1066 }
1067
1068 // Always add TYPE_VPN as a supported type
1069 addSupportedType(TYPE_VPN);
1070 }
1071
1072 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001073 if (mTypeLists[type] != null) {
1074 throw new IllegalStateException(
1075 "legacy list for type " + type + "already initialized");
1076 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001077 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001078 }
1079
Robert Greenwalt802c1102014-06-02 15:32:02 -07001080 public boolean isTypeSupported(int type) {
1081 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1082 }
1083
1084 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001085 synchronized (mTypeLists) {
1086 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1087 return mTypeLists[type].get(0);
1088 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001089 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001090 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001091 }
1092
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001093 public int getRestoreTimerForType(int type) {
1094 synchronized (mTypeLists) {
1095 if (mRestoreTimers == null) {
1096 mRestoreTimers = loadRestoreTimers();
1097 }
1098 return mRestoreTimers.getOrDefault(type, -1);
1099 }
1100 }
1101
1102 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1103 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001104 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001105 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1106 for (final String config : configs) {
1107 final String[] splits = TextUtils.split(config, ",");
1108 if (splits.length != 2) {
1109 logwtf("Invalid restore timer token count: " + config);
1110 continue;
1111 }
1112 try {
1113 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1114 } catch (NumberFormatException e) {
1115 logwtf("Invalid restore timer number format: " + config, e);
1116 }
1117 }
1118 return ret;
1119 }
1120
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001121 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001122 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001123 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001124 log("Sending " + state
1125 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001126 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001127 }
1128 }
1129
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001130 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1131 // network type, to preserve previous behaviour.
1132 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1133 if (vpnNai != mService.getLegacyLockdownNai()) return;
1134
1135 if (vpnNai.declaredUnderlyingNetworks == null
1136 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1137 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1138 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1139 return;
1140 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001141 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001142 vpnNai.declaredUnderlyingNetworks[0]);
1143 if (underlyingNai == null) return;
1144
1145 final int type = underlyingNai.networkInfo.getType();
1146 final DetailedState state = DetailedState.CONNECTED;
1147 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1148 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1149 }
1150
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001151 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001152 public void add(int type, NetworkAgentInfo nai) {
1153 if (!isTypeSupported(type)) {
1154 return; // Invalid network type.
1155 }
1156 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1157
1158 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1159 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001160 return;
1161 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001162 synchronized (mTypeLists) {
1163 list.add(nai);
1164 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001165
Chalard Jean5b409c72021-02-04 13:12:59 +09001166 // Send a broadcast if this is the first network of its type or if it's the default.
1167 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001168
1169 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1170 // to preserve previous behaviour.
1171 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001172 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001173 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1174 mService.sendLegacyNetworkBroadcast(nai, state, type);
1175 }
1176
1177 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1178 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001179 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001180 }
1181
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001182 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001183 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001184 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1185 if (list == null || list.isEmpty()) {
1186 return;
1187 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001188 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001189
Hugo Benichi389633f2016-06-21 09:48:07 +09001190 synchronized (mTypeLists) {
1191 if (!list.remove(nai)) {
1192 return;
1193 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001194 }
1195
Lorenzo Colitti49767722015-05-01 00:30:10 +09001196 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001197 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1198 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001199 }
1200
1201 if (!list.isEmpty() && wasFirstNetwork) {
1202 if (DBG) log("Other network available for type " + type +
1203 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001204 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001205 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001206 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001207 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001208 }
1209 }
1210
1211 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001212 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1213 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001214 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001215 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001216 }
1217 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001218
Chalard Jean46bfbf02022-02-02 00:56:25 +09001219 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001220 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001221 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001222 final DetailedState state = nai.networkInfo.getDetailedState();
1223 for (int type = 0; type < mTypeLists.length; type++) {
1224 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001225 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001226 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001227 if (isFirst || contains && isDefault) {
1228 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001229 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001230 }
1231 }
1232 }
1233
Robert Greenwalt94e22142014-07-30 16:31:24 -07001234 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001235 pw.println("mLegacyTypeTracker:");
1236 pw.increaseIndent();
1237 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001238 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001239 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001240 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001241 pw.println();
1242 pw.println("Current state:");
1243 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001244 synchronized (mTypeLists) {
1245 for (int type = 0; type < mTypeLists.length; type++) {
1246 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1247 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001248 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001249 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001250 }
1251 }
1252 pw.decreaseIndent();
1253 pw.decreaseIndent();
1254 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001255 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001256 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001257 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001258
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001259 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001260 /**
1261 * Helper class which parses out priority arguments and dumps sections according to their
1262 * priority. If priority arguments are omitted, function calls the legacy dump command.
1263 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001264 private class LocalPriorityDump {
1265 private static final String PRIORITY_ARG = "--dump-priority";
1266 private static final String PRIORITY_ARG_HIGH = "HIGH";
1267 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001268 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001269
1270 LocalPriorityDump() {}
1271
1272 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Laif8dba342023-10-12 17:01:03 +08001273 if (!HandlerUtils.runWithScissors(mHandler, () -> {
1274 doDump(fd, pw, new String[]{DIAG_ARG});
1275 doDump(fd, pw, new String[]{SHORT_ARG});
1276 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1277 pw.println("dumpHigh timeout");
1278 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001279 }
1280
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001281 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Laif8dba342023-10-12 17:01:03 +08001282 if (!HandlerUtils.runWithScissors(mHandler, () -> doDump(fd, pw, args),
1283 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1284 pw.println("dumpNormal timeout");
1285 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001286 }
1287
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001288 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1289 if (args == null) {
1290 dumpNormal(fd, pw, args);
1291 return;
1292 }
1293
1294 String priority = null;
1295 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1296 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1297 argIndex++;
1298 priority = args[argIndex];
1299 }
1300 }
1301
1302 if (PRIORITY_ARG_HIGH.equals(priority)) {
1303 dumpHigh(fd, pw);
1304 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1305 dumpNormal(fd, pw, args);
1306 } else {
1307 // ConnectivityService publishes binder service using publishBinderService() with
1308 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001309 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1310 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001311 // TODO: Integrate into signal dump.
1312 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001313 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001314 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001315 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001316
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001317 /**
1318 * Dependencies of ConnectivityService, for injection in tests.
1319 */
1320 @VisibleForTesting
1321 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001322 public int getCallingUid() {
1323 return Binder.getCallingUid();
1324 }
1325
Chalard Jeandf29a852023-05-29 17:02:43 +09001326 public boolean isAtLeastS() {
1327 return SdkLevel.isAtLeastS();
1328 }
1329
1330 public boolean isAtLeastT() {
1331 return SdkLevel.isAtLeastT();
1332 }
1333
1334 public boolean isAtLeastU() {
1335 return SdkLevel.isAtLeastU();
1336 }
1337
Chalard Jeaneb663892023-10-07 15:17:07 +09001338 public boolean isAtLeastV() {
1339 return SdkLevel.isAtLeastV();
1340 }
1341
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001342 /**
1343 * Get system properties to use in ConnectivityService.
1344 */
1345 public MockableSystemProperties getSystemProperties() {
1346 return new MockableSystemProperties();
1347 }
1348
1349 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001350 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1351 */
1352 public ConnectivityResources getResources(@NonNull Context ctx) {
1353 return new ConnectivityResources(ctx);
1354 }
1355
1356 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001357 * Create a HandlerThread to use in ConnectivityService.
1358 */
1359 public HandlerThread makeHandlerThread() {
1360 return new HandlerThread("ConnectivityServiceThread");
1361 }
1362
1363 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001364 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001365 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001366 public NetworkStackClientBase getNetworkStack() {
1367 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001368 }
1369
1370 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001371 * @see ProxyTracker
1372 */
1373 public ProxyTracker makeProxyTracker(@NonNull Context context,
1374 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001375 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001376 }
1377
1378 /**
1379 * @see NetIdManager
1380 */
1381 public NetIdManager makeNetIdManager() {
1382 return new NetIdManager();
1383 }
1384
1385 /**
1386 * @see NetworkUtils#queryUserAccess(int, int)
1387 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001388 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1389 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001390 }
1391
1392 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001393 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1394 * requires CAP_NET_ADMIN, which the unit tests do not have.
1395 */
1396 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1397 InetSocketAddress remote) {
1398 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1399 }
1400
1401 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001402 * @see MultinetworkPolicyTracker
1403 */
1404 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1405 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1406 return new MultinetworkPolicyTracker(c, h, r);
1407 }
1408
Aaron Huang330a4c02020-10-27 03:36:19 +08001409 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001410 * @see AutomaticOnOffKeepaliveTracker
1411 */
1412 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1413 @NonNull Context c, @NonNull Handler h) {
1414 return new AutomaticOnOffKeepaliveTracker(c, h);
1415 }
1416
1417 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001418 * @see BatteryStatsManager
1419 */
1420 public void reportNetworkInterfaceForTransports(Context context, String iface,
1421 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001422 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001423 context.getSystemService(BatteryStatsManager.class);
1424 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1425 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001426
1427 public boolean getCellular464XlatEnabled() {
1428 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1429 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001430
1431 /**
1432 * @see PendingIntent#intentFilterEquals
1433 */
1434 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1435 return a.intentFilterEquals(b);
1436 }
1437
1438 /**
1439 * @see LocationPermissionChecker
1440 */
1441 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1442 return new LocationPermissionChecker(context);
1443 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001444
1445 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001446 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001447 *
1448 * This method returns null in versions before T, where carrier privilege
1449 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001450 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001451 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001452 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1453 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001454 if (isAtLeastT()) {
Chalard Jean84dfa9f2023-01-30 11:23:20 +09001455 return new CarrierPrivilegeAuthenticator(context, this, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001456 } else {
1457 return null;
1458 }
1459 }
1460
1461 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001462 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001463 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001464 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001465 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001466 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001467
1468 /**
1469 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001470 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001471 * @return BpfNetMaps implementation.
1472 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001473 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1474 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001475 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001476
1477 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001478 * @see ClatCoordinator
1479 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001480 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001481 public ClatCoordinator getClatCoordinator(INetd netd) {
1482 return new ClatCoordinator(
1483 new ClatCoordinator.Dependencies() {
1484 @NonNull
1485 public INetd getNetd() {
1486 return netd;
1487 }
1488 });
1489 }
1490
1491 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001492 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1493 */
1494 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1495 final InterfaceParams params = InterfaceParams.getByName(iface);
1496 if (params == null) {
1497 // the interface might have disappeared.
1498 logw("Failed to get interface params for interface " + iface);
1499 return;
1500 }
1501 try {
1502 // converting rateInBytesPerSecond from long to int is safe here because the
1503 // setting's range is limited to INT_MAX.
1504 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001505 Log.i(TAG,
1506 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001507 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1508 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1509 } catch (IOException e) {
1510 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1511 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1512 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1513 + ") failure: ", e);
1514 }
1515 }
1516
1517 /**
1518 * Wraps {@link TcUtils#tcFilterDelDev}
1519 */
1520 public void disableIngressRateLimit(String iface) {
1521 final InterfaceParams params = InterfaceParams.getByName(iface);
1522 if (params == null) {
1523 // the interface might have disappeared.
1524 logw("Failed to get interface params for interface " + iface);
1525 return;
1526 }
1527 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001528 Log.i(TAG,
1529 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001530 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1531 } catch (IOException e) {
1532 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1533 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1534 }
1535 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001536
1537 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001538 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1539 */
1540 public int getBpfProgramId(final int attachType, @NonNull final String cgroupPath)
1541 throws IOException {
1542 return BpfUtils.getProgramId(attachType, cgroupPath);
1543 }
1544
1545 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001546 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1547 */
1548 // TODO: when available in all active branches:
1549 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1550 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1551 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1552 return BroadcastOptionsShimImpl.newInstance(options);
1553 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001554
1555 /**
1556 * Wrapper method for
1557 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1558 *
1559 * @param changeId The ID of the compatibility change in question.
1560 * @param packageName The package name of the app in question.
1561 * @param user The user that the operation is done for.
1562 * @return {@code true} if the change is enabled for the specified package.
1563 */
1564 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1565 @NonNull final UserHandle user) {
1566 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1567 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001568
1569 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001570 * As above but with a UID.
1571 * @see CompatChanges#isChangeEnabled(long, int)
1572 */
1573 public boolean isChangeEnabled(final long changeId, final int uid) {
1574 return CompatChanges.isChangeEnabled(changeId, uid);
1575 }
1576
1577 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001578 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1579 *
1580 * @param ranges target uid ranges
1581 * @param exemptUids uids to skip close socket
1582 */
1583 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1584 @NonNull final Set<Integer> exemptUids)
1585 throws SocketException, InterruptedIOException, ErrnoException {
1586 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1587 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001588
1589 /**
1590 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1591 *
1592 * @param ownerUids target uids to close sockets
1593 */
1594 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1595 throws SocketException, InterruptedIOException, ErrnoException {
1596 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1597 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001598
1599 /**
1600 * Schedule the evaluation timeout.
1601 *
1602 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1603 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1604 * of these events happen, this time will run out, after which the network is considered
1605 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1606 * on this network and considers it won't provide connectivity. In particular, that means
1607 * it's when the system prefers it to cell if it's wifi and configuration says it should
1608 * prefer bad wifi to cell.
1609 */
1610 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1611 @NonNull final Network network, final long delayMs) {
1612 handler.sendMessageDelayed(
1613 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1614 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001615 }
1616
junyulaie7c7d2a2021-01-26 15:29:15 +08001617 public ConnectivityService(Context context) {
1618 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001619 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1620 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001621 }
1622
1623 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001624 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1625 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001626 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001627
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001628 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001629 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001630 mSystemProperties = mDeps.getSystemProperties();
1631 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001632 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001633 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001634 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1635 // Pass limit - 1 to maintain backward compatibility.
1636 // TODO: Remove the workaround.
1637 mNetworkRequestCounter =
1638 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1639 mSystemNetworkRequestCounter =
1640 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001641
Hugo Benichi208c0102016-07-28 17:53:06 +09001642 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001643 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1644 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001645 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001646 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001647 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001648 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1649 mDefaultNetworkRequests.add(mDefaultRequest);
1650 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001651
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001652 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001653 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001654
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001655 // The default WiFi request is a background request so that apps using WiFi are
1656 // migrated to a better network (typically ethernet) when one comes up, instead
1657 // of staying on WiFi forever.
1658 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1659 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1660
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001661 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1662 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1663 NetworkRequest.Type.BACKGROUND_REQUEST);
1664
Chalard Jean0702f982021-09-16 21:50:07 +09001665 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1666 // TODO: Consider making the timer customizable.
1667 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1668 mCellularRadioTimesharingCapable =
1669 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1670
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001671 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1672 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1673
1674 if (SdkLevel.isAtLeastU()) {
1675 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1676 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1677 final int defaultUMarkMask = 0x80000000; // u32
1678
1679 if ((mark == 0) || (mask == 0)) {
1680 // simply treat unset/disabled as the default U value
1681 mark = defaultUMarkMask;
1682 mask = defaultUMarkMask;
1683 }
1684 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1685 // invalid device overlay settings
1686 throw new IllegalArgumentException(
1687 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1688 }
1689 }
1690
1691 mWakeUpMark = mark;
1692 mWakeUpMask = mask;
1693
Paul Hu51f816b2022-08-11 14:43:47 +00001694 mNetd = netd;
1695 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001696 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001697 mPermissionMonitor =
1698 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001699 mHandlerThread.start();
1700 mHandler = new InternalHandler(mHandlerThread.getLooper());
1701 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001702 mConnectivityDiagnosticsHandler =
1703 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001704
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001705 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001706 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001707
junyulaie7c7d2a2021-01-26 15:29:15 +08001708 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001709 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001710 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001711 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001712
Wink Saville32506bc2013-06-29 21:10:57 -07001713 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001714 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001715 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001716 mCarrierPrivilegeAuthenticator =
1717 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001718
Sudheer Shanka9967d462021-03-18 19:09:25 +00001719 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001720 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1721 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001722 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001723
1724 final PowerManager powerManager = (PowerManager) context.getSystemService(
1725 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001726 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001727 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001728
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001729 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1730 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001731 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001732 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001733 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001734 mProtectedNetworks.add(p);
1735 } else {
1736 if (DBG) loge("Ignoring protectedNetwork " + p);
1737 }
1738 }
1739
soma, kawata29444ae2019-05-23 09:30:40 +09001740 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1741
James Mattis02220e22021-03-13 19:27:21 -08001742 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001743 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001744 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001745 final IntentFilter userIntentFilter = new IntentFilter();
1746 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1747 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1748 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1749 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001750
James Mattis02220e22021-03-13 19:27:21 -08001751 // Listen to package add/removes for netd
1752 final IntentFilter packageIntentFilter = new IntentFilter();
1753 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1754 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1755 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1756 packageIntentFilter.addDataScheme("package");
1757 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001758 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001759
Motomu Utsumi1e51a642023-07-18 15:11:41 +09001760 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001761
Chalard Jean46bfbf02022-02-02 00:56:25 +09001762 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001763 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001764 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001765 } catch (RemoteException | ServiceSpecificException e) {
1766 loge("Error registering event listener :" + e);
1767 }
1768
Erik Kline05f2b402015-04-30 12:58:40 +09001769 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1770 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001771
chiachangwang7c17c282023-02-02 05:58:59 +00001772 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001773 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001774 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001775
1776 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001777 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001778 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1779 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001780 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001781 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1782 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001783
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001784 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001785 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001786 mNetworkRanker =
1787 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1788
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001789 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001790
Chiachang Wangc1215d32020-10-20 15:38:58 +08001791 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001792 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001793
Chalard Jean28018572020-12-21 18:36:52 +09001794 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1795 // request that doesn't allow fallback to the default network. It should never be visible
1796 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1797 // arguments like the handler or the DnsResolver.
1798 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001799 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001800 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001801 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001802 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001803 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001804 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1805 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001806
1807 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001808 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1809 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1810 // Even if it could, running on S would at least require mocking out the BPF map,
1811 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1812 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001813 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001814 mDscpPolicyTracker = new DscpPolicyTracker();
1815 }
Tyler Wear72388212021-09-09 14:49:02 -07001816 } catch (ErrnoException e) {
1817 loge("Unable to create DscpPolicyTracker");
1818 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001819
1820 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1821 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001822
Chalard Jeandf29a852023-05-29 17:02:43 +09001823 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001824 mCdmps = new CompanionDeviceManagerProxyService(context);
1825 } else {
1826 mCdmps = null;
1827 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001828
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001829 mDestroyFrozenSockets = mDeps.isAtLeastU()
1830 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1831 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1832 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
1833 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001834 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1835 new UidFrozenStateChangedCallback() {
1836 @Override
1837 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1838 if (uids.length != frozenStates.length) {
1839 Log.wtf(TAG, "uids has length " + uids.length
1840 + " but frozenStates has length " + frozenStates.length);
1841 return;
1842 }
1843
1844 final UidFrozenStateChangedArgs args =
1845 new UidFrozenStateChangedArgs(uids, frozenStates);
1846
1847 mHandler.sendMessage(
1848 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1849 }
1850 };
1851
1852 final ActivityManager activityManager =
1853 mContext.getSystemService(ActivityManager.class);
1854 activityManager.registerUidFrozenStateChangedCallback(
1855 (Runnable r) -> r.run(), frozenStateChangedCallback);
1856 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001857 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001858
Xiao Ma0a171c02022-01-23 16:14:51 +00001859 /**
1860 * Check whether or not the device supports Ethernet transport.
1861 */
1862 public static boolean deviceSupportsEthernet(final Context context) {
1863 final PackageManager pm = context.getPackageManager();
1864 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1865 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1866 }
1867
Chalard Jean46adcf32018-04-18 20:18:38 +09001868 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001869 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1870 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001871 }
1872
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001873 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1874 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001875 final NetworkCapabilities netCap = new NetworkCapabilities();
1876 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001877 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001878 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001879 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001880 return netCap;
1881 }
1882
James Mattis45d81842021-01-10 14:24:24 -08001883 private NetworkRequest createDefaultRequest() {
1884 return createDefaultInternetRequestForTransport(
1885 TYPE_NONE, NetworkRequest.Type.REQUEST);
1886 }
1887
lucaslin3ba7cc22022-12-19 02:35:33 +00001888 private NetworkRequest createVpnRequest() {
1889 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1890 .withoutDefaultCapabilities()
1891 .addTransportType(TRANSPORT_VPN)
1892 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1893 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1894 .build();
1895 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1896 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1897 }
1898
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001899 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001900 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001901 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001902 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001903 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001904 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001905 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001906 netCap.addTransportType(transportType);
1907 }
James Mattis45d81842021-01-10 14:24:24 -08001908 return createNetworkRequest(type, netCap);
1909 }
1910
1911 private NetworkRequest createNetworkRequest(
1912 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001913 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001914 }
1915
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001916 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1917 NetworkRequest.Type type) {
1918 final NetworkCapabilities netCap = new NetworkCapabilities();
1919 netCap.clearAll();
1920 netCap.addCapability(capability);
1921 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1922 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1923 }
1924
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001925 // Used only for testing.
1926 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001927 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001928 // changing ContentResolver to make registerContentObserver non-final).
1929 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1930 // by subclassing SettingsObserver.
1931 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001932 void updateAlwaysOnNetworks() {
1933 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001934 }
1935
Erik Kline9a62f012018-03-21 07:18:33 -07001936 // See FakeSettingsProvider comment above.
1937 @VisibleForTesting
1938 void updatePrivateDnsSettings() {
1939 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1940 }
1941
paulhu51f77dc2021-06-07 02:34:20 +00001942 @VisibleForTesting
1943 void updateMobileDataPreferredUids() {
1944 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1945 }
1946
Patrick Rohr2857ac42022-01-21 14:58:16 +01001947 @VisibleForTesting
1948 void updateIngressRateLimit() {
1949 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1950 }
1951
Aaron Huang40b52442021-06-08 04:34:24 +08001952 @VisibleForTesting
1953 void simulateUpdateProxyInfo(@Nullable final Network network,
1954 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001955 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001956 new Pair<>(network, proxyInfo)).sendToTarget();
1957 }
1958
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001959 private void handleAlwaysOnNetworkRequest(
1960 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001961 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001962 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001963 handleAlwaysOnNetworkRequest(networkRequest, enable);
1964 }
1965
1966 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001967 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001968 if (enable == isEnabled) {
1969 return; // Nothing to do.
1970 }
1971
1972 if (enable) {
1973 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001974 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001975 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001976 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001977 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001978 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1979 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001980 }
1981 }
1982
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001983 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001984 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1985 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1986 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1987 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001988 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1989 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001990 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001991 }
1992
paulhu51f77dc2021-06-07 02:34:20 +00001993 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001994 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001995 private void registerSettingsCallbacks() {
1996 // Watch for global HTTP proxy changes.
1997 mSettingsObserver.observe(
1998 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1999 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2000
Chalard Jean46bfbf02022-02-02 00:56:25 +09002001 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002002 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002003 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002004 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2005
Chalard Jean46bfbf02022-02-02 00:56:25 +09002006 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002007 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002008 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002009 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002010
2011 // Watch for mobile data preferred uids changes.
2012 mSettingsObserver.observe(
2013 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2014 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002015
2016 // Watch for ingress rate limit changes.
2017 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002018 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002019 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2020 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002021 }
2022
Erik Kline31b4a9e2018-01-11 21:07:29 +09002023 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002024 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2025 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002026 }
2027 }
2028
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002029 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002030 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2031 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002032 return mNextNetworkRequestId++;
2033 }
2034
junyulai74f9a8b2018-06-13 15:00:37 +08002035 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002036 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002037 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002038 if (network == null) {
2039 return null;
2040 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002041 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002042 }
2043
2044 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002045 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002046 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002047 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002048 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002049
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002050 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002051 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002052 private NetworkAgentInfo getVpnForUid(int uid) {
2053 synchronized (mNetworkForNetId) {
2054 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2055 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002056 if (nai.isVPN() && nai.everConnected()
2057 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002058 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002059 }
2060 }
2061 }
2062 return null;
2063 }
2064
Chalard Jean46bfbf02022-02-02 00:56:25 +09002065 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002066 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002067 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002068 final NetworkAgentInfo nai = getVpnForUid(uid);
2069 if (nai != null) return nai.declaredUnderlyingNetworks;
2070 return null;
2071 }
2072
Lorenzo Colittia7574052021-01-19 01:33:05 +09002073 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002074 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002075
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002076 final Network[] networks = getVpnUnderlyingNetworks(uid);
2077 if (networks != null) {
2078 // getUnderlyingNetworks() returns:
2079 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2080 // empty array => the VPN explicitly said "no default network".
2081 // non-empty array => the VPN specified one or more default networks; we use the
2082 // first one.
2083 if (networks.length > 0) {
2084 nai = getNetworkAgentInfoForNetwork(networks[0]);
2085 } else {
2086 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002087 }
2088 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002089 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002090 }
2091
2092 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002093 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002094 */
paulhu7aeba372020-12-30 00:42:19 +08002095 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2096 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002097 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002098 if (ignoreBlocked) {
2099 return false;
2100 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002101 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002102 final long ident = Binder.clearCallingIdentity();
2103 try {
2104 final boolean metered = nc == null ? true : nc.isMetered();
2105 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2106 } finally {
2107 Binder.restoreCallingIdentity(ident);
2108 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002109 }
2110
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002111 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002112 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2113 return;
2114 }
Hugo Benichi47011212017-03-30 10:46:05 +09002115 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002116 synchronized (mBlockedAppUids) {
2117 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002118 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002119 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002120 blocked = false;
2121 } else {
2122 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002123 }
2124 }
Hugo Benichi47011212017-03-30 10:46:05 +09002125 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2126 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2127 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002128 }
2129
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002130 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002131 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2132 return;
2133 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002134 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002135 final int requestId = nri.getActiveRequest() != null
2136 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002137 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002138 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002139 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002140 }
2141
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002142 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002143 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002144 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002145 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002146 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002147 @NonNull
2148 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2149 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002150 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2151 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2152 // but only exists if an app asks about them or requests them. Ensure the requesting app
2153 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002154 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002155 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2156 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2157 null /* extraInfo */);
2158 }
2159 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002160 return filtered;
2161 }
2162
2163 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2164 boolean ignoreBlocked) {
2165 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2166 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002167 }
2168
2169 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002170 * Return NetworkInfo for the active (i.e., connected) network interface.
2171 * It is assumed that at most one network is active at a time. If more
2172 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002173 * @return the info for the active network, or {@code null} if none is
2174 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002175 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002176 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002177 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002178 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002179 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002180 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002181 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2182 if (nai == null) return null;
2183 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2184 maybeLogBlockedNetworkInfo(networkInfo, uid);
2185 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002186 }
2187
Paul Jensen1f567382015-02-13 14:18:39 -05002188 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002189 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002190 public Network getActiveNetwork() {
2191 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002192 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002193 }
2194
2195 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002196 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002197 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002198 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002199 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002200 }
2201
Chalard Jean46bfbf02022-02-02 00:56:25 +09002202 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002203 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002204 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2205 if (vpnNai != null) {
2206 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2207 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2208 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002209 }
Paul Jensen1f567382015-02-13 14:18:39 -05002210 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002211
James Mattis2516da32021-01-31 17:06:19 -08002212 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002213 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2214 ignoreBlocked)) {
2215 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002216 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002217 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002218 }
2219
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002220 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002221 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002222 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002223 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002224 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2225 if (nai == null) return null;
2226 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002227 }
2228
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002229 /** Returns a NetworkInfo object for a network that doesn't exist. */
2230 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2231 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2232 getNetworkTypeName(networkType), "" /* subtypeName */);
2233 info.setIsAvailable(true);
2234 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2235 // background data is restricted.
2236 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2237 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2238 ? DetailedState.BLOCKED
2239 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002240 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2241 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002242 return info;
2243 }
2244
Lorenzo Colittia7574052021-01-19 01:33:05 +09002245 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002246 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2247 return null;
2248 }
2249 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002250 if (nai == null) {
2251 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002252 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002253 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2254 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002255 }
2256
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002257 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002258 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002259 public NetworkInfo getNetworkInfo(int networkType) {
2260 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002261 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002262 if (getVpnUnderlyingNetworks(uid) != null) {
2263 // A VPN is active, so we may need to return one of its underlying networks. This
2264 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002265 // getNetworkAgentInfoForUid.
2266 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2267 if (nai == null) return null;
2268 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2269 if (networkInfo.getType() == networkType) {
2270 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002271 }
2272 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002273 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002274 }
2275
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002276 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002277 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002278 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002279 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002280 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002281 if (nai == null) return null;
2282 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002283 }
2284
2285 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002286 public NetworkInfo[] getAllNetworkInfo() {
2287 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002288 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002289 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2290 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002291 NetworkInfo info = getNetworkInfo(networkType);
2292 if (info != null) {
2293 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002294 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002295 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002296 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002297 }
2298
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002299 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002300 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002301 public Network getNetworkForType(int networkType) {
2302 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002303 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2304 return null;
2305 }
2306 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2307 if (nai == null) {
2308 return null;
2309 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002310 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002311 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2312 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002313 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002314 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002315 }
2316
2317 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002318 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002319 public Network[] getAllNetworks() {
2320 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002321 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002322 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002323 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002324 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002325 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002326 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002327 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002328 }
2329
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002330 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002331 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002332 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002333 // The basic principle is: if an app's traffic could possibly go over a
2334 // network, without the app doing anything multinetwork-specific,
2335 // (hence, by "default"), then include that network's capabilities in
2336 // the array.
2337 //
2338 // In the normal case, app traffic only goes over the system's default
2339 // network connection, so that's the only network returned.
2340 //
2341 // With a VPN in force, some app traffic may go into the VPN, and thus
2342 // over whatever underlying networks the VPN specifies, while other app
2343 // traffic may go over the system default network (e.g.: a split-tunnel
2344 // VPN, or an app disallowed by the VPN), so the set of networks
2345 // returned includes the VPN's underlying networks and the system
2346 // default.
2347 enforceAccessPermission();
2348
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002349 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002350
James Mattis2516da32021-01-31 17:06:19 -08002351 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2352 if (!nri.isBeingSatisfied()) {
2353 continue;
2354 }
2355 final NetworkAgentInfo nai = nri.getSatisfier();
2356 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2357 if (null != nc
2358 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2359 && !result.containsKey(nai.network)) {
2360 result.put(
2361 nai.network,
2362 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002363 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002364 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2365 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002366 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002367 }
2368
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002369 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002370 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002371 if (null != networks) {
2372 for (final Network network : networks) {
2373 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2374 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002375 result.put(
2376 network,
2377 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002378 nc,
2379 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002380 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002381 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002382 }
2383 }
2384 }
2385
2386 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2387 out = result.values().toArray(out);
2388 return out;
2389 }
2390
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002391 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2392 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2393 // can call sampleConnectivityState and make the checks on it.
2394 @NonNull
2395 private StatsEvent sampleConnectivityStateToStatsEvent() {
2396 final ConnectivityStateSample sample = sampleConnectivityState();
2397 return ConnectivityStatsLog.buildStatsEvent(
2398 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2399 sample.getNetworkCountPerTransports().toByteArray(),
2400 sample.getConnectionDurationPerTransports().toByteArray(),
2401 sample.getNetworkRequestCount().toByteArray(),
2402 sample.getNetworks().toByteArray());
2403 }
2404
2405 /**
2406 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2407 *
2408 * This is used for metrics. These snapshots will be sampled and constitute a base for
2409 * statistics about connectivity state of devices.
2410 */
2411 @VisibleForTesting
2412 @NonNull
2413 public ConnectivityStateSample sampleConnectivityState() {
2414 ensureRunningOnConnectivityServiceThread();
2415 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2416 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2417 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2418 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2419 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2420 return builder.build();
2421 }
2422
2423 private static NetworkCountPerTransports sampleNetworkCount(
2424 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2425 final SparseIntArray countPerTransports = new SparseIntArray();
2426 for (final NetworkAgentInfo nai : nais) {
2427 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2428 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2429 }
2430 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2431 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2432 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2433 c.setTransportTypes(countPerTransports.keyAt(i));
2434 c.setNetworkCount(countPerTransports.valueAt(i));
2435 builder.addNetworkCountForTransports(c);
2436 }
2437 return builder.build();
2438 }
2439
2440 private static ConnectionDurationPerTransports sampleConnectionDuration(
2441 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2442 final ConnectionDurationPerTransports.Builder builder =
2443 ConnectionDurationPerTransports.newBuilder();
2444 for (final NetworkAgentInfo nai : nais) {
2445 final ConnectionDurationForTransports.Builder c =
2446 ConnectionDurationForTransports.newBuilder();
2447 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2448 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2449 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2450 // Add millisPerSecond/2 to round up or down to the nearest value
2451 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2452 builder.addConnectionDurationForTransports(c);
2453 }
2454 return builder.build();
2455 }
2456
2457 private static NetworkRequestCount sampleNetworkRequestCount(
2458 @NonNull final Collection<NetworkRequestInfo> nris) {
2459 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2460 final SparseIntArray countPerType = new SparseIntArray();
2461 for (final NetworkRequestInfo nri : nris) {
2462 final int type;
2463 if (Process.SYSTEM_UID == nri.mAsUid) {
2464 // The request is filed "as" the system, so it's the system on its own behalf.
2465 type = RequestType.RT_SYSTEM.getNumber();
2466 } else if (Process.SYSTEM_UID == nri.mUid) {
2467 // The request is filed by the system as some other app, so it's the system on
2468 // behalf of an app.
2469 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2470 } else {
2471 // Not the system, so it's an app requesting on its own behalf.
2472 type = RequestType.RT_APP.getNumber();
2473 }
2474 countPerType.put(type, countPerType.get(type, 0));
2475 }
2476 for (int i = countPerType.size() - 1; i >= 0; --i) {
2477 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2478 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2479 r.setRequestCount(countPerType.valueAt(i));
2480 builder.addRequestCountForType(r);
2481 }
2482 return builder.build();
2483 }
2484
2485 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2486 final NetworkList.Builder builder = NetworkList.newBuilder();
2487 for (final NetworkAgentInfo nai : nais) {
2488 final NetworkCapabilities nc = nai.networkCapabilities;
2489 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2490 d.setTransportTypes((int) nc.getTransportTypesInternal());
2491 final MeteredState meteredState;
2492 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2493 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2494 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2495 meteredState = MeteredState.METERED_NO;
2496 } else {
2497 meteredState = MeteredState.METERED_YES;
2498 }
2499 d.setMeteredState(meteredState);
2500 final ValidatedState validatedState;
2501 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2502 validatedState = ValidatedState.VS_PORTAL;
2503 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2504 validatedState = ValidatedState.VS_PARTIAL;
2505 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2506 validatedState = ValidatedState.VS_VALID;
2507 } else {
2508 validatedState = ValidatedState.VS_INVALID;
2509 }
2510 d.setValidatedState(validatedState);
2511 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2512 d.setCapabilities(nc.getCapabilitiesInternal());
2513 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2514 builder.addNetworkDescription(d);
2515 }
2516 return builder.build();
2517 }
2518
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002519 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002520 public boolean isNetworkSupported(int networkType) {
2521 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002522 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002523 }
2524
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002525 /**
2526 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002527 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002528 * @return the ip properties for the active network, or {@code null} if
2529 * none is active
2530 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002531 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002532 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002533 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002534 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002535 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2536 if (nai == null) return null;
2537 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002538 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002539 }
2540
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002541 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002542 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002543 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002544 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002545 final LinkProperties lp = getLinkProperties(nai);
2546 if (lp == null) return null;
2547 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002548 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002549 }
2550
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002551 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002552 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002553 public LinkProperties getLinkProperties(Network network) {
2554 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002555 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2556 if (lp == null) return null;
2557 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002558 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002559 }
2560
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002561 @Nullable
2562 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002563 if (nai == null) {
2564 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002565 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002566 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002567 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002568 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002569 }
2570
lucaslinc582d502022-01-27 09:07:00 +08002571 @Override
2572 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002573 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002574 @NonNull String packageName, @Nullable String callingAttributionTag) {
2575 Objects.requireNonNull(packageName);
2576 Objects.requireNonNull(lp);
2577 enforceNetworkStackOrSettingsPermission();
2578 if (!checkAccessPermission(-1 /* pid */, uid)) {
2579 return null;
2580 }
2581 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2582 }
2583
Qingxi Lib2748102020-01-08 12:51:49 -08002584 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2585 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2586 }
2587
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002588 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002589 if (nai == null) return null;
2590 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002591 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002592 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002593 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002594 }
2595
2596 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002597 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2598 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002599 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002600 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002601 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002602 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002603 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002604 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002605 }
2606
lucaslinc582d502022-01-27 09:07:00 +08002607 @Override
lucaslind2b06132022-03-02 10:56:57 +08002608 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2609 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2610 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002611 Objects.requireNonNull(nc);
2612 Objects.requireNonNull(packageName);
2613 enforceNetworkStackOrSettingsPermission();
2614 if (!checkAccessPermission(-1 /* pid */, uid)) {
2615 return null;
2616 }
2617 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2618 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2619 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2620 callingAttributionTag);
2621 }
2622
lucaslin69e1aa92022-03-22 18:15:09 +08002623 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2624 if (nc.getUnderlyingNetworks() != null
2625 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2626 nc.setUnderlyingNetworks(null);
2627 }
2628 }
2629
Qingxi Libb8da982020-01-17 17:54:27 -08002630 @VisibleForTesting
2631 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002632 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002633 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2634 // this would be expensive (one more permission check every time any NC callback is
2635 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2636 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2637 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002638 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002639 if (!checkSettingsPermission(callerPid, callerUid)) {
2640 newNc.setUids(null);
2641 newNc.setSSID(null);
2642 }
Etan Cohen107ae952018-12-30 17:59:59 -08002643 if (newNc.getNetworkSpecifier() != null) {
2644 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2645 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002646 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2647 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002648 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2649 newNc.setAdministratorUids(new int[0]);
2650 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002651 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002652 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002653 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002654 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002655 }
lucaslin69e1aa92022-03-22 18:15:09 +08002656 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002657
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002658 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002659 }
2660
Roshan Pius98f59ec2021-02-23 08:47:39 -08002661 /**
2662 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002663 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002664 * NetworkCapabilities.
2665 * Note: This wrapper does not support any sort of invalidation and thus must not be
2666 * persistent or long-lived. It may only be used for the time necessary to
2667 * compute the redactions required by one particular NetworkCallback or
2668 * synchronous call.
2669 */
2670 private class RedactionPermissionChecker {
2671 private final int mCallingPid;
2672 private final int mCallingUid;
2673 @NonNull private final String mCallingPackageName;
2674 @Nullable private final String mCallingAttributionTag;
2675
2676 private Boolean mHasLocationPermission = null;
2677 private Boolean mHasLocalMacAddressPermission = null;
2678 private Boolean mHasSettingsPermission = null;
2679
2680 RedactionPermissionChecker(int callingPid, int callingUid,
2681 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2682 mCallingPid = callingPid;
2683 mCallingUid = callingUid;
2684 mCallingPackageName = callingPackageName;
2685 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002686 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002687
2688 private boolean hasLocationPermissionInternal() {
2689 final long token = Binder.clearCallingIdentity();
2690 try {
2691 return mLocationPermissionChecker.checkLocationPermission(
2692 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2693 null /* message */);
2694 } finally {
2695 Binder.restoreCallingIdentity(token);
2696 }
2697 }
2698
2699 /**
2700 * Returns whether the app holds location permission or not (might return cached result
2701 * if the permission was already checked before).
2702 */
2703 public boolean hasLocationPermission() {
2704 if (mHasLocationPermission == null) {
2705 // If there is no cached result, perform the check now.
2706 mHasLocationPermission = hasLocationPermissionInternal();
2707 }
2708 return mHasLocationPermission;
2709 }
2710
2711 /**
2712 * Returns whether the app holds local mac address permission or not (might return cached
2713 * result if the permission was already checked before).
2714 */
2715 public boolean hasLocalMacAddressPermission() {
2716 if (mHasLocalMacAddressPermission == null) {
2717 // If there is no cached result, perform the check now.
2718 mHasLocalMacAddressPermission =
2719 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2720 }
2721 return mHasLocalMacAddressPermission;
2722 }
2723
2724 /**
2725 * Returns whether the app holds settings permission or not (might return cached
2726 * result if the permission was already checked before).
2727 */
2728 public boolean hasSettingsPermission() {
2729 if (mHasSettingsPermission == null) {
2730 // If there is no cached result, perform the check now.
2731 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2732 }
2733 return mHasSettingsPermission;
2734 }
2735 }
2736
2737 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2738 @NetworkCapabilities.NetCapability long redaction) {
2739 return (redactions & redaction) != 0;
2740 }
2741
2742 /**
2743 * Use the provided |applicableRedactions| to check the receiving app's
2744 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2745 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2746 * before being sent to the corresponding app.
2747 */
2748 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2749 @NetworkCapabilities.RedactionType long applicableRedactions,
2750 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2751 boolean includeLocationSensitiveInfo) {
2752 long redactions = applicableRedactions;
2753 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2754 if (includeLocationSensitiveInfo
2755 && redactionPermissionChecker.hasLocationPermission()) {
2756 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2757 }
2758 }
2759 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2760 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2761 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2762 }
2763 }
2764 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2765 if (redactionPermissionChecker.hasSettingsPermission()) {
2766 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2767 }
2768 }
2769 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002770 }
2771
Qingxi Lib2748102020-01-08 12:51:49 -08002772 @VisibleForTesting
2773 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002774 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002775 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002776 int callingPid, int callingUid, @NonNull String callingPkgName,
2777 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002778 if (nc == null) {
2779 return null;
2780 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002781 // Avoid doing location permission check if the transport info has no location sensitive
2782 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002783 final RedactionPermissionChecker redactionPermissionChecker =
2784 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2785 callingAttributionTag);
2786 final long redactions = retrieveRequiredRedactions(
2787 nc.getApplicableRedactions(), redactionPermissionChecker,
2788 includeLocationSensitiveInfo);
2789 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002790 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002791 // TODO : calling UID is redacted because apps should generally not know what UID is
2792 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002793 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002794 newNc.setOwnerUid(INVALID_UID);
2795 return newNc;
2796 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002797 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2798 if (nc.hasTransport(TRANSPORT_VPN)) {
2799 // Owner UIDs already checked above. No need to re-check.
2800 return newNc;
2801 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002802 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2803 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002804 // compatibility for older apps.
2805 if (!includeLocationSensitiveInfo
2806 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002807 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002808 newNc.setOwnerUid(INVALID_UID);
2809 return newNc;
2810 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002811 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002812 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002813 newNc.setOwnerUid(INVALID_UID);
2814 }
Qingxi Lib2748102020-01-08 12:51:49 -08002815 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002816 }
2817
lucaslinc582d502022-01-27 09:07:00 +08002818 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002819 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2820 LinkProperties lp, int callerPid, int callerUid) {
2821 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002822 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2823 // this would be expensive (one more permission check every time any LP callback is
2824 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2825 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2826 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002827
2828 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2829 final boolean needsSanitization =
2830 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2831 if (!needsSanitization) {
2832 return new LinkProperties(lp);
2833 }
2834
2835 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002836 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002837 }
2838
2839 final LinkProperties newLp = new LinkProperties(lp);
2840 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2841 // object gets parceled.
2842 newLp.setCaptivePortalApiUrl(null);
2843 newLp.setCaptivePortalData(null);
2844 return newLp;
2845 }
2846
Roshan Pius08c94fb2020-01-16 12:17:17 -08002847 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2848 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002849 // There is no need to track the effective UID of the request here. If the caller
2850 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002851 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002852 // Unprivileged apps can only pass in null or their own UID.
2853 if (nc.getUids() == null) {
2854 // If the caller passes in null, the callback will also match networks that do not
2855 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2856 // In this case, redact everything in the request immediately. This ensures that the
2857 // app is not able to get any redacted information by filing an unredacted request
2858 // and observing whether the request matches something.
2859 if (nc.getNetworkSpecifier() != null) {
2860 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2861 }
2862 } else {
2863 nc.setSingleUid(callerUid);
2864 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002865 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002866 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002867 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002868
2869 // Clear owner UID; this can never come from an app.
2870 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002871 }
2872
Chalard Jean38354d12018-03-20 19:13:57 +09002873 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002874 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002875 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2876 }
2877 }
2878
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002879 @Override
2880 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2881 enforceAccessPermission();
2882 final int callerUid = Binder.getCallingUid();
2883 final long token = Binder.clearCallingIdentity();
2884 try {
2885 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2886 } finally {
2887 Binder.restoreCallingIdentity(token);
2888 }
2889 }
2890
junyulaiebd15162021-03-03 12:09:05 +08002891 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002892 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002893 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002894 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002895 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002896
Serik Beketayev05130302021-01-15 16:47:25 -08002897 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002898 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002899 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2900 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002901 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002902 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002903 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002904 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2905 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002906 }
2907 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002908 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002909 }
2910
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002911 @Override
junyulaiebd15162021-03-03 12:09:05 +08002912 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002913 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002914 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002915 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002916
2917 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2918 for (Network network : getAllNetworks()) {
2919 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002920 final boolean includeNetwork = (nai != null) && nai.isCreated();
2921 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002922 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2923 // NetworkCapabilities, which may contain UIDs of apps to which the
2924 // network applies. Should the UIDs be cleared so as not to leak or
2925 // interfere ?
2926 result.add(nai.getNetworkStateSnapshot());
2927 }
2928 }
2929 return result;
2930 }
2931
2932 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002933 public boolean isActiveNetworkMetered() {
2934 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002935
Qingxi Lib2748102020-01-08 12:51:49 -08002936 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002937 if (caps != null) {
2938 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2939 } else {
2940 // Always return the most conservative value
2941 return true;
2942 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002943 }
2944
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002945 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002946 * Ensures that the system cannot call a particular method.
2947 */
2948 private boolean disallowedBecauseSystemCaller() {
2949 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002950 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2951 // for devices launched with Q and above. However, existing devices upgrading to Q and
2952 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002953 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002954 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002955 log("This method exists only for app backwards compatibility"
2956 + " and must not be called by system services.");
2957 return true;
2958 }
2959 return false;
2960 }
2961
paulhub2c28682021-08-18 18:35:54 +08002962 private int getAppUid(final String app, final UserHandle user) {
2963 final PackageManager pm =
2964 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2965 final long token = Binder.clearCallingIdentity();
2966 try {
2967 return pm.getPackageUid(app, 0 /* flags */);
2968 } catch (PackageManager.NameNotFoundException e) {
2969 return -1;
2970 } finally {
2971 Binder.restoreCallingIdentity(token);
2972 }
2973 }
2974
2975 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2976 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2977 if (getAppUid(packageName, user) != callingUid) {
2978 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2979 }
2980 }
2981
Lorenzo Colitti23862912018-09-28 11:31:55 +09002982 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002983 * Ensure that a network route exists to deliver traffic to the specified
2984 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002985 * @param networkType the type of the network over which traffic to the
2986 * specified host is to be routed
2987 * @param hostAddress the IP address of the host to which the route is
2988 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002989 * @return {@code true} on success, {@code false} on failure
2990 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002991 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002992 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2993 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002994 if (disallowedBecauseSystemCaller()) {
2995 return false;
2996 }
paulhub2c28682021-08-18 18:35:54 +08002997 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002998 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002999 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003000 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003001 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003002
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003003 InetAddress addr;
3004 try {
3005 addr = InetAddress.getByAddress(hostAddress);
3006 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003007 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003008 return false;
3009 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003010
The Android Open Source Project28527d22009-03-03 19:31:44 -08003011 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003012 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003013 return false;
3014 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003015
3016 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3017 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003018 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003019 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3020 } else {
3021 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3022 }
3023 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003024 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003025
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003026 DetailedState netState;
3027 synchronized (nai) {
3028 netState = nai.networkInfo.getDetailedState();
3029 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003030
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003031 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003032 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003033 log("requestRouteToHostAddress on down network "
3034 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003035 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003036 }
3037 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003038 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003039
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003040 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003041 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003042 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003043 LinkProperties lp;
3044 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003045 synchronized (nai) {
3046 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003047 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003048 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003049 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003050 if (DBG) {
3051 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3052 }
Wink Saville32506bc2013-06-29 21:10:57 -07003053 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003054 } finally {
3055 Binder.restoreCallingIdentity(token);
3056 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003057 }
3058
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003059 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003060 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003061 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003062 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003063 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003064 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003065 if (bestRoute.getGateway().equals(addr)) {
3066 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003067 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003068 } else {
3069 // if we will connect to this through another route, add a direct route
3070 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003071 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003072 }
3073 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003074 if (DBG) log("Adding legacy route " + bestRoute +
3075 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003076
3077 final String dst = bestRoute.getDestinationLinkAddress().toString();
3078 final String nextHop = bestRoute.hasGateway()
3079 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003080 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003081 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3082 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003083 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003084 return false;
3085 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003086 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003087 }
3088
paulhu7c0a2e62021-01-08 00:51:49 +08003089 class DnsResolverUnsolicitedEventCallback extends
3090 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003091 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003092 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003093 try {
3094 mHandler.sendMessage(mHandler.obtainMessage(
3095 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003096 new PrivateDnsValidationUpdate(event.netId,
3097 InetAddresses.parseNumericAddress(event.ipAddress),
3098 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003099 } catch (IllegalArgumentException e) {
3100 loge("Error parsing ip address in validation event");
3101 }
3102 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003103
3104 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003105 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3106 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003107 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3108 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3109 // event callback for certain nai. e.g. cellular. Register here to pass to
3110 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003111 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003112 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3113 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003114 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003115 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003116 }
3117 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003118
3119 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003120 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3121 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3122 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003123 }
dalyk1720e542018-03-05 12:42:22 -05003124
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003125 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003126 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003127 return this.VERSION;
3128 }
3129
3130 @Override
3131 public String getInterfaceHash() {
3132 return this.HASH;
3133 }
paulhu7c0a2e62021-01-08 00:51:49 +08003134 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003135
3136 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003137 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3138 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003139
paulhu7c0a2e62021-01-08 00:51:49 +08003140 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003141 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003142 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003143 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003144 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003145 }
3146 }
3147
Sudheer Shanka9967d462021-03-18 19:09:25 +00003148 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003149 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003150 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003151 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3152 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003153 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003154 };
3155
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003156 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003157 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003158 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003159 }
3160
Mark Fasheh7c999d82023-05-04 20:23:11 +00003161 static final class UidFrozenStateChangedArgs {
3162 final int[] mUids;
3163 final int[] mFrozenStates;
3164
3165 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3166 mUids = uids;
3167 mFrozenStates = frozenStates;
3168 }
3169 }
3170
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003171 /**
3172 * Check if the cell network is idle.
3173 * @return true if the cell network state is idle
3174 * false if the cell network state is active or unknown
3175 */
3176 private boolean isCellNetworkIdle() {
3177 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3178 if (defaultNai == null
3179 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3180 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3181 // cell network is not the default network, cell network state is unknown.
3182 // TODO(b/279380356): Track cell network state when the cell is not the default network
3183 return false;
3184 }
3185
3186 return !mNetworkActivityTracker.isDefaultNetworkActive();
3187 }
3188
Mark Fasheh7c999d82023-05-04 20:23:11 +00003189 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003190 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003191
3192 for (int i = 0; i < uids.length; i++) {
3193 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003194 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003195 } else {
3196 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003197 }
3198 }
3199
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003200 if (ownerUids.isEmpty()) {
3201 return;
3202 }
3203
3204 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3205 // Delay closing sockets to avoid waking the cell modem up.
3206 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3207 // than waking cell modem up.
3208 mPendingFrozenUids.addAll(ownerUids);
3209 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003210 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003211 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003212 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003213 loge("Exception in socket destroy: " + e);
3214 }
3215 }
3216 }
3217
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003218 private void closePendingFrozenSockets() {
3219 ensureRunningOnConnectivityServiceThread();
3220
3221 try {
3222 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3223 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3224 loge("Failed to close pending frozen app sockets: " + e);
3225 }
3226 mPendingFrozenUids.clear();
3227 }
3228
3229 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3230 mNetworkActivityTracker.handleReportNetworkActivity(params);
3231
3232 if (mDelayDestroyFrozenSockets
3233 && params.isActive
3234 && params.label == TRANSPORT_CELLULAR
3235 && !mPendingFrozenUids.isEmpty()) {
3236 closePendingFrozenSockets();
3237 }
3238 }
3239
3240 /**
3241 * If the cellular network is no longer the default network, close pending frozen sockets.
3242 *
3243 * @param newNetwork new default network
3244 * @param oldNetwork old default network
3245 */
3246 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3247 NetworkAgentInfo oldNetwork) {
3248 final boolean isOldNetworkCellular = oldNetwork != null
3249 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3250 final boolean isNewNetworkCellular = newNetwork != null
3251 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3252
3253 if (isOldNetworkCellular
3254 && !isNewNetworkCellular
3255 && !mPendingFrozenUids.isEmpty()) {
3256 closePendingFrozenSockets();
3257 }
3258 }
3259
3260 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3261 pw.println("CloseFrozenAppSockets:");
3262 pw.increaseIndent();
3263 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3264 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3265 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3266 pw.decreaseIndent();
3267 }
3268
Junyu Lai155760b2023-10-05 14:51:00 +08003269 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3270 pw.println("Bpf Program Status:");
3271 pw.increaseIndent();
3272 try {
3273 pw.print("CGROUP_INET_INGRESS: ");
3274 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS, BpfUtils.CGROUP_PATH));
3275 pw.print("CGROUP_INET_EGRESS: ");
3276 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS, BpfUtils.CGROUP_PATH));
3277 pw.print("CGROUP_INET_SOCK_CREATE: ");
3278 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE, BpfUtils.CGROUP_PATH));
3279 pw.print("CGROUP_INET4_BIND: ");
3280 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND, BpfUtils.CGROUP_PATH));
3281 pw.print("CGROUP_INET6_BIND: ");
3282 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND, BpfUtils.CGROUP_PATH));
3283 } catch (IOException e) {
3284 pw.println(" IOException");
3285 }
3286 pw.decreaseIndent();
3287 }
3288
Mark Fasheh7c999d82023-05-04 20:23:11 +00003289 @VisibleForTesting
3290 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003291 @VisibleForTesting
3292 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3293 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003294
Paul Jensen83f5d572014-08-29 09:54:01 -04003295 private void enforceInternetPermission() {
3296 mContext.enforceCallingOrSelfPermission(
3297 android.Manifest.permission.INTERNET,
3298 "ConnectivityService");
3299 }
3300
The Android Open Source Project28527d22009-03-03 19:31:44 -08003301 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003302 mContext.enforceCallingOrSelfPermission(
3303 android.Manifest.permission.ACCESS_NETWORK_STATE,
3304 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003305 }
3306
lucaslinc582d502022-01-27 09:07:00 +08003307 private boolean checkAccessPermission(int pid, int uid) {
3308 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3309 == PERMISSION_GRANTED;
3310 }
3311
paulhua6ee2122021-02-22 15:40:43 +08003312 /**
3313 * Performs a strict and comprehensive check of whether a calling package is allowed to
3314 * change the state of network, as the condition differs for pre-M, M+, and
3315 * privileged/preinstalled apps. The caller is expected to have either the
3316 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3317 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3318 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3319 * permission and cannot be revoked. See http://b/23597341
3320 *
3321 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3322 * of this app will be updated to the current time.
3323 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003324 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003325 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3326 == PackageManager.PERMISSION_GRANTED) {
3327 return;
3328 }
3329
3330 if (callingPkg == null) {
3331 throw new SecurityException("Calling package name is null.");
3332 }
3333
3334 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3335 final int uid = mDeps.getCallingUid();
3336 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3337 callingPkg, callingAttributionTag, null /* message */);
3338
3339 if (mode == AppOpsManager.MODE_ALLOWED) {
3340 return;
3341 }
3342
3343 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3344 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3345 return;
3346 }
3347
3348 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3349 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3350 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003351 }
3352
Charles He9369e612017-05-15 17:07:18 +01003353 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003354 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003355 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003356 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003357 }
3358
Quang Luong98858d62023-02-11 00:25:24 +00003359 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003360 enforceAnyPermissionOf(mContext,
3361 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003362 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003363 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3364 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3365 }
3366
paulhu8e96a752019-08-12 16:25:11 +08003367 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003368 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003369 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003370 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003371 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003372 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003373 }
3374
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003375 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003376 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003377 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003378 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003379 android.Manifest.permission.NETWORK_SETTINGS,
3380 android.Manifest.permission.NETWORK_FACTORY,
3381 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3382 }
3383
3384 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003385 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003386 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003387 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003388 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3389 android.Manifest.permission.NETWORK_FACTORY,
3390 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3391 }
3392
lucaslin69e1aa92022-03-22 18:15:09 +08003393 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3394 return PERMISSION_GRANTED == mContext.checkPermission(
3395 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3396 || PERMISSION_GRANTED == mContext.checkPermission(
3397 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3398 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003399 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003400 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003401 }
3402
Chalard Jean9a396cc2018-02-21 18:43:54 +09003403 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003404 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003405 android.Manifest.permission.NETWORK_SETTINGS,
3406 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003407 }
3408
3409 private boolean checkSettingsPermission(int pid, int uid) {
3410 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003411 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3412 || PERMISSION_GRANTED == mContext.checkPermission(
3413 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003414 }
3415
paulhu8e96a752019-08-12 16:25:11 +08003416 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003417 enforceNetworkStackPermissionOr(mContext,
3418 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003419 }
3420
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003421 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003422 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003423 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003424 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003425 }
3426
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003427 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003428 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003429 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3430 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003431 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003432 }
3433
James Mattis8378aec2021-01-26 14:05:36 -08003434 private void enforceOemNetworkPreferencesPermission() {
3435 mContext.enforceCallingOrSelfPermission(
3436 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3437 "ConnectivityService");
3438 }
3439
James Mattisfa270db2021-05-31 17:11:10 -07003440 private void enforceManageTestNetworksPermission() {
3441 mContext.enforceCallingOrSelfPermission(
3442 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3443 "ConnectivityService");
3444 }
3445
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003446 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003447 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003448 android.Manifest.permission.NETWORK_STACK,
3449 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003450 }
3451
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003452 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003453 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003454 android.Manifest.permission.NETWORK_STACK,
3455 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3456 }
3457
paulhu1a407652019-03-22 16:35:06 +08003458 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003459 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003460 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003461 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3462 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003463 }
3464
Paul Hu8fc2a552022-05-04 18:44:42 +08003465 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3466 boolean checkUidsAllowedList) {
3467 if (PermissionUtils.checkAnyPermissionOf(mContext,
3468 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3469 return true;
3470 }
3471
3472 // fallback to ConnectivityInternalPermission
3473 // TODO: Remove this fallback check after all apps have declared
3474 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3475 if (PermissionUtils.checkAnyPermissionOf(mContext,
3476 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3477 return true;
3478 }
3479
3480 // Check whether uid is in allowed on restricted networks list.
3481 if (checkUidsAllowedList
3482 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3483 return true;
3484 }
3485 return false;
3486 }
3487
3488 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3489 final int callingUid = mDeps.getCallingUid();
3490 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3491 throw new SecurityException("ConnectivityService: user " + callingUid
3492 + " has no permission to access restricted network.");
3493 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003494 }
3495
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003496 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003497 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003498 }
3499
Roshan Pius98f59ec2021-02-23 08:47:39 -08003500 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3501 return PERMISSION_GRANTED == mContext.checkPermission(
3502 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3503 }
3504
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003505 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003506 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003507 }
3508
3509 private void sendInetConditionBroadcast(NetworkInfo info) {
3510 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3511 }
3512
Wink Saville4f0de1e2011-08-04 15:01:58 -07003513 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003514 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003515 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003516 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003517 if (info.isFailover()) {
3518 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3519 info.setFailover(false);
3520 }
3521 if (info.getReason() != null) {
3522 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3523 }
3524 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003525 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3526 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003527 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003528 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003529 return intent;
3530 }
3531
3532 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3533 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3534 }
3535
Michael Groover73f69482023-01-27 11:01:25 -06003536 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3537 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003538 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3539 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003540 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003541 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003542 if (!mSystemReady
3543 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003544 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003545 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003546 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003547 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003548 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003549 }
3550
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003551 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003552 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003553 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003554 final NetworkInfo ni = intent.getParcelableExtra(
3555 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003556 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3557 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003558 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003559 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003560 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003561 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003562 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003563 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003564 } finally {
3565 Binder.restoreCallingIdentity(ident);
3566 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003567 }
3568 }
3569
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003570 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3571 NetworkInfo info) {
3572 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003573 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003574
3575 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3576 try {
3577 // This allows us to discard older broadcasts still waiting to be delivered
3578 // which have the same namespace and key.
3579 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3580 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3581 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003582 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003583 } catch (UnsupportedApiLevelException e) {
3584 Log.wtf(TAG, "Using unsupported API" + e);
3585 }
3586 }
3587
3588 @VisibleForTesting
3589 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3590 final StringBuilder sb = new StringBuilder();
3591 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3592 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3593 sb.append(info.getExtraInfo());
3594 return sb.toString();
3595 }
3596
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003597 /**
Aaron Huang96011892020-06-27 07:18:23 +08003598 * Called by SystemServer through ConnectivityManager when the system is ready.
3599 */
3600 @Override
3601 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003602 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003603 throw new SecurityException("Calling Uid is not system uid.");
3604 }
3605 systemReadyInternal();
3606 }
3607
3608 /**
3609 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003610 */
3611 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003612 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003613 // Load flags after PackageManager is ready to query module version
3614 mFlags.loadFlags(mDeps, mContext);
3615
Aaron Huang9a57acf2020-12-08 10:03:29 +08003616 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3617 // listening network request which is sent by MultipathPolicyTracker won't be added
3618 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3619 // be called after PermissionMonitor#startMonitoring().
3620 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3621 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3622 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003623 final ConditionVariable startMonitoringDone = new ConditionVariable();
3624 mHandler.post(() -> {
3625 mPermissionMonitor.startMonitoring();
3626 startMonitoringDone.open();
3627 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003628 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003629 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003630
Hugo Benichie5220992017-04-26 14:53:28 +09003631 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003632 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003633 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003634 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003635 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003636 }
3637 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003638
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003639 // Create network requests for always-on networks.
3640 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003641
3642 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003643 // Note that updating can be skipped here if the list is empty only because no uid
3644 // rules are applied before system ready. Normally, the empty uid list means to clear
3645 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003646 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3647 updateMobileDataPreferredUids();
3648 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003649
3650 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003651 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003652 mBpfNetMaps.setPullAtomCallback(mContext);
3653 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003654 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3655 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003656 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3657 // have permission problem. While CV#block() is unbounded in time and can in principle block
3658 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3659 // could have blocked forever too.
3660 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003661 }
3662
The Android Open Source Project28527d22009-03-03 19:31:44 -08003663 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003664 * Start listening for default data network activity state changes.
3665 */
3666 @Override
3667 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003668 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003669 }
3670
3671 /**
3672 * Stop listening for default data network activity state changes.
3673 */
3674 @Override
3675 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003676 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003677 }
3678
3679 /**
3680 * Check whether the default network radio is currently active.
3681 */
3682 @Override
3683 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003684 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003685 }
3686
3687 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003688 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003689 * and set it on it's iface.
3690 */
Junyu Lai970963e2022-10-25 15:46:47 +08003691 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003692 final String iface = newLp.getInterfaceName();
3693 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003694 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003695 // Silently ignore unset MTU value.
3696 return;
3697 }
Hansen Kurli04252032022-12-07 11:21:49 +00003698 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3699 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3700 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003701 return;
3702 }
Hansen Kurli04252032022-12-07 11:21:49 +00003703 // Cannot set MTU without interface name
3704 if (TextUtils.isEmpty(iface)) {
3705 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003706 return;
3707 }
sy.yun4aa73922013-09-02 05:24:09 +09003708
Hansen Kurli04252032022-12-07 11:21:49 +00003709 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3710 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003711 return;
3712 }
3713
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003714 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003715 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003716 mNetd.interfaceSetMtu(iface, mtu);
3717 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003718 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003719 }
3720 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003721
Chenbo Feng15416292018-11-08 17:36:21 -08003722 @VisibleForTesting
3723 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003724
Junyu Lai970963e2022-10-25 15:46:47 +08003725 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003726 String[] values = null;
3727 if (tcpBufferSizes != null) {
3728 values = tcpBufferSizes.split(",");
3729 }
3730
3731 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003732 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003733 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3734 values = tcpBufferSizes.split(",");
3735 }
3736
3737 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3738
3739 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003740 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003741
Chenbo Feng15416292018-11-08 17:36:21 -08003742 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3743 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3744 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003745 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003746 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003747 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003748 }
3749 }
3750
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003751 @Override
3752 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003753 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003754 NETWORK_RESTORE_DELAY_PROP_NAME);
3755 if(restoreDefaultNetworkDelayStr != null &&
3756 restoreDefaultNetworkDelayStr.length() != 0) {
3757 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003758 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003759 } catch (NumberFormatException e) {
3760 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003761 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003762 // if the system property isn't set, use the value for the apn type
3763 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3764
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003765 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3766 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003767 }
3768 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003769 }
3770
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003771 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003772 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003773 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003774 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003775 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003776 // Start gathering diagnostic information.
3777 netDiags.add(new NetworkDiagnostics(
3778 nai.network,
3779 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003780 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003781 DIAG_TIME_MS));
3782 }
3783
3784 for (NetworkDiagnostics netDiag : netDiags) {
3785 pw.println();
3786 netDiag.waitForMeasurements();
3787 netDiag.dump(pw);
3788 }
3789 }
3790
The Android Open Source Project28527d22009-03-03 19:31:44 -08003791 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003792 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3793 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003794 if (!checkDumpPermission(mContext, TAG, writer)) return;
3795
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003796 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003797 }
3798
lucaslin99473f62020-12-10 15:10:54 +08003799 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3800 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3801 != PackageManager.PERMISSION_GRANTED) {
3802 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003803 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003804 + " due to missing android.permission.DUMP permission");
3805 return false;
3806 } else {
3807 return true;
3808 }
3809 }
3810
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003811 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003812 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003813
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003814 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003815 dumpNetworkDiagnostics(pw);
3816 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003817 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003818 dumpNetworks(pw);
3819 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003820 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003821 dumpNetworkRequests(pw);
3822 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003823 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3824 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3825 dumpTrafficController(pw, fd, verbose);
3826 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003827 }
Erik Kline9647f382015-06-05 17:47:34 +09003828
Junyu Lai0da479b2022-04-20 15:06:29 +08003829 pw.println("NetworkProviders for:");
3830 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003831 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003832 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003833 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003834 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003835 pw.println();
3836
Chalard Jean5b409c72021-02-04 13:12:59 +09003837 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003838 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003839 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003840 pw.println("none");
3841 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003842 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003843 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003844 pw.println();
3845
James Mattis8b298a02021-06-01 22:34:04 -07003846 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003847 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003848 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003849 pw.decreaseIndent();
3850 pw.println();
3851
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003852 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003853 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003854 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003855 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003856 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003857
junyulaif2c67e42018-08-07 19:50:45 +08003858 pw.println("Status for known UIDs:");
3859 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003860 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003861 for (int i = 0; i < size; i++) {
3862 // Don't crash if the array is modified while dumping in bugreports.
3863 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003864 final int uid = mUidBlockedReasons.keyAt(i);
3865 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3866 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003867 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003868 } catch (ArrayIndexOutOfBoundsException e) {
3869 pw.println(" ArrayIndexOutOfBoundsException");
3870 } catch (ConcurrentModificationException e) {
3871 pw.println(" ConcurrentModificationException");
3872 }
3873 }
3874 pw.println();
3875 pw.decreaseIndent();
3876
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003877 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003878 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003879 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003880 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003881 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003882
Junyu Lai0da479b2022-04-20 15:06:29 +08003883 pw.println("Network Offers:");
3884 pw.increaseIndent();
3885 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3886 pw.println(offerInfo.offer);
3887 }
3888 pw.decreaseIndent();
3889 pw.println();
3890
Robert Greenwalt94e22142014-07-30 16:31:24 -07003891 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003892
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003893 pw.println();
markchien5e866652019-09-30 14:40:57 +08003894 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003895
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003896 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003897 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003898
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003899 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003900 dumpCloseFrozenAppSockets(pw);
3901
3902 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003903 dumpBpfProgramStatus(pw);
3904
3905 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003906
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003907 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003908 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003909 pw.println("mNetworkRequestInfoLogs (most recent first):");
3910 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003911 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003912 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003913
3914 pw.println();
3915 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3916 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003917 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003918 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003919
3920 pw.println();
3921 pw.println("NetTransition WakeLock activity (most recent first):");
3922 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003923 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3924 pw.println("total releases: " + mTotalWakelockReleases);
3925 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3926 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3927 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3928 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3929 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3930 }
James Mattiscb1e0362021-04-06 17:07:42 -07003931 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003932
3933 pw.println();
3934 pw.println("bandwidth update requests (by uid):");
3935 pw.increaseIndent();
3936 synchronized (mBandwidthRequests) {
3937 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3938 pw.println("[" + mBandwidthRequests.keyAt(i)
3939 + "]: " + mBandwidthRequests.valueAt(i));
3940 }
3941 }
3942 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003943 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003944
James Mattiscb1e0362021-04-06 17:07:42 -07003945 pw.println();
3946 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3947 pw.increaseIndent();
3948 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003949 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003950 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003951
3952 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003953
3954 pw.println();
3955 pw.println("Permission Monitor:");
3956 pw.increaseIndent();
3957 mPermissionMonitor.dump(pw);
3958 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003959
3960 pw.println();
3961 pw.println("Legacy network activity:");
3962 pw.increaseIndent();
3963 mNetworkActivityTracker.dump(pw);
3964 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003965 }
3966
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003967 private void dumpNetworks(IndentingPrintWriter pw) {
3968 for (NetworkAgentInfo nai : networksSortedById()) {
3969 pw.println(nai.toString());
3970 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003971 pw.println("Nat464Xlat:");
3972 pw.increaseIndent();
3973 nai.dumpNat464Xlat(pw);
3974 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003975 pw.println(String.format(
3976 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3977 nai.numForegroundNetworkRequests(),
3978 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3979 nai.numBackgroundNetworkRequests(),
3980 nai.numNetworkRequests()));
3981 pw.increaseIndent();
3982 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3983 pw.println(nai.requestAt(i).toString());
3984 }
3985 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003986 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003987 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003988 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003989 pw.decreaseIndent();
3990 pw.decreaseIndent();
3991 }
3992 }
3993
James Mattis8b298a02021-06-01 22:34:04 -07003994 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3995 if (!mProfileNetworkPreferences.isEmpty()) {
3996 pw.println("Profile preferences:");
3997 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003998 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003999 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004000 }
James Mattis8b298a02021-06-01 22:34:04 -07004001 if (!mOemNetworkPreferences.isEmpty()) {
4002 pw.println("OEM preferences:");
4003 pw.increaseIndent();
4004 pw.println(mOemNetworkPreferences);
4005 pw.decreaseIndent();
4006 }
4007 if (!mMobileDataPreferredUids.isEmpty()) {
4008 pw.println("Mobile data preferred UIDs:");
4009 pw.increaseIndent();
4010 pw.println(mMobileDataPreferredUids);
4011 pw.decreaseIndent();
4012 }
James Mattis45d81842021-01-10 14:24:24 -08004013
James Mattis8b298a02021-06-01 22:34:04 -07004014 pw.println("Default requests:");
4015 pw.increaseIndent();
4016 dumpPerAppDefaultRequests(pw);
4017 pw.decreaseIndent();
4018 }
4019
4020 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004021 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4022 if (mDefaultRequest == defaultRequest) {
4023 continue;
4024 }
4025
James Mattis8b298a02021-06-01 22:34:04 -07004026 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4027 final String networkOutput;
4028 if (null == satisfier) {
4029 networkOutput = "null";
4030 } else if (mNoServiceNetwork.equals(satisfier)) {
4031 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004032 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004033 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004034 }
James Mattis8b298a02021-06-01 22:34:04 -07004035 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4036 ? "" : " asUid: " + defaultRequest.mAsUid;
4037 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4038 + defaultRequest.mPid + asUidString + "]";
4039 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4040 + " Preference order: " + defaultRequest.mPreferenceOrder
4041 + " Tracked UIDs: " + defaultRequest.getUids();
4042 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004043 }
4044 }
4045
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004046 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004047 NetworkRequestInfo[] infos = null;
4048 while (infos == null) {
4049 try {
4050 infos = requestsSortedById();
4051 } catch (ConcurrentModificationException e) {
4052 // mNetworkRequests should only be accessed from handler thread, except dump().
4053 // As dump() is never called in normal usage, it would be needlessly expensive
4054 // to lock the collection only for its benefit. Instead, retry getting the
4055 // requests if ConcurrentModificationException is thrown during dump().
4056 }
4057 }
4058 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004059 pw.println(nri.toString());
4060 }
4061 }
4062
Ken Chene6d511f2022-01-25 11:10:42 +08004063 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4064 boolean verbose) {
4065 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004066 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004067 } catch (ServiceSpecificException e) {
4068 pw.println(e.getMessage());
4069 } catch (IOException e) {
4070 loge("Dump BPF maps failed, " + e);
4071 }
4072 }
4073
Chalard Jean524f0b12021-10-25 21:11:56 +09004074 private void dumpAllRequestInfoLogsToLogcat() {
4075 try (PrintWriter logPw = new PrintWriter(new Writer() {
4076 @Override
4077 public void write(final char[] cbuf, final int off, final int len) {
4078 // This method is called with 0-length and 1-length arrays for empty strings
4079 // or strings containing only the DEL character.
4080 if (len <= 1) return;
4081 Log.e(TAG, new String(cbuf, off, len));
4082 }
4083 @Override public void flush() {}
4084 @Override public void close() {}
4085 })) {
4086 mNetworkRequestInfoLogs.dump(logPw);
4087 }
4088 }
4089
Hugo Benichia480ba52018-09-03 08:19:02 +09004090 /**
4091 * Return an array of all current NetworkAgentInfos sorted by network id.
4092 */
4093 private NetworkAgentInfo[] networksSortedById() {
4094 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004095 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004096 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004097 return networks;
4098 }
4099
4100 /**
4101 * Return an array of all current NetworkRequest sorted by request id.
4102 */
James Mattis258ea3c2020-11-15 15:04:40 -08004103 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004104 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004105 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004106 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004107 // Sort the array based off the NRI containing the min requestId in its requests.
4108 Arrays.sort(requests,
4109 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4110 Comparator.comparingInt(req -> req.requestId)).requestId
4111 )
4112 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004113 return requests;
4114 }
4115
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004116 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004117 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004118 if (officialNai != null && officialNai.equals(nai)) return true;
4119 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004120 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004121 " - " + nai);
4122 }
4123 return false;
4124 }
4125
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004126 private boolean isDisconnectRequest(Message msg) {
4127 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4128 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4129 return info.getState() == NetworkInfo.State.DISCONNECTED;
4130 }
4131
Robert Greenwalt2034b912009-08-12 16:08:25 -07004132 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004133 private class NetworkStateTrackerHandler extends Handler {
4134 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004135 super(looper);
4136 }
4137
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004138 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004139 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4140 final NetworkAgentInfo nai = arg.first;
4141 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004142 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004143 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004144 }
4145 return;
4146 }
4147
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004148 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004149 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004150 return;
4151 }
4152
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004153 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004154 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09004155 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
4156 final NetworkCapabilities sanitized =
4157 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004158 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004159 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004160 break;
4161 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004162 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004163 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004164 processLinkPropertiesFromAgent(nai, newLp);
4165 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004166 break;
4167 }
4168 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004169 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004170 updateNetworkInfo(nai, info);
4171 break;
4172 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004173 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4174 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
4175 updateLocalNetworkConfig(nai, config);
4176 break;
4177 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004178 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004179 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004180 break;
4181 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004182 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004183 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004184 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004185 // Note that if the NAI had been connected, this would affect the
4186 // score, and therefore would require re-mixing the score and performing
4187 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004188 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004189 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4190 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004191 // Mark the network as temporarily accepting partial connectivity so that it
4192 // will be validated (and possibly become default) even if it only provides
4193 // partial internet access. Note that if user connects to partial connectivity
4194 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4195 // out of wifi coverage) and if the same wifi is available again, the device
4196 // will auto connect to this wifi even though the wifi has "no internet".
4197 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004198 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004199 break;
4200 }
junyulai011b1f12019-01-03 18:50:15 +08004201 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004202 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004203 break;
4204 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004205 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004206 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004207 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004208
4209 if (isLegacyLockdownNai(nai)
4210 && (underlying == null || underlying.size() != 1)) {
4211 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4212 + " must have exactly one underlying network: " + underlying);
4213 }
4214
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004215 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4216 nai.declaredUnderlyingNetworks = (underlying != null)
4217 ? underlying.toArray(new Network[0]) : null;
4218
4219 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4220 if (DBG) {
4221 log(nai.toShortString() + " changed underlying networks to "
4222 + Arrays.toString(nai.declaredUnderlyingNetworks));
4223 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004224 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004225 notifyIfacesChangedForNetworkStats();
4226 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004227 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004228 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004229 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4230 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4231 nai.teardownDelayMs = msg.arg1;
4232 } else {
4233 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4234 }
Chalard Jean550b5212021-03-05 23:07:53 +09004235 break;
4236 }
4237 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4238 nai.setLingerDuration((int) arg.second);
4239 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004240 }
Tyler Wear72388212021-09-09 14:49:02 -07004241 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4242 DscpPolicy policy = (DscpPolicy) arg.second;
4243 if (mDscpPolicyTracker != null) {
4244 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4245 }
4246 break;
4247 }
4248 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4249 if (mDscpPolicyTracker != null) {
4250 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4251 }
4252 break;
4253 }
4254 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4255 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004256 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004257 }
4258 break;
4259 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004260 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004261 if (!nai.everConnected()) {
4262 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4263 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004264 teardownUnneededNetwork(nai);
4265 break;
4266 }
4267
4268 if (nai.isDestroyed()) {
4269 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4270 + ", ignoring");
4271 break;
4272 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004273
4274 final int timeoutMs = (int) arg.second;
4275 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4276 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4277 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4278 }
4279
4280 // Marking a network awaiting replacement is used to ensure that any requests
4281 // satisfied by the network do not switch to another network until a
4282 // replacement is available or the wait for a replacement times out.
4283 // If the network is inactive (i.e., nascent or lingering), then there are no
4284 // such requests, and there is no point keeping it. Just tear it down.
4285 // Note that setLingerDuration(0) cannot be used to do this because the network
4286 // could be nascent.
4287 nai.clearInactivityState();
4288 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4289 Log.d(TAG, nai.toShortString()
4290 + " marked awaiting replacement is unneeded, tearing down instead");
4291 teardownUnneededNetwork(nai);
4292 break;
4293 }
4294
4295 Log.d(TAG, "Marking " + nai.toShortString()
4296 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4297 destroyNativeNetwork(nai);
4298
4299 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4300 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4301 // consider the fact that the network could already have disconnected or been
4302 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4303 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4304 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4305 mKeepaliveTracker.handleStopAllKeepalives(nai,
4306 SocketKeepalive.ERROR_INVALID_NETWORK);
4307
4308 nai.updateScoreForNetworkAgentUpdate();
4309 // This rematch is almost certainly not going to result in any changes, because
4310 // the destroyed flag is only just above the "current satisfier wins"
4311 // tie-breaker. But technically anything that affects scoring should rematch.
4312 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004313 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004314 break;
4315 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004316 }
4317 }
4318
4319 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004320 final int netId = msg.arg2;
4321 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004322 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004323 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004324 switch (msg.what) {
4325 default:
4326 return false;
lucasline117e2e2019-10-22 18:27:33 +08004327 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004328 if (nai == null) {
4329 break;
4330 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004331 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4332 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004333 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004334 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004335 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004336 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004337 if (probePrivateDnsCompleted) {
4338 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4339 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004340 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004341 }
4342 // Only show the notification when the private DNS is broken and the
4343 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004344 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004345 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4346 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004347 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004348 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4349 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4350 // private DNS is broken, it means this network is being reevaluated.
4351 // Either probing private DNS is not necessary any more or it hasn't been
4352 // done yet. In either case, the networkCapabilities should be updated to
4353 // reflect the new status.
4354 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004355 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004356 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004357 }
4358 break;
4359 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004360 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004361 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4362
Erik Kline31b4a9e2018-01-11 21:07:29 +09004363 if (nai == null) break;
4364
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004365 handleNetworkTested(nai, results.mTestResult,
4366 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004367 break;
4368 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004369 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004370 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004371 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004372 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004373 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004374 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004375 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4376 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004377 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004378 if (nai == null) {
4379 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4380 break;
4381 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004382 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004383 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004384 (PendingIntent) msg.obj,
4385 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004386 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004387 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004388 break;
4389 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004390 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004391 if (nai == null) break;
4392
Erik Kline9a62f012018-03-21 07:18:33 -07004393 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004394 break;
4395 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004396 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004397 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004398 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004399 break;
4400 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004401 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004402 return true;
4403 }
4404
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004405 private void handleNetworkTested(
4406 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004407 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4408 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004409 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004410
4411 // If there is any kind of working networking, then the NAI has been evaluated
4412 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4413 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004414 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004415 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004416 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4417 // any callback that receives onAvailable for that rematch receives an extra caps
4418 // callback. To prevent that, update the score in the agent so the updates below won't
4419 // see an update to both caps and score at the same time.
4420 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004421 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4422
he_won.hwang881307a2022-03-15 21:23:52 +09004423 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4424 // Assume the validation failure is due to a temporary failure after roaming
4425 // and ignore it. NetworkMonitor will continue to retry validation. If it
4426 // continues to fail after the block timeout expires, the network will be
4427 // marked unvalidated. If it succeeds, then validation state will not change.
4428 return;
4429 }
4430
Chalard Jean254bd162022-08-25 13:04:51 +09004431 final boolean wasValidated = nai.isValidated();
4432 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004433 final boolean wasPortal = nai.captivePortalDetected();
4434 nai.setPartialConnectivity(partial);
4435 nai.setCaptivePortalDetected(portal);
4436 nai.updateScoreForNetworkAgentUpdate();
4437 final boolean partialConnectivityChanged = (wasPartial != partial);
4438 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004439
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004440 if (DBG) {
4441 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4442 ? " with redirect to " + redirectUrl
4443 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004444 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004445 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004446 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004447 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004448 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004449 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004450 if (valid) {
4451 handleFreshlyValidatedNetwork(nai);
4452 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4453 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004454 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004455 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004456 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004457 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004458 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004459 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004460 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004461 NotificationType.PRIVATE_DNS_BROKEN);
4462 // If network becomes valid, the hasShownBroken should be reset for
4463 // that network so that the notification will be fired when the private
4464 // DNS is broken again.
4465 nai.networkAgentConfig.hasShownBroken = false;
4466 }
4467 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004468 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004469 } else if (portalChanged) {
4470 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004471 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004472 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4473 nai.onPreventAutomaticReconnect();
4474 teardownUnneededNetwork(nai);
4475 return;
4476 } else {
4477 updateCapabilitiesForNetwork(nai);
4478 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004479 } else if (becameEvaluated) {
4480 // If valid or partial connectivity changed, updateCapabilities* has
4481 // done the rematch.
4482 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004483 }
4484 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004485
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004486 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004487 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004488 nai.onValidationStatusChanged(
4489 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4490 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004491
4492 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004493 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004494 // immediately. Re-notify partial connectivity silently if no internet
4495 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004496 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004497 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004498 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4499 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004500 }
4501
Chalard Jean254bd162022-08-25 13:04:51 +09004502 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004503 handleNetworkUnvalidated(nai);
4504 }
4505 }
4506
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004507 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4508 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4509 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4510 // Do not avoid captive portal when network is wear proxy.
4511 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4512 }
4513
Calvin Ondada1452016-10-11 15:10:46 -07004514 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004515 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4516 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004517 }
4518
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004519 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4520 switch (msg.what) {
4521 default:
4522 return false;
4523 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4524 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4525 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4526 handleLingerComplete(nai);
4527 }
4528 break;
4529 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004530 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4531 handleNetworkAgentRegistered(msg);
4532 break;
4533 }
4534 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4535 handleNetworkAgentDisconnected(msg);
4536 break;
4537 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004538 }
4539 return true;
4540 }
4541
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004542 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004543 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004544 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004545 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004546 maybeHandleNetworkAgentMessage(msg);
4547 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004548 }
4549 }
4550
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004551 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004552 private final int mNetId;
4553 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004554
4555 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004556 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004557 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004558 }
4559
4560 @Override
4561 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4562 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004563 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004564 }
4565
4566 @Override
4567 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004568 // Legacy version of notifyNetworkTestedWithExtras.
4569 // Would only be called if the system has a NetworkStack module older than the
4570 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004571 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004572 }
4573
4574 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004575 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004576 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4577 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004578 final Message msg = mTrackerHandler.obtainMessage(
4579 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004580 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004581 new NetworkTestedResults(
4582 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004583 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004584
4585 // Invoke ConnectivityReport generation for this Network test event.
4586 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4587 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004588
Cody Kestingf1120be2020-08-03 18:01:40 -07004589 // NetworkMonitor reports the network validation result as a bitmask while
4590 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4591 // logical value for ConnectivityDiagnostics.
4592 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4593 p.result);
4594
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004595 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004596 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004597 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4598 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4599
Aaron Huang959d3642021-01-21 15:47:41 +08004600 ConnectivityReportEvent reportEvent =
4601 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4602 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004603 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004604 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004605 }
4606
4607 @Override
4608 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4609 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4610 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004611 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004612 }
4613
4614 @Override
lucasline117e2e2019-10-22 18:27:33 +08004615 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4616 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4617 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004618 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004619 }
4620
4621 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004622 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4623 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4624 EVENT_CAPPORT_DATA_CHANGED,
4625 0, mNetId, data));
4626 }
4627
4628 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004629 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004630 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004631 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004632
4633 final PendingIntent pendingIntent;
4634 // Only the system server can register notifications with package "android"
4635 final long token = Binder.clearCallingIdentity();
4636 try {
paulhu7746e4e2020-06-09 19:07:03 +08004637 pendingIntent = PendingIntent.getBroadcast(
4638 mContext,
4639 0 /* requestCode */,
4640 intent,
4641 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004642 } finally {
4643 Binder.restoreCallingIdentity(token);
4644 }
4645 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4646 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004647 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004648 }
4649
4650 @Override
4651 public void hideProvisioningNotification() {
4652 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004653 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004654 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004655
4656 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004657 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004658 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004659 }
4660
4661 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004662 public int getInterfaceVersion() {
4663 return this.VERSION;
4664 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004665
4666 @Override
4667 public String getInterfaceHash() {
4668 return this.HASH;
4669 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004670 }
4671
Cody Kestingf1120be2020-08-03 18:01:40 -07004672 /**
4673 * Converts the given NetworkMonitor-specific validation result bitmask to a
4674 * ConnectivityDiagnostics-specific validation result int.
4675 */
4676 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4677 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4678 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4679 }
4680 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4681 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4682 }
4683 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4684 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4685 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4686 }
4687
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004688 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004689 log("Data stall detected with methods: " + p.detectionMethod);
4690
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004691 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004692 int detectionMethod = 0;
4693 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4694 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4695 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4696 }
4697 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4698 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4699 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4700 p.tcpMetricsCollectionPeriodMillis);
4701 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004702 }
4703
Cody Kestingf53a0752020-04-15 12:33:28 -07004704 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004705 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004706 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004707
4708 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4709 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4710 // the cost of going through two handlers.
4711 mConnectivityDiagnosticsHandler.sendMessage(msg);
4712 }
4713
Cody Kestingb37958e2020-05-15 10:36:01 -07004714 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4715 return (p.detectionMethod & detectionMethod) != 0;
4716 }
4717
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004718 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4719 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004720 }
4721
Erik Klinea73af002018-06-26 18:53:43 +09004722 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4723 if (nai == null) return;
4724 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4725 // in order to restart a validation pass from within netd.
4726 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4727 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004728 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004729 }
4730 }
4731
Erik Kline31b4a9e2018-01-11 21:07:29 +09004732 private void handlePrivateDnsSettingsChanged() {
4733 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4734
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004735 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004736 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004737 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004738 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4739 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004740 }
4741 }
4742
Erik Kline9a62f012018-03-21 07:18:33 -07004743 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4744 // Private DNS only ever applies to networks that might provide
4745 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004746 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004747
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004748 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004749 // schedule DNS resolutions. If a DNS resolution is required the
4750 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004751 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004752
4753 // With Private DNS bypass support, we can proceed to update the
4754 // Private DNS config immediately, even if we're in strict mode
4755 // and have not yet resolved the provider name into a set of IPs.
4756 updatePrivateDns(nai, cfg);
4757 }
4758
4759 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4760 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004761 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004762 }
4763
dalyk1720e542018-03-05 12:42:22 -05004764 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4765 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4766 if (nai == null) {
4767 return;
4768 }
4769 mDnsManager.updatePrivateDnsValidation(update);
4770 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4771 }
4772
paulhu7c0a2e62021-01-08 00:51:49 +08004773 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004774 int prefixLength) {
4775 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4776 if (nai == null) return;
4777
paulhu7c0a2e62021-01-08 00:51:49 +08004778 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4779 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004780
4781 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004782 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004783 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004784 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004785 prefixLength);
4786 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004787 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004788 return;
4789 }
4790 }
4791
Lorenzo Colittid523d142020-04-01 20:16:30 +09004792 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004793 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4794 }
4795
Hai Shalome58bdc62021-01-11 18:45:34 -08004796 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004797 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004798 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004799 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4800 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4801 }
4802
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004803 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004804 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004805 * @param nai the agent info to update
4806 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004807 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004808 */
junyulai2b6f0c22021-02-03 20:15:30 +08004809 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4810 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4811 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004812 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004813 // one lingered request, set inactive.
4814 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004815 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004816 if (DBG) log("Unsetting inactive " + nai.toShortString());
4817 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004818 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004819 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004820 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004821 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4822 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004823 }
junyulai2b6f0c22021-02-03 20:15:30 +08004824 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004825 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004826 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004827 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004828 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004829 }
4830
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004831 private void handleNetworkAgentRegistered(Message msg) {
4832 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4833 if (!mNetworkAgentInfos.contains(nai)) {
4834 return;
4835 }
4836
4837 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4838 if (VDBG) log("NetworkAgent registered");
4839 } else {
4840 loge("Error connecting NetworkAgent");
4841 mNetworkAgentInfos.remove(nai);
4842 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004843 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004844 synchronized (mNetworkForNetId) {
4845 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004846 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004847 mNetIdManager.releaseNetId(nai.network.getNetId());
4848 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004849 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004850 }
4851 }
4852 }
Paul Jensend5f53392014-11-25 15:26:53 -05004853
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004854 @VisibleForTesting
4855 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004856 // The feature of creating the networks immediately was slated for U, but race conditions
4857 // detected late required this was flagged off.
4858 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4859 // in NetworkAgentTest.
4860 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004861 }
4862
4863 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4864 @NonNull NetworkInfo.State state) {
4865 if (nai.isCreated()) return false;
4866 if (state == NetworkInfo.State.CONNECTED) return true;
4867 if (state != NetworkInfo.State.CONNECTING) {
4868 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004869 if (shouldCreateNetworksImmediately()) {
4870 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4871 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004872 return false;
4873 }
4874 return nai.isVPN() || shouldCreateNetworksImmediately();
4875 }
4876
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004877 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004878 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004879 }
4880
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004881 @VisibleForTesting
4882 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004883 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004884 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004885
4886 // If the network never roamed, return false. The check below is not sufficient if time
4887 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4888 if (nai.lastRoamTime == 0) return false;
4889
he_won.hwang881307a2022-03-15 21:23:52 +09004890 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4891 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004892 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004893 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004894 final long currentTimeMs = SystemClock.elapsedRealtime();
4895 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004896 if (timeSinceLastRoam <= blockTimeOut) {
4897 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4898 return true;
4899 }
4900 }
4901 return false;
4902 }
4903
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004904 private void handleNetworkAgentDisconnected(Message msg) {
4905 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004906 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004907 }
4908
Chalard Jeand9fffc32018-05-11 20:19:20 +09004909 // Destroys a network, remove references to it from the internal state managed by
4910 // ConnectivityService, free its interfaces and clean up.
4911 // Must be called on the Handler thread.
4912 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004913 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004914
4915 if (!mNetworkAgentInfos.contains(nai)) return;
4916
Chalard Jeand9fffc32018-05-11 20:19:20 +09004917 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004918 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004919 }
lucaslinb25c9a62019-02-12 15:30:13 +08004920 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004921 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004922 // A network agent has disconnected.
4923 // TODO - if we move the logic to the network agent (have them disconnect
4924 // because they lost all their requests or because their score isn't good)
4925 // then they would disconnect organically, report their new state and then
4926 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004927 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004928 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4929 null, null);
4930 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004931 final boolean wasDefault = isDefaultNetwork(nai);
4932 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004933 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004934 }
4935 notifyIfacesChangedForNetworkStats();
4936 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4937 // by other networks that are already connected. Perhaps that can be done by
4938 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4939 // of rematchAllNetworksAndRequests
4940 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004941 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004942
4943 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004944 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4945 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004946 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004947 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004948 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004949 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004950 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004951 synchronized (mNetworkForNetId) {
4952 // Remove the NetworkAgent, but don't mark the netId as
4953 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004954 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004955 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004956 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004957 // Update allowed network lists in netd. This should be called after removing nai
4958 // from mNetworkAgentInfos.
4959 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004960 // Remove all previously satisfied requests.
4961 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004962 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004963 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004964 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004965 if (currentNetwork != null
4966 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004967 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004968 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4969 // rematch not to keep disconnected agents instead of setting it here ; this
4970 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004971 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004972 for (final NetworkOfferInfo noi : mNetworkOffers) {
4973 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004974 }
James Mattise3ef1912020-12-20 11:09:58 -08004975
Chalard Jean5b409c72021-02-04 13:12:59 +09004976 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004977 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004978 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004979 // network, because while incorrect this is the closest to the old (also
4980 // incorrect) behavior.
4981 mNetworkActivityTracker.updateDataActivityTracking(
4982 null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004983 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004984 ensureNetworkTransitionWakelock(nai.toShortString());
4985 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004986 }
4987 }
junyulai2b6f0c22021-02-03 20:15:30 +08004988 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004989 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004990 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004991 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004992 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004993 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004994 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004995
Aaron Huang9fe47be2021-06-08 13:11:45 +08004996 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
4997 // The obvious place to do this would be in makeDefault(), however makeDefault() is
4998 // not called by the rematch in this case. This is because the code above unset
4999 // this network from the default request's satisfier, and that is what the rematch
5000 // is using as its source data to know what the old satisfier was. So as far as the
5001 // rematch above is concerned, the old default network was null.
5002 // Therefore if there is no new default, the default network was null and is still
5003 // null, thus there was no change so makeDefault() is not called. So if the old
5004 // network had a proxy and there is no new default, the proxy tracker should be told
5005 // that there is no longer a default proxy.
5006 // Strictly speaking this is not essential because having a proxy setting when
5007 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5008 mProxyTracker.setDefaultProxy(null);
5009 }
5010
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005011 // Immediate teardown.
5012 if (nai.teardownDelayMs == 0) {
5013 destroyNetwork(nai);
5014 return;
5015 }
5016
5017 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005018 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305019 try {
5020 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5021 } catch (RemoteException e) {
5022 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5023 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005024 }
5025 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5026 }
5027
5028 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005029 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005030 // Tell netd to clean up the configuration for this network
5031 // (routing rules, DNS, etc).
5032 // This may be slow as it requires a lot of netd shelling out to ip and
5033 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005034 // after we've rematched networks with requests (which might change the default
5035 // network or service a new request from an app), so network traffic isn't interrupted
5036 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005037 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005038 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005039 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005040 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5041 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5042 // false if the network was never created.
5043 // TODO: delete when S is no longer supported.
5044 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005045 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005046 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005047 }
5048
Ken Chen6df7a902021-04-09 15:08:42 +08005049 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005050 try {
5051 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005052 final NativeNetworkConfig config;
5053 if (nai.isVPN()) {
5054 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005055 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005056 return false;
5057 }
5058 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5059 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005060 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005061 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005062 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005063 final boolean hasLocalCap =
5064 nai.networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
5065 config = new NativeNetworkConfig(nai.network.getNetId(),
5066 hasLocalCap ? NativeNetworkType.PHYSICAL_LOCAL : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005067 getNetworkPermission(nai.networkCapabilities),
5068 false /* secure */,
5069 VpnManager.TYPE_VPN_NONE,
5070 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005071 }
Ken Chen6df7a902021-04-09 15:08:42 +08005072 mNetd.networkCreate(config);
5073 mDnsResolver.createNetworkCache(nai.network.getNetId());
5074 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
5075 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08005076 return true;
5077 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005078 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005079 return false;
5080 }
5081 }
5082
Ken Chen6df7a902021-04-09 15:08:42 +08005083 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005084 if (mDscpPolicyTracker != null) {
5085 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5086 }
Luke Huangfdd11f82019-04-09 18:41:49 +08005087 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005088 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005089 } catch (RemoteException | ServiceSpecificException e) {
5090 loge("Exception destroying network(networkDestroy): " + e);
5091 }
5092 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005093 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005094 } catch (RemoteException | ServiceSpecificException e) {
5095 loge("Exception destroying network: " + e);
5096 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005097 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5098 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5099 // gets created, could add data to DnsManager data structures that will never get deleted.
5100 mDnsManager.removeNetwork(nai.network);
5101
5102 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005103 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005104 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5105 }
5106
Chalard Jean254bd162022-08-25 13:04:51 +09005107 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005108 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005109 }
5110
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005111 // If this method proves to be too slow then we can maintain a separate
5112 // pendingIntent => NetworkRequestInfo map.
5113 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5114 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005115 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5116 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5117 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005118 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005119 return entry.getValue();
5120 }
5121 }
5122 return null;
5123 }
5124
Chalard Jean524f0b12021-10-25 21:11:56 +09005125 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005126 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005127 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5128 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5129 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5130 // bug is fixed.
5131 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005132 throw new IllegalStateException("This NRI is already registered. New : " + nri
5133 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005134 }
5135 }
5136 }
5137 }
5138
Chalard Jeanac9ace02022-01-26 16:54:05 +09005139 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5140 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005141 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005142 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5143 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005144 }
5145 return false;
5146 }
5147
James Mattisf7027322020-12-13 16:28:14 -08005148 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005149 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005150 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5151 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5152 final NetworkRequestInfo existingRequest =
5153 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005154 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005155 if (DBG) {
5156 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5157 + nri.mRequests.get(0) + " because their intents matched.");
5158 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005159 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005160 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005161 }
Erik Kline05f2b402015-04-30 12:58:40 +09005162 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005163 }
5164
James Mattisf7027322020-12-13 16:28:14 -08005165 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005166 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005167 }
5168
James Mattis3ce3d3c2021-02-09 18:18:28 -08005169 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005170 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005171 for (final NetworkRequestInfo nri : nris) {
5172 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005173 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005174 for (final NetworkRequest req : nri.mRequests) {
5175 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005176 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005177 if (req.isListen()) {
5178 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5179 if (req.networkCapabilities.hasSignalStrength()
5180 && network.satisfiesImmutableCapabilitiesOf(req)) {
5181 updateSignalStrengthThresholds(network, "REGISTER", req);
5182 }
James Mattisf7027322020-12-13 16:28:14 -08005183 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005184 }
5185 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005186
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005187 // If this NRI has a satisfier already, it is replacing an older request that
5188 // has been removed. Track it.
5189 final NetworkRequest activeRequest = nri.getActiveRequest();
5190 if (null != activeRequest) {
5191 // If there is an active request, then for sure there is a satisfier.
5192 nri.getSatisfier().addRequest(activeRequest);
5193 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005194 }
James Mattisf7027322020-12-13 16:28:14 -08005195
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005196 if (mFlags.noRematchAllRequestsOnRegister()) {
5197 rematchNetworksAndRequests(nris);
5198 } else {
5199 rematchAllNetworksAndRequests();
5200 }
James Mattis45d81842021-01-10 14:24:24 -08005201
Chalard Jean0354d8c2021-01-12 10:58:56 +09005202 // Requests that have not been matched to a network will not have been sent to the
5203 // providers, because the old satisfier and the new satisfier are the same (null in this
5204 // case). Send these requests to the providers.
5205 for (final NetworkRequestInfo nri : nris) {
5206 for (final NetworkOfferInfo noi : mNetworkOffers) {
5207 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005208 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005209 }
5210 }
5211
James Mattisf7027322020-12-13 16:28:14 -08005212 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5213 final int callingUid) {
5214 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005215 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005216 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5217 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5218 handleReleaseNetworkRequest(
5219 nri.mRequests.get(0),
5220 callingUid,
5221 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005222 }
5223 }
5224
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005225 // Determines whether the network is the best (or could become the best, if it validated), for
5226 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5227 // on the value of reason:
5228 //
5229 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5230 // then it should be torn down.
5231 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5232 // then it should be lingered.
5233 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005234 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005235
Chalard Jean254bd162022-08-25 13:04:51 +09005236 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005237 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5238 return false;
5239 }
5240
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005241 final int numRequests;
5242 switch (reason) {
5243 case TEARDOWN:
5244 numRequests = nai.numRequestNetworkRequests();
5245 break;
5246 case LINGER:
5247 numRequests = nai.numForegroundNetworkRequests();
5248 break;
5249 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005250 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005251 return true;
5252 }
5253
Chalard Jean947acd42021-03-08 22:29:27 +09005254 if (numRequests > 0) return false;
5255
Paul Jensende49eb12015-06-25 15:30:08 -04005256 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005257 if (reason == UnneededFor.LINGER
5258 && !nri.isMultilayerRequest()
5259 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005260 // Background requests don't affect lingering.
5261 continue;
5262 }
5263
James Mattis3d229892020-11-16 16:46:28 -08005264 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005265 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005266 }
5267 }
Paul Jensende49eb12015-06-25 15:30:08 -04005268 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005269 }
5270
James Mattis3d229892020-11-16 16:46:28 -08005271 private boolean isNetworkPotentialSatisfier(
5272 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
5273 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005274 // request, return immediately. For multilayer requests, check to see if any of the
5275 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005276 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5277 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005278 return false;
5279 }
5280 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005281 // This multilayer listen request is satisfied therefore no further requests need to be
5282 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005283 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005284 return false;
5285 }
James Mattis3d229892020-11-16 16:46:28 -08005286 // As non-multilayer listen requests have already returned, the below would only happen
5287 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005288 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005289 continue;
5290 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09005291 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08005292 // there is hope for it to become one if it validated, then it is needed.
5293 if (candidate.satisfies(req)) {
5294 // As soon as a network is found that satisfies a request, return. Specifically for
5295 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5296 // is important so as to not evaluate lower priority requests further in
5297 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005298 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5299 ? nri.getSatisfier() : null;
5300 // Note that this catches two important cases:
5301 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5302 // is currently satisfying the request. This is desirable when
5303 // cellular ends up validating but WiFi does not.
5304 // 2. Unvalidated WiFi will not be reaped when validated cellular
5305 // is currently satisfying the request. This is desirable when
5306 // WiFi ends up validating and out scoring cellular.
5307 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005308 }
5309 }
5310
5311 return false;
5312 }
5313
Erik Kline0c04b742016-07-07 16:50:58 +09005314 private NetworkRequestInfo getNriForAppRequest(
5315 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005316 // Looking up the app passed param request in mRequests isn't possible since it may return
5317 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5318 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005319 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5320 // to avoid potential race conditions when validating a package->uid mapping when sending
5321 // the callback on the very low-chance that an application shuts down prior to the callback
5322 // being sent.
5323 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5324 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005325
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005326 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005327 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005328 log(String.format("UID %d attempted to %s for unowned request %s",
5329 callingUid, requestedOperation, nri));
5330 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005331 }
Erik Kline0c04b742016-07-07 16:50:58 +09005332 }
5333
5334 return nri;
5335 }
5336
James Mattisf7027322020-12-13 16:28:14 -08005337 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5338 final String callingMethod) {
5339 if (nri.isMultilayerRequest()) {
5340 throw new IllegalStateException(
5341 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005342 }
5343 }
5344
James Mattisf7027322020-12-13 16:28:14 -08005345 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005346 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005347 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5348 // single NetworkRequest and thus does not apply to multilayer requests.
5349 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5350 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005351 return;
5352 }
James Mattis2516da32021-01-31 17:06:19 -08005353 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005354 return;
5355 }
James Mattisf7027322020-12-13 16:28:14 -08005356 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5357 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005358 }
5359 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005360 callCallbackForRequest(
5361 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005362 }
5363
James Mattisf7027322020-12-13 16:28:14 -08005364 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5365 final int callingUid,
5366 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005367 final NetworkRequestInfo nri =
5368 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5369 if (nri == null) {
5370 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005371 }
James Mattisf7027322020-12-13 16:28:14 -08005372 if (VDBG || (DBG && request.isRequest())) {
5373 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005374 }
5375 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005376 if (callOnUnavailable) {
5377 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5378 }
Erik Kline155a59a2015-11-25 12:49:38 +09005379 }
Erik Kline0c04b742016-07-07 16:50:58 +09005380
James Mattisa076c532020-12-02 14:12:41 -08005381 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005382 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005383 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005384 if (null == mNetworkRequests.remove(req)) {
5385 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5386 continue;
5387 }
James Mattisa076c532020-12-02 14:12:41 -08005388 if (req.isListen()) {
5389 removeListenRequestFromNetworks(req);
5390 }
5391 }
James Mattis8f036802021-06-20 16:26:01 -07005392 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005393 if (mDefaultNetworkRequests.remove(nri)) {
5394 // If this request was one of the defaults, then the UID rules need to be updated
5395 // WARNING : if the app(s) for which this network request is the default are doing
5396 // traffic, this will kill their connected sockets, even if an equivalent request
5397 // is going to be reinstated right away ; unconnected traffic will go on the default
5398 // until the new default is set, which will happen very soon.
5399 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5400 // remove ranges for those requests that won't have a replacement
5401 final NetworkAgentInfo satisfier = nri.getSatisfier();
5402 if (null != satisfier) {
5403 try {
paulhu0e79d952021-06-09 16:11:35 +08005404 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5405 satisfier.network.getNetId(),
5406 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005407 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005408 } catch (RemoteException e) {
5409 loge("Exception setting network preference default network", e);
5410 }
5411 }
5412 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005413
Junyu Lai00d92df2022-07-05 11:01:52 +08005414 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005415 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005416 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005417
5418 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005419 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005420 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005421 }
5422 }
5423
Chalard Jean0354d8c2021-01-12 10:58:56 +09005424 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5425 // needed for this offer.
5426 for (final NetworkOfferInfo noi : mNetworkOffers) {
5427 for (final NetworkRequest req : nri.mRequests) {
5428 if (req.isRequest() && noi.offer.neededFor(req)) {
5429 noi.offer.onNetworkUnneeded(req);
5430 }
5431 }
5432 }
James Mattisa076c532020-12-02 14:12:41 -08005433 }
5434
James Mattis3ce3d3c2021-02-09 18:18:28 -08005435 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5436 for (final NetworkRequestInfo nri : nris) {
5437 if (mDefaultRequest == nri) {
5438 // Make sure we never remove the default request.
5439 continue;
5440 }
5441 handleRemoveNetworkRequest(nri);
5442 }
5443 }
5444
James Mattisa076c532020-12-02 14:12:41 -08005445 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5446 // listens don't have a singular affected Network. Check all networks to see
5447 // if this listen request applies and remove it.
5448 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5449 nai.removeRequest(req.requestId);
5450 if (req.networkCapabilities.hasSignalStrength()
5451 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5452 updateSignalStrengthThresholds(nai, "RELEASE", req);
5453 }
5454 }
5455 }
5456
5457 /**
5458 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5459 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5460 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5461 */
5462 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5463 boolean wasKept = false;
5464 final NetworkAgentInfo nai = nri.getSatisfier();
5465 if (nai != null) {
5466 final int requestLegacyType = nri.getActiveRequest().legacyType;
5467 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5468 nai.removeRequest(nri.getActiveRequest().requestId);
5469 if (VDBG || DDBG) {
5470 log(" Removing from current network " + nai.toShortString()
5471 + ", leaving " + nai.numNetworkRequests() + " requests.");
5472 }
5473 // If there are still lingered requests on this network, don't tear it down,
5474 // but resume lingering instead.
5475 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005476 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005477 notifyNetworkLosing(nai, now);
5478 }
5479 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5480 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5481 teardownUnneededNetwork(nai);
5482 } else {
5483 wasKept = true;
5484 }
James Mattisa076c532020-12-02 14:12:41 -08005485 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5486 // Went from foreground to background.
5487 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005488 }
5489
Erik Kline0c04b742016-07-07 16:50:58 +09005490 // Maintain the illusion. When this request arrived, we might have pretended
5491 // that a network connected to serve it, even though the network was already
5492 // connected. Now that this request has gone away, we might have to pretend
5493 // that the network disconnected. LegacyTypeTracker will generate that
5494 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005495 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005496 boolean doRemove = true;
5497 if (wasKept) {
5498 // check if any of the remaining requests for this network are for the
5499 // same legacy type - if so, don't remove the nai
5500 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5501 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005502 if (otherRequest.legacyType == requestLegacyType
5503 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005504 if (DBG) log(" still have other legacy request - leaving");
5505 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005506 }
5507 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005508 }
5509
Erik Kline0c04b742016-07-07 16:50:58 +09005510 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005511 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005512 }
5513 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005514 }
5515 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005516
Junyu Lai00d92df2022-07-05 11:01:52 +08005517 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005518 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005519 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5520 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5521 }
5522
Lorenzo Colittid6459092016-07-04 12:55:44 +09005523 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005524 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005525 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005526 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005527 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005528 }
5529
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005530 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005531 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5532 enforceNetworkStackSettingsOrSetup();
5533 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5534 encodeBool(accept), encodeBool(always), network));
5535 }
5536
5537 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005538 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005539 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005540 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5541 }
5542
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005543 @Override
5544 public void setTestAllowBadWifiUntil(long timeMs) {
5545 enforceSettingsPermission();
5546 if (!Build.isDebuggable()) {
5547 throw new IllegalStateException("Does not support in non-debuggable build");
5548 }
5549
5550 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5551 throw new IllegalArgumentException("It should not exceed "
5552 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5553 }
5554
5555 mHandler.sendMessage(
5556 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5557 }
5558
chiachangwange0192a72023-02-06 13:25:01 +00005559 @Override
5560 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5561 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005562
5563 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5564 throw new IllegalArgumentException("Argument should not exceed "
5565 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5566 }
5567
5568 mHandler.sendMessage(
5569 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5570 }
5571
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005572 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5573 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5574 " accept=" + accept + " always=" + always);
5575
5576 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5577 if (nai == null) {
5578 // Nothing to do.
5579 return;
5580 }
5581
Chalard Jean254bd162022-08-25 13:04:51 +09005582 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005583 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005584 return;
5585 }
5586
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005587 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005588 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005589 }
5590
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005591 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5592 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005593 // If network becomes partial connectivity and user already accepted to use this
5594 // network, we should respect the user's option and don't need to popup the
5595 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005596 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005597 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005598 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005599 }
5600
5601 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005602 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005603 }
5604
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005605 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005606 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005607 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005608 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005609 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005610 }
5611
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005612 }
5613
lucaslin2240ef62019-03-12 13:08:03 +08005614 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5615 boolean always) {
5616 if (DBG) {
5617 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5618 + " always=" + always);
5619 }
5620
5621 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5622 if (nai == null) {
5623 // Nothing to do.
5624 return;
5625 }
5626
Chalard Jean254bd162022-08-25 13:04:51 +09005627 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005628 // The network validated while the dialog box was up. Take no action.
5629 return;
5630 }
5631
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005632 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5633 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005634 }
5635
5636 // TODO: Use the current design or save the user choice into IpMemoryStore.
5637 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005638 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005639 }
5640
5641 if (!accept) {
5642 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005643 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005644 // Tear down the network.
5645 teardownUnneededNetwork(nai);
5646 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005647 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5648 // result in a partial connectivity result which will be processed by
5649 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005650 //
5651 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5652 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005653 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005654 }
5655 }
5656
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005657 private void handleSetAvoidUnvalidated(Network network) {
5658 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005659 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005660 // Nothing to do. The network either disconnected or revalidated.
5661 return;
5662 }
Chalard Jean254bd162022-08-25 13:04:51 +09005663 if (0L == nai.getAvoidUnvalidated()) {
5664 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005665 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005666 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005667 }
5668 }
5669
Chalard Jean5fb43c72022-09-08 19:03:14 +09005670 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005671 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005672 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005673 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005674 }
5675
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005676 @Override
5677 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005678 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005679 mHandler.post(() -> {
5680 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5681 if (nai == null) return;
5682 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005683 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005684 });
5685 }
5686
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005687 /**
5688 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5689 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005690 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005691 * @param appExtras Bundle to use as intent extras for the captive portal application.
5692 * Must be treated as opaque to avoid preventing the captive portal app to
5693 * update its arguments.
5694 */
5695 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005696 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005697 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5698 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005699
5700 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5701 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005702 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5703 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005704 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5705
lucaslin75ff7022020-12-17 04:14:35 +08005706 final long token = Binder.clearCallingIdentity();
5707 try {
5708 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5709 } finally {
5710 Binder.restoreCallingIdentity(token);
5711 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005712 }
5713
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005714 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5715 private final Network mNetwork;
5716
5717 private CaptivePortalImpl(Network network) {
5718 mNetwork = network;
5719 }
5720
5721 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005722 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005723 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5724 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005725 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5726 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5727 // Since the network will be disconnected, skip notifying NetworkMonitor
5728 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005729 }
5730
Chiachang Wang938bfba2020-01-09 13:50:55 +08005731 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005732 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005733 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005734 }
5735
5736 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005737 public void appRequest(final int request) {
5738 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5739 if (nm == null) return;
5740
5741 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005742 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005743 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005744 }
5745 }
5746
5747 @Nullable
5748 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5749 // getNetworkAgentInfoForNetwork is thread-safe
5750 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5751 if (nai == null) return null;
5752
5753 // nai.networkMonitor() is thread-safe
5754 return nai.networkMonitor();
5755 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005756 }
5757
Hugo Benichic9048bc2016-09-14 23:23:08 +00005758 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005759 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005760 }
5761
Chalard Jean020b93a2022-09-01 13:20:14 +09005762 private boolean activelyPreferBadWifi() {
5763 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5764 }
5765
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005766 /**
5767 * Return whether the device should maintain continuous, working connectivity by switching away
5768 * from WiFi networks having no connectivity.
5769 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5770 */
5771 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005772 if (!checkNetworkStackPermission()) {
5773 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5774 }
5775 return avoidBadWifi();
5776 }
5777
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005778 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005779 ensureRunningOnConnectivityServiceThread();
5780 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005781 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005782 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005783 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005784 if (avoidBadWifi) {
5785 // If the device is now avoiding bad wifi, remove notifications that might have
5786 // been put up when the device didn't.
5787 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5788 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005789 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005790 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5791 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5792 for (final NetworkOfferInfo noi : offersToUpdate) {
5793 updateOfferScore(noi.offer);
5794 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005795 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005796 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005797 }
5798
Erik Kline95ecfee2016-10-02 18:02:14 +09005799 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005800 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005801 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005802 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005803 if (!configRestrict) {
5804 pw.println("Bad Wi-Fi avoidance: unrestricted");
5805 return;
5806 }
5807
5808 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5809 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005810 pw.println("Config restrict: " + configRestrict);
5811 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005812
Chalard Jeane0fdea32022-09-14 21:44:22 +09005813 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005814 String description;
5815 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005816 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005817 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005818 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005819 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005820 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005821 description = "avoid";
5822 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005823 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005824 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005825 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005826
5827 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5828 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005829 if (null == configValue) {
5830 description = "unset";
5831 } else if (configValue) {
5832 description = "force true";
5833 } else {
5834 description = "force false";
5835 }
5836 pw.println("Actively prefer bad wifi conf: " + description);
5837 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005838 pw.println("Network overrides:");
5839 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005840 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005841 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005842 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005843 }
5844 }
5845 pw.decreaseIndent();
5846 pw.decreaseIndent();
5847 }
5848
paulhu7746e4e2020-06-09 19:07:03 +08005849 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5850 // unify the method.
5851 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5852 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5853 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5854 return settingsComponent != null
5855 ? settingsComponent.getPackageName() : "com.android.settings";
5856 }
5857
lucaslinb1e8e382019-01-24 15:55:30 +08005858 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005859 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005860 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005861 switch (type) {
5862 case NO_INTERNET:
5863 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005864 // High priority because it is only displayed for explicitly selected networks.
5865 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005866 break;
lucasline117e2e2019-10-22 18:27:33 +08005867 case PRIVATE_DNS_BROKEN:
5868 action = Settings.ACTION_WIRELESS_SETTINGS;
5869 // High priority because we should let user know why there is no internet.
5870 highPriority = true;
5871 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005872 case LOST_INTERNET:
5873 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005874 // High priority because it could help the user avoid unexpected data usage.
5875 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005876 break;
lucaslin2240ef62019-03-12 13:08:03 +08005877 case PARTIAL_CONNECTIVITY:
5878 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005879 // Don't bother the user with a high-priority notification if the network was not
5880 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005881 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005882 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005883 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005884 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005885 return;
5886 }
5887
5888 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005889 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005890 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005891 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005892 // Some OEMs have their own Settings package. Thus, need to get the current using
5893 // Settings package name instead of just use default name "com.android.settings".
5894 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5895 intent.setClassName(settingsPkgName,
5896 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005897 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005898
paulhu2af50222020-10-11 22:52:27 +08005899 PendingIntent pendingIntent = PendingIntent.getActivity(
5900 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005901 0 /* requestCode */,
5902 intent,
paulhu2af50222020-10-11 22:52:27 +08005903 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005904
Serik Beketayevec8ad212020-12-07 22:43:07 -08005905 mNotifier.showNotification(
5906 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005907 }
5908
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005909 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5910 // Don't prompt if the network is validated, and don't prompt on captive portals
5911 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005912 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005913 return false;
5914 }
5915
5916 // If a network has partial connectivity, always prompt unless the user has already accepted
5917 // partial connectivity and selected don't ask again. This ensures that if the device
5918 // automatically connects to a network that has partial Internet access, the user will
5919 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005920 // because we have prompted them.
5921 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005922 return true;
5923 }
5924
5925 // If a network has no Internet access, only prompt if the network was explicitly selected
5926 // and if the user has not already told us to use the network regardless of whether it
5927 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005928 if (nai.networkAgentConfig.explicitlySelected
5929 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005930 return true;
5931 }
5932
5933 return false;
5934 }
5935
Chalard Jean5fb43c72022-09-08 19:03:14 +09005936 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5937 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005938
Chalard Jean5fb43c72022-09-08 19:03:14 +09005939 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5940 if (null == nai) return;
5941
5942 if (nai.setEvaluated()) {
5943 // If setEvaluated() returned true, the network never had any form of connectivity.
5944 // This may have an impact on request matching if bad WiFi avoidance is off and the
5945 // network was found not to have Internet access.
5946 nai.updateScoreForNetworkAgentUpdate();
5947 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005948
5949 // Also, if this is WiFi and it should be preferred actively, now is the time to
5950 // prompt the user that they walked past and connected to a bad WiFi.
5951 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5952 && !avoidBadWifi()
5953 && activelyPreferBadWifi()) {
5954 // The notification will be removed if the network validates or disconnects.
5955 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5956 return;
5957 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005958 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005959
Chalard Jean5fb43c72022-09-08 19:03:14 +09005960 if (!shouldPromptUnvalidated(nai)) return;
5961
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005962 // Stop automatically reconnecting to this network in the future. Automatically connecting
5963 // to a network that provides no or limited connectivity is not useful, because the user
5964 // cannot use that network except through the notification shown by this method, and the
5965 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005966 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005967
Chalard Jean254bd162022-08-25 13:04:51 +09005968 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005969 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005970 } else {
5971 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5972 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005973 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005974
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005975 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5976 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005977 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005978
lucaslin2240ef62019-03-12 13:08:03 +08005979 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5980 return;
5981 }
5982
5983 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005984 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005985 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005986 }
5987
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005988 @Override
5989 public int getMultipathPreference(Network network) {
5990 enforceAccessPermission();
5991
5992 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005993 if (nai != null && nai.networkCapabilities
5994 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005995 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5996 }
5997
Aaron Huang9a57acf2020-12-08 10:03:29 +08005998 final NetworkPolicyManager netPolicyManager =
5999 mContext.getSystemService(NetworkPolicyManager.class);
6000
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006001 final long token = Binder.clearCallingIdentity();
6002 final int networkPreference;
6003 try {
6004 networkPreference = netPolicyManager.getMultipathPreference(network);
6005 } finally {
6006 Binder.restoreCallingIdentity(token);
6007 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006008 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006009 return networkPreference;
6010 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006011 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6012 }
6013
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006014 @Override
6015 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006016 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006017 }
6018
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006019 private class InternalHandler extends Handler {
6020 public InternalHandler(Looper looper) {
6021 super(looper);
6022 }
6023
6024 @Override
6025 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006026 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006027 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006028 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006029 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006030 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006031 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006032 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006033 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006034 break;
6035 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006036 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006037 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006038 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006039 break;
6040 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006041 case EVENT_REGISTER_NETWORK_PROVIDER: {
6042 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006043 break;
6044 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006045 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6046 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006047 break;
6048 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006049 case EVENT_REGISTER_NETWORK_OFFER: {
6050 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6051 break;
6052 }
6053 case EVENT_UNREGISTER_NETWORK_OFFER: {
6054 final NetworkOfferInfo offer =
6055 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6056 if (null != offer) {
6057 handleUnregisterNetworkOffer(offer);
6058 }
6059 break;
6060 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006061 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006062 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6063 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6064 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006065 break;
6066 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006067 case EVENT_REGISTER_NETWORK_REQUEST:
6068 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006069 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006070 break;
6071 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006072 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6073 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006074 handleRegisterNetworkRequestWithIntent(msg);
6075 break;
6076 }
Erik Kline155a59a2015-11-25 12:49:38 +09006077 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6078 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6079 handleTimedOutNetworkRequest(nri);
6080 break;
6081 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006082 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6083 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6084 break;
6085 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006086 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006087 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6088 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006089 break;
6090 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006091 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006092 Network network = (Network) msg.obj;
6093 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006094 break;
6095 }
lucaslin2240ef62019-03-12 13:08:03 +08006096 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6097 Network network = (Network) msg.obj;
6098 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6099 toBool(msg.arg2));
6100 break;
6101 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006102 case EVENT_SET_AVOID_UNVALIDATED: {
6103 handleSetAvoidUnvalidated((Network) msg.obj);
6104 break;
6105 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006106 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6107 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006108 break;
6109 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006110 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6111 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006112 break;
6113 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006114 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6115 // handler thread.
6116 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006117 mKeepaliveTracker.handleStartKeepalive(msg);
6118 break;
6119 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006120 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006121 final AutomaticOnOffKeepalive ki =
6122 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6123 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006124
chiachangwang676c84e2023-02-14 09:22:05 +00006125 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006126 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006127 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006128 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006129 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6130 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006131 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6132 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006133 }
6134 }
6135
6136 // If the network no longer exists, then the keepalive should have been
6137 // cleaned up already. There is no point trying to resume keepalives.
6138 if (!networkFound) return;
6139
chiachangwang676c84e2023-02-14 09:22:05 +00006140 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006141 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00006142 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006143 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006144 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006145 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006146 }
6147 break;
6148 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006149 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006150 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006151 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6152 (IBinder) msg.obj);
6153 if (ki == null) {
6154 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006155 return;
6156 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006157 final int reason = msg.arg2;
6158 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006159 break;
6160 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006161 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6162 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6163 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006164 break;
6165 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006166 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6167 handlePrivateDnsSettingsChanged();
6168 break;
dalyk1720e542018-03-05 12:42:22 -05006169 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6170 handlePrivateDnsValidationUpdate(
6171 (PrivateDnsValidationUpdate) msg.obj);
6172 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006173 case EVENT_UID_BLOCKED_REASON_CHANGED:
6174 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006175 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006176 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6177 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6178 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006179 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006180 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6181 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006182 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006183 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006184 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006185 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006186 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6187 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006188 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006189 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006190 }
lucaslin1193a5d2021-01-21 02:04:15 +08006191 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006192 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006193 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006194 break;
paulhu51f77dc2021-06-07 02:34:20 +00006195 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6196 handleMobileDataPreferredUidsChanged();
6197 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006198 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6199 final long timeMs = ((Long) msg.obj).longValue();
6200 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6201 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006202 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6203 handleIngressRateLimitChanged();
6204 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006205 case EVENT_USER_DOES_NOT_WANT:
6206 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6207 if (nai == null) break;
6208 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006209 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006210 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006211 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6212 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6213 break;
chiachangwange0192a72023-02-06 13:25:01 +00006214 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6215 final long time = ((Long) msg.obj).longValue();
6216 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6217 break;
6218 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006219 case EVENT_UID_FROZEN_STATE_CHANGED:
6220 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6221 handleFrozenUids(args.mUids, args.mFrozenStates);
6222 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006223 }
6224 }
6225 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006226
Lorenzo Colittid6459092016-07-04 12:55:44 +09006227 @Override
markchien5776f962019-12-16 20:15:20 +08006228 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006229 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006230 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006231 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6232 Context.TETHERING_SERVICE);
6233 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006234 }
6235
Lorenzo Colittid6459092016-07-04 12:55:44 +09006236 @Override
markchien5776f962019-12-16 20:15:20 +08006237 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006238 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006239 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006240 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6241 Context.TETHERING_SERVICE);
6242 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006243 }
6244
Lorenzo Colittid6459092016-07-04 12:55:44 +09006245 @Override
markchien5776f962019-12-16 20:15:20 +08006246 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006247 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006248 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006249 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6250 Context.TETHERING_SERVICE);
6251 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006252 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006253
markchien5776f962019-12-16 20:15:20 +08006254
Lorenzo Colittid6459092016-07-04 12:55:44 +09006255 @Override
markchien5776f962019-12-16 20:15:20 +08006256 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006257 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006258 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006259 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6260 Context.TETHERING_SERVICE);
6261
6262 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006263 }
6264
Lorenzo Colittid6459092016-07-04 12:55:44 +09006265 @Override
markchien5776f962019-12-16 20:15:20 +08006266 @Deprecated
6267 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006268 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006269 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6270 Context.TETHERING_SERVICE);
6271
6272 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006273 }
6274
Udam Saini8f7d6a72017-06-07 12:06:28 -07006275 @Override
markchien5776f962019-12-16 20:15:20 +08006276 @Deprecated
6277 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006278 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006279 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6280 Context.TETHERING_SERVICE);
6281 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006282 }
6283
Robert Greenwalte0b00512014-07-02 09:59:16 -07006284 // Called when we lose the default network and have no replacement yet.
6285 // This will automatically be cleared after X seconds or a new default network
6286 // becomes CONNECTED, whichever happens first. The timer is started by the
6287 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006288 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006289 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006290 if (mNetTransitionWakeLock.isHeld()) {
6291 return;
6292 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006293 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006294 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6295 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006296 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006297 mWakelockLogs.log("ACQUIRE for " + forWhom);
6298 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006299 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006300 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006301 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006302 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006303
Hugo Benichi471b62a2017-03-30 23:18:10 +09006304 // Called when we gain a new default network to release the network transition wakelock in a
6305 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6306 // message is cancelled.
6307 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006308 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006309 if (!mNetTransitionWakeLock.isHeld()) {
6310 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006311 }
6312 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006313 // Cancel self timeout on wakelock hold.
6314 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6315 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6316 mHandler.sendMessageDelayed(msg, 1000);
6317 }
6318
6319 // Called when either message of ensureNetworkTransitionWakelock or
6320 // scheduleReleaseNetworkTransitionWakelock is processed.
6321 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6322 String event = eventName(eventId);
6323 synchronized (this) {
6324 if (!mNetTransitionWakeLock.isHeld()) {
6325 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006326 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006327 return;
6328 }
6329 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006330 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6331 mTotalWakelockDurationMs += lockDuration;
6332 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6333 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006334 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006335 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006336 }
6337
Robert Greenwalt986c7412010-09-08 15:24:47 -07006338 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006339 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006340 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006341 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006342 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006343 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006344 }
6345
Lorenzo Colittid6459092016-07-04 12:55:44 +09006346 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006347 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006348 enforceAccessPermission();
6349 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006350 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006351 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006352
6353 final NetworkAgentInfo nai;
6354 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006355 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006356 } else {
6357 nai = getNetworkAgentInfoForNetwork(network);
6358 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006359
6360 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006361 mHandler.obtainMessage(
6362 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006363 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006364
Hugo Benichid6b510a2017-04-06 17:22:18 +09006365 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006366 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006367 if (nai == null
6368 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006369 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006370 return;
6371 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006372 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006373 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006374 mConnectivityDiagnosticsHandler.sendMessage(
6375 mConnectivityDiagnosticsHandler.obtainMessage(
6376 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6377 new ReportedNetworkConnectivityInfo(
6378 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006379 return;
6380 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006381 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006382 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006383 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006384 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006385 // Validating a network that has not yet connected could result in a call to
6386 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006387 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006388 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006389 }
paulhu7aeba372020-12-30 00:42:19 +08006390 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6391 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006392 return;
6393 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006394
6395 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6396 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6397 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6398 // completed.
6399 mConnectivityDiagnosticsHandler.sendMessage(
6400 mConnectivityDiagnosticsHandler.obtainMessage(
6401 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6402 new ReportedNetworkConnectivityInfo(
6403 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006404 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006405 }
6406
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006407 // TODO: call into netd.
6408 private boolean queryUserAccess(int uid, Network network) {
6409 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6410 if (nai == null) return false;
6411
6412 // Any UID can use its default network.
6413 if (nai == getDefaultNetworkForUid(uid)) return true;
6414
6415 // Privileged apps can use any network.
6416 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6417 return true;
6418 }
6419
6420 // An unprivileged UID can use a VPN iff the VPN applies to it.
6421 if (nai.isVPN()) {
6422 return nai.networkCapabilities.appliesToUid(uid);
6423 }
6424
6425 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6426 // sockets, i.e., if it is the owner.
6427 final NetworkAgentInfo vpn = getVpnForUid(uid);
6428 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6429 && uid != vpn.networkCapabilities.getOwnerUid()) {
6430 return false;
6431 }
6432
6433 // The UID's permission must be at least sufficient for the network. Since the restricted
6434 // permission was already checked above, that just leaves background networks.
6435 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6436 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6437 }
6438
6439 // Unrestricted network. Anyone gets to use it.
6440 return true;
6441 }
6442
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006443 /**
6444 * Returns information about the proxy a certain network is using. If given a null network, it
6445 * it will return the proxy for the bound network for the caller app or the default proxy if
6446 * none.
6447 *
6448 * @param network the network we want to get the proxy information for.
6449 * @return Proxy information if a network has a proxy configured, or otherwise null.
6450 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006451 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006452 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006453 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006454 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006455 if (network == null) {
6456 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006457 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006458 true);
6459 if (activeNetwork == null) {
6460 return null;
6461 }
6462 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006463 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006464 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6465 // caller may not have.
6466 return getLinkPropertiesProxyInfo(network);
6467 }
6468 // No proxy info available if the calling UID does not have network access.
6469 return null;
6470 }
6471
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006472
6473 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006474 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6475 if (nai == null) return null;
6476 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006477 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6478 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006479 }
6480 }
6481
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006482 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006483 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006484 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006485 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006486 }
6487
Chalard Jean777e2e52018-06-07 18:02:37 +09006488 @Override
6489 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006490 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006491 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006492 }
6493
Aaron Huang9fe47be2021-06-08 13:11:45 +08006494 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006495 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006496 final NetworkAgentInfo nai = getDefaultNetwork();
6497 // TODO : this method should check that net == nai.network, unfortunately at this point
6498 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6499 // is only ever installed on the default network so in practice this is okay.
6500 if (null == nai) return;
6501 // PAC proxies only work on the default network. Therefore, only the default network
6502 // should have its link properties fixed up for PAC proxies.
6503 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6504 if (nai.everConnected()) {
6505 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6506 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006507 }
6508
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006509 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6510 // when any network changes proxy.
6511 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6512 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006513 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6514 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006515 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6516
Chalard Jean7d97afc2018-06-07 17:41:29 +09006517 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006518 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006519 }
6520 }
6521
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006522 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006523 final private HashMap<Uri, Integer> mUriEventMap;
6524 final private Context mContext;
6525 final private Handler mHandler;
6526
6527 SettingsObserver(Context context, Handler handler) {
6528 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006529 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006530 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006531 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006532 }
6533
Erik Kline05f2b402015-04-30 12:58:40 +09006534 void observe(Uri uri, int what) {
6535 mUriEventMap.put(uri, what);
6536 final ContentResolver resolver = mContext.getContentResolver();
6537 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006538 }
6539
6540 @Override
6541 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006542 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006543 }
6544
6545 @Override
6546 public void onChange(boolean selfChange, Uri uri) {
6547 final Integer what = mUriEventMap.get(uri);
6548 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006549 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006550 } else {
6551 loge("No matching event to send for URI=" + uri);
6552 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006553 }
6554 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006555
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006556 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006557 Log.d(TAG, s);
6558 }
6559
6560 private static void logw(String s) {
6561 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006562 }
6563
Daniel Brightf9e945b2020-06-15 16:10:01 -07006564 private static void logwtf(String s) {
6565 Log.wtf(TAG, s);
6566 }
6567
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006568 private static void logwtf(String s, Throwable t) {
6569 Log.wtf(TAG, s, t);
6570 }
6571
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006572 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006573 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006574 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006575
Hugo Benichi39621362017-02-11 17:04:43 +09006576 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006577 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006578 }
6579
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006580 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006581 * Return the information of all ongoing VPNs.
6582 *
6583 * <p>This method is used to update NetworkStatsService.
6584 *
6585 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006586 */
junyulai2050bed2021-01-23 09:46:34 +08006587 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006588 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006589 if (mLockdownEnabled) {
6590 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006591 }
junyulai2050bed2021-01-23 09:46:34 +08006592 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006593 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006594 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006595 if (info != null) {
6596 infoList.add(info);
6597 }
6598 }
junyulai2050bed2021-01-23 09:46:34 +08006599 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006600 }
6601
6602 /**
6603 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006604 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006605 */
junyulai2050bed2021-01-23 09:46:34 +08006606 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006607 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006608 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6609 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006610 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6611 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6612 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006613 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6614 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006615 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006616 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006617 }
6618 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006619
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006620 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006621
6622 List<String> interfaces = new ArrayList<>();
6623 for (Network network : underlyingNetworks) {
6624 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6625 if (underlyingNai == null) continue;
6626 LinkProperties lp = underlyingNai.linkProperties;
6627 for (String iface : lp.getAllInterfaceNames()) {
6628 if (!TextUtils.isEmpty(iface)) {
6629 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006630 }
6631 }
Benedict Wong34857f82019-06-12 17:46:15 +00006632 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006633
6634 if (interfaces.isEmpty()) return null;
6635
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006636 // Must be non-null or NetworkStatsService will crash.
6637 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6638 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006639 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006640 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006641
junyulai2050bed2021-01-23 09:46:34 +08006642 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6643 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006644 }
6645
James Mattisd31bdfa2020-12-23 16:37:26 -08006646 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006647 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6648 Network[] underlyingNetworks) {
6649 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006650 if (underlyingNetworks == null && defaultNetwork != null) {
6651 // null underlying networks means to track the default.
6652 underlyingNetworks = new Network[] { defaultNetwork };
6653 }
6654 return underlyingNetworks;
6655 }
6656
6657 // Returns true iff |network| is an underlying network of |nai|.
6658 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6659 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6660 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006661 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006662 final Network[] underlying = underlyingNetworksOrDefault(
6663 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006664 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006665 }
6666
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006667 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006668 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006669 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006670 * When underlying networks change, such networks may have to update capabilities to reflect
6671 * things like the metered bit, their transports, and so on. The capabilities are calculated
6672 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006673 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006674 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006675 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006676 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006677 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006678 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006679 }
6680 }
6681 }
6682
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006683 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6684 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6685 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6686 // a VPN is not up.
6687 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6688 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6689 for (UidRange range : blockedUidRanges) {
6690 if (range.contains(uid)) return true;
6691 }
6692 return false;
6693 }
6694
6695 @Override
6696 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006697 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006698 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6699 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6700 }
6701
6702 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6703 if (DBG) {
6704 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6705 + Arrays.toString(ranges));
6706 }
6707 // Cannot use a Set since the list of UID ranges might contain duplicates.
6708 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6709 for (int i = 0; i < ranges.length; i++) {
6710 if (requireVpn) {
6711 newVpnBlockedUidRanges.add(ranges[i]);
6712 } else {
6713 newVpnBlockedUidRanges.remove(ranges[i]);
6714 }
6715 }
6716
6717 try {
6718 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6719 } catch (RemoteException | ServiceSpecificException e) {
6720 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6721 + Arrays.toString(ranges) + "): netd command failed: " + e);
6722 }
6723
Chalard Jeandf29a852023-05-29 17:02:43 +09006724 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006725 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6726 }
6727
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006728 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6729 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006730 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6731 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006732 }
6733
6734 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6735 }
6736
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006737 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006738 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006739 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006740 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006741 }
6742
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006743 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6744 return mLockdownEnabled
6745 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6746 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006747 }
6748
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006749 private NetworkAgentInfo getLegacyLockdownNai() {
6750 if (!mLockdownEnabled) {
6751 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006752 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006753 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006754 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6755 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006756
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006757 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006758 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6759 // a local variable. There is no need to make a copy because its contents cannot change.
6760 final Network[] underlying = nai.declaredUnderlyingNetworks;
6761 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006762 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006763 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006764
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006765 // The legacy lockdown VPN always uses the default network.
6766 // If the VPN's underlying network is no longer the current default network, it means that
6767 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006768 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6769 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006770 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006771 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006772 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006773 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006774
6775 return nai;
6776 };
6777
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006778 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6779 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6780 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006781 private DetailedState getLegacyLockdownState(DetailedState origState) {
6782 if (origState != DetailedState.CONNECTED) {
6783 return origState;
6784 }
6785 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6786 ? DetailedState.CONNECTING
6787 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006788 }
6789
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006790 private void filterForLegacyLockdown(NetworkInfo ni) {
6791 if (!mLockdownEnabled || !ni.isConnected()) return;
6792 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6793 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6794 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6795 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6796 // network, this time with a state of CONNECTED.
6797 //
6798 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6799 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6800 // is not too far off the truth, since an always-on VPN, when not connected, is always
6801 // trying to reconnect.
6802 if (getLegacyLockdownNai() == null) {
6803 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6804 }
6805 }
6806
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006807 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006808 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006809 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006810 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006811 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6812 return;
6813 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006814 final long ident = Binder.clearCallingIdentity();
6815 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006816 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006817 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006818 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006819 } finally {
6820 Binder.restoreCallingIdentity(ident);
6821 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006822 }
Wink Savillecb117d32013-08-29 14:57:08 -07006823
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006824 @Override
6825 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006826 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006827 final long ident = Binder.clearCallingIdentity();
6828 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006829 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006830 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006831 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6832 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006833 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006834 } finally {
6835 Binder.restoreCallingIdentity(ident);
6836 }
6837 }
6838
James Mattis02220e22021-03-13 19:27:21 -08006839 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006840 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6841 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6842 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006843 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006844 }
6845
James Mattis02220e22021-03-13 19:27:21 -08006846 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006847 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006848 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006849 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6850 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006851 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006852 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6853 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6854 }
junyulaid91e7052020-08-28 13:44:33 +08006855 }
6856
James Mattis02220e22021-03-13 19:27:21 -08006857 private void onPackageChanged(@NonNull final String packageName) {
6858 // This is necessary in case a package is added or removed, but also when it's replaced to
6859 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6860 // as one in the preferences, then it should follow the same routing as that other package,
6861 // which means updating the rules is never to be needed in this case (whether it joins or
6862 // leaves a UID with a preference).
6863 if (isMappedInOemNetworkPreference(packageName)) {
6864 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6865 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006866
6867 // Invalidates cache entry when the package is updated.
6868 synchronized (mSelfCertifiedCapabilityCache) {
6869 mSelfCertifiedCapabilityCache.remove(packageName);
6870 }
James Mattis02220e22021-03-13 19:27:21 -08006871 }
6872
6873 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006874 @Override
6875 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006876 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006877 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006878 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006879
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006880 // User should be filled for below intents, check the existence.
6881 if (user == null) {
6882 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6883 return;
6884 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006885
Lorenzo Colitticd675292021-02-04 17:32:07 +09006886 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006887 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006888 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006889 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006890 } else {
junyulaid91e7052020-08-28 13:44:33 +08006891 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006892 }
6893 }
6894 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006895
James Mattis02220e22021-03-13 19:27:21 -08006896 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6897 @Override
6898 public void onReceive(Context context, Intent intent) {
6899 ensureRunningOnConnectivityServiceThread();
6900 switch (intent.getAction()) {
6901 case Intent.ACTION_PACKAGE_ADDED:
6902 case Intent.ACTION_PACKAGE_REMOVED:
6903 case Intent.ACTION_PACKAGE_REPLACED:
6904 onPackageChanged(intent.getData().getSchemeSpecificPart());
6905 break;
6906 default:
6907 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6908 }
6909 }
6910 };
6911
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006912 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006913 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006914
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006915 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006916 public final String name;
6917 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006918 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006919 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006920
lifraf3a3492021-03-10 13:58:14 +08006921 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6922 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006923 this.name = name;
6924 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006925 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006926 mDeathRecipient = deathRecipient;
6927
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006928 if (mDeathRecipient == null) {
6929 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006930 }
6931 }
6932
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006933 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006934 try {
6935 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6936 } catch (RemoteException e) {
6937 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006938 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006939 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006940 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006941
James Mattis4fce5d12020-11-12 15:53:42 -08006942 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6943 for (int i = 0; i < requests.size(); i++) {
6944 ensureNetworkRequestHasType(requests.get(i));
6945 }
6946 }
6947
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006948 private void ensureNetworkRequestHasType(NetworkRequest request) {
6949 if (request.type == NetworkRequest.Type.NONE) {
6950 throw new IllegalArgumentException(
6951 "All NetworkRequests in ConnectivityService must have a type");
6952 }
6953 }
6954
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006955 /**
6956 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006957 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006958 */
James Mattis258ea3c2020-11-15 15:04:40 -08006959 @VisibleForTesting
6960 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006961 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6962 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006963 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006964
James Mattisa076c532020-12-02 14:12:41 -08006965 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6966 void setSatisfier(
6967 @Nullable final NetworkAgentInfo satisfier,
6968 @Nullable final NetworkRequest activeRequest) {
6969 mSatisfier = satisfier;
6970 mActiveRequest = activeRequest;
6971 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006972
James Mattisd31bdfa2020-12-23 16:37:26 -08006973 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006974 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006975 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006976 private NetworkAgentInfo mSatisfier;
6977 NetworkAgentInfo getSatisfier() {
6978 return mSatisfier;
6979 }
6980
6981 // The request in mRequests assigned to a network agent. This is null if none of the
6982 // requests in mRequests can be satisfied. This member has the constraint of only being
6983 // accessible on the handler thread.
6984 @Nullable
6985 private NetworkRequest mActiveRequest;
6986 NetworkRequest getActiveRequest() {
6987 return mActiveRequest;
6988 }
6989
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006990 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006991 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006992 @Nullable
6993 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006994
6995 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006996 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006997 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006998 final int mPid;
6999 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007000 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007001 @Nullable
7002 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007003
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007004 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007005 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007006
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007007 // Effective UID of this request. This is different from mUid when a privileged process
7008 // files a request on behalf of another UID. This UID is used to determine blocked status,
7009 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7010 // maximum limit of registered callbacks per UID.
7011 final int mAsUid;
7012
paulhu48291862021-07-14 14:53:57 +08007013 // Preference order of this request.
7014 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007015
James Mattis3ce3d3c2021-02-09 18:18:28 -08007016 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7017 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7018 // maintained for keying off of. This is only a concern when the original nri
7019 // mNetworkRequests changes which happens currently for apps that register callbacks to
7020 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7021 // that match the per-app default nri that currently tracks the calling app's uid so that
7022 // callbacks are fired at the appropriate time. When the callbacks fire,
7023 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7024 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7025 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7026 @NonNull
7027 private final NetworkRequest mNetworkRequestForCallback;
7028 NetworkRequest getNetworkRequestForCallback() {
7029 return mNetworkRequestForCallback;
7030 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007031
James Mattisd31bdfa2020-12-23 16:37:26 -08007032 /**
7033 * Get the list of UIDs this nri applies to.
7034 */
7035 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007036 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007037 // networkCapabilities.getUids() returns a defensive copy.
7038 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007039 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7040 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007041 }
7042
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007043 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7044 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007045 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007046 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007047 }
7048
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007049 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007050 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007051 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007052 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007053 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007054 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007055 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007056 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007057 mBinder = null;
7058 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007059 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007060 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007061 mPerUidCounter = getRequestCounter(this);
7062 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007063 /**
7064 * Location sensitive data not included in pending intent. Only included in
7065 * {@link NetworkCallback}.
7066 */
7067 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007068 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007069 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007070 }
7071
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007072 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007073 @Nullable final IBinder binder,
7074 @NetworkCallback.Flag int callbackFlags,
7075 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007076 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7077 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007078 }
7079
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007080 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007081 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007082 @Nullable final IBinder binder,
7083 @NetworkCallback.Flag int callbackFlags,
7084 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007085 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007086 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007087 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007088 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007089 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007090 mBinder = binder;
7091 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007092 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007093 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007094 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007095 mPerUidCounter = getRequestCounter(this);
7096 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007097 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007098 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007099 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007100 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007101 }
7102
James Mattis3ce3d3c2021-02-09 18:18:28 -08007103 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7104 @NonNull final List<NetworkRequest> r) {
7105 super();
7106 ensureAllNetworkRequestsHaveType(r);
7107 mRequests = initializeRequests(r);
7108 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007109 final NetworkAgentInfo satisfier = nri.getSatisfier();
7110 if (null != satisfier) {
7111 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7112 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007113 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007114 // As this code creates a new NRI with a new set of requests, figure out which of
7115 // the list of requests should be the active request. It is always the first
7116 // request of the list that can be satisfied by the satisfier since the order of
7117 // requests is a priority order.
7118 // Note even in the presence of a satisfier there may not be an active request,
7119 // when the satisfier is the no-service network.
7120 NetworkRequest activeRequest = null;
7121 for (final NetworkRequest candidate : r) {
7122 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7123 activeRequest = candidate;
7124 break;
7125 }
7126 }
7127 setSatisfier(satisfier, activeRequest);
7128 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007129 mMessenger = nri.mMessenger;
7130 mBinder = nri.mBinder;
7131 mPid = nri.mPid;
7132 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007133 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007134 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007135 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007136 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007137 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007138 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007139 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007140 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007141 }
7142
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007143 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007144 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007145 }
7146
paulhue9913722021-05-26 15:19:20 +08007147 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007148 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007149 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007150 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007151 }
7152
James Mattis2516da32021-01-31 17:06:19 -08007153 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7154 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7155 // false.
7156 boolean isBeingSatisfied() {
7157 return (null != mSatisfier && null != mActiveRequest);
7158 }
7159
James Mattis3d229892020-11-16 16:46:28 -08007160 boolean isMultilayerRequest() {
7161 return mRequests.size() > 1;
7162 }
7163
James Mattis45d81842021-01-10 14:24:24 -08007164 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7165 // Creating a defensive copy to prevent the sender from modifying the list being
7166 // reflected in the return value of this method.
7167 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007168 return Collections.unmodifiableList(tempRequests);
7169 }
7170
James Mattisb1392002021-03-31 13:57:52 -07007171 void linkDeathRecipient() {
7172 if (null != mBinder) {
7173 try {
7174 mBinder.linkToDeath(this, 0);
7175 } catch (RemoteException e) {
7176 binderDied();
7177 }
7178 }
7179 }
7180
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007181 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007182 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007183 try {
7184 mBinder.unlinkToDeath(this, 0);
7185 } catch (NoSuchElementException e) {
7186 // Temporary workaround for b/194394697 pending analysis of additional logs
7187 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7188 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007189 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007190 }
7191
paulhu48291862021-07-14 14:53:57 +08007192 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7193 // Compare two preference orders.
7194 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007195 }
7196
paulhu48291862021-07-14 14:53:57 +08007197 int getPreferenceOrderForNetd() {
7198 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7199 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7200 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007201 }
paulhu48291862021-07-14 14:53:57 +08007202 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007203 }
7204
James Mattis4fce5d12020-11-12 15:53:42 -08007205 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007206 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007207 // As an immutable collection, mRequests cannot change by the time the
7208 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7209 // is acceptable. Use handleReleaseNetworkRequest and not directly
7210 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7211 // the app already unregistered the request.
7212 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7213 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007214 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007215
James Mattis4fce5d12020-11-12 15:53:42 -08007216 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007217 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007218 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7219 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007220 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007221 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007222 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007223 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007224 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007225 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007226 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007227 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007228 }
7229
Junyu Lai00d92df2022-07-05 11:01:52 +08007230 // Keep backward compatibility since the ServiceSpecificException is used by
7231 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7232 public static class RequestInfoPerUidCounter extends PerUidCounter {
7233 RequestInfoPerUidCounter(int maxCountPerUid) {
7234 super(maxCountPerUid);
7235 }
7236
7237 @Override
7238 public synchronized void incrementCountOrThrow(int uid) {
7239 try {
7240 super.incrementCountOrThrow(uid);
7241 } catch (IllegalStateException e) {
7242 throw new ServiceSpecificException(
7243 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7244 "Uid " + uid + " exceeded its allotted requests limit");
7245 }
7246 }
7247
7248 @Override
7249 public synchronized void decrementCountOrThrow(int uid) {
7250 throw new UnsupportedOperationException("Use decrementCount instead.");
7251 }
7252
7253 public synchronized void decrementCount(int uid) {
7254 try {
7255 super.decrementCountOrThrow(uid);
7256 } catch (IllegalStateException e) {
7257 logwtf("Exception when decrement per uid request count: ", e);
7258 }
7259 }
7260 }
7261
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007262 // This checks that the passed capabilities either do not request a
7263 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007264 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007265 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007266 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007267 throw new SecurityException("Insufficient permissions to request a specific SSID");
7268 }
paulhu1a407652019-03-22 16:35:06 +08007269
7270 if (nc.hasSignalStrength()
7271 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7272 throw new SecurityException(
7273 "Insufficient permissions to request a specific signal strength");
7274 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007275 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007276
junyulai2217bec2021-04-14 23:33:31 +08007277 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007278 enforceNetworkFactoryPermission();
7279 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007280 }
7281
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007282 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007283 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007284 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007285 // mNetworkRequests may contain the same value multiple times in case of
7286 // multilayer requests. It won't matter in this case because the thresholds
7287 // will then be the same and be deduplicated as they enter the `thresholds` set.
7288 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007289 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7290 for (final NetworkRequest req : nri.mRequests) {
7291 if (req.networkCapabilities.hasSignalStrength()
7292 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7293 thresholds.add(req.networkCapabilities.getSignalStrength());
7294 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007295 }
7296 }
7297 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007298 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007299 }
7300
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007301 private void updateSignalStrengthThresholds(
7302 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007303 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007304
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007305 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007306 String detail;
7307 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7308 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7309 } else {
7310 detail = reason;
7311 }
7312 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007313 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007314 }
7315
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007316 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007317 }
7318
Chalard Jeandd421992021-12-16 23:16:02 +09007319 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007320 if (nc == null) {
7321 return;
7322 }
7323 NetworkSpecifier ns = nc.getNetworkSpecifier();
7324 if (ns == null) {
7325 return;
7326 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007327 if (ns instanceof MatchAllNetworkSpecifier) {
7328 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7329 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007330 }
7331
Chalard Jeandd421992021-12-16 23:16:02 +09007332 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007333 ensureValidNetworkSpecifier(nc);
7334 if (nc.isPrivateDnsBroken()) {
7335 throw new IllegalArgumentException("Can't request broken private DNS");
7336 }
Chalard Jeande665262022-02-25 16:12:12 +09007337 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007338 throw new IllegalArgumentException("Can't request access UIDs");
7339 }
lucasline117e2e2019-10-22 18:27:33 +08007340 }
7341
Chalard Jeandd421992021-12-16 23:16:02 +09007342 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7343 ensureListenableCapabilities(nc);
7344 final String badCapability = nc.describeFirstNonRequestableCapability();
7345 if (badCapability != null) {
7346 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7347 }
7348 }
7349
Chiachang Wang3bc52762021-11-25 14:17:57 +08007350 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7351 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007352 private boolean isTargetSdkAtleast(int version, int callingUid,
7353 @NonNull String callingPackageName) {
7354 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007355 final PackageManager pm =
7356 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007357 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007358 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007359 if (callingVersion < version) return false;
7360 } catch (PackageManager.NameNotFoundException e) { }
7361 return true;
7362 }
7363
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007364 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007365 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007366 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007367 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007368 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007369 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007370 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7371 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007372 throw new SecurityException("Insufficient permissions to specify legacy type");
7373 }
markchienfac84a22020-03-18 21:16:15 +08007374 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007375 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007376 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007377 // Privileged callers can track the default network of another UID by passing in a UID.
7378 if (asUid != Process.INVALID_UID) {
7379 enforceSettingsPermission();
7380 } else {
7381 asUid = callingUid;
7382 }
junyulaiad010792021-01-11 16:53:38 +08007383 final NetworkRequest.Type reqType;
7384 try {
7385 reqType = NetworkRequest.Type.values()[reqTypeInt];
7386 } catch (ArrayIndexOutOfBoundsException e) {
7387 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7388 }
7389 switch (reqType) {
7390 case TRACK_DEFAULT:
7391 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007392 // is unused and will be replaced by ones appropriate for the UID (usually, the
7393 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007394 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007395 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007396 enforceAccessPermission();
7397 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007398 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007399 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007400 networkCapabilities = new NetworkCapabilities(defaultNc);
7401 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007402 case BACKGROUND_REQUEST:
7403 enforceNetworkStackOrSettingsPermission();
7404 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007405 case REQUEST:
7406 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7407 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007408 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007409 // TODO: this is incorrect. We mark the request as metered or not depending on
7410 // the state of the app when the request is filed, but we never change the
7411 // request if the app changes network state. http://b/29964605
7412 enforceMeteredApnPolicy(networkCapabilities);
7413 break;
junyulai1b1c8742021-03-12 20:05:08 +08007414 case LISTEN_FOR_BEST:
7415 enforceAccessPermission();
7416 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7417 break;
junyulaiad010792021-01-11 16:53:38 +08007418 default:
7419 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007420 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007421 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007422 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007423 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007424
junyulai1b1c8742021-03-12 20:05:08 +08007425 // Enforce FOREGROUND if the caller does not have permission to use background network.
7426 if (reqType == LISTEN_FOR_BEST) {
7427 restrictBackgroundRequestForCaller(networkCapabilities);
7428 }
7429
7430 // Set the UID range for this request to the single UID of the requester, unless the
7431 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007432 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7433 // are no visible methods to set the UIDs, an app could use reflection to try and get
7434 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007435 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007436 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7437 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007438
Etan Cohen85000162017-02-05 10:42:27 -08007439 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007440 throw new IllegalArgumentException("Bad timeout specified");
7441 }
Etan Cohen9786d922015-11-18 10:56:15 -08007442
James Mattis3ce3d3c2021-02-09 18:18:28 -08007443 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007444 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007445 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007446 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007447 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007448 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007449
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007450 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7451 // copied from the default request above. (This is necessary to ensure, for example, that
7452 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7453 // changes don't alter request matching.
7454 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7455 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007456 throw new IllegalStateException(
7457 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007458 + networkCapabilities + " vs. " + defaultNc);
7459 }
7460
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007461 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007462 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007463 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007464 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007465 }
7466 return networkRequest;
7467 }
7468
James Mattis3ce3d3c2021-02-09 18:18:28 -08007469 /**
7470 * Return the nri to be used when registering a network request. Specifically, this is used with
7471 * requests registered to track the default request. If there is currently a per-app default
7472 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7473 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007474 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7475 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007476 * @param nr the network request for the nri.
7477 * @param msgr the messenger for the nri.
7478 * @param binder the binder for the nri.
7479 * @param callingAttributionTag the calling attribution tag for the nri.
7480 * @return the nri to register.
7481 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007482 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007483 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007484 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007485 @Nullable String callingAttributionTag) {
7486 final List<NetworkRequest> requests;
7487 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7488 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007489 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007490 } else {
7491 requests = Collections.singletonList(nr);
7492 }
Roshan Pius951c0032020-12-22 15:10:42 -08007493 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007494 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007495 }
7496
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007497 private boolean shouldCheckCapabilitiesDeclaration(
7498 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7499 @NonNull final String callingPackageName) {
7500 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7501 // Only run the check if the change is enabled.
7502 if (!mDeps.isChangeEnabled(
7503 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7504 callingPackageName, user)) {
7505 return false;
7506 }
7507
7508 return networkCapabilities.hasCapability(
7509 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7510 || networkCapabilities.hasCapability(
7511 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7512 }
7513
7514 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7515 @NonNull final NetworkCapabilities networkCapabilities) {
7516 // This check is added to fix the linter error for "current min is 30", which is not going
7517 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007518 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007519 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7520 return;
7521 }
7522 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007523 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007524 try {
7525 synchronized (mSelfCertifiedCapabilityCache) {
7526 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7527 callerPackageName);
7528 if (applicationNetworkCapabilities == null) {
7529 final PackageManager packageManager = mContext.getPackageManager();
7530 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7531 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7532 callerPackageName
7533 );
7534 final XmlResourceParser parser = packageManager
7535 .getResourcesForApplication(callerPackageName)
7536 .getXml(networkSliceProperty.getResourceId());
7537 applicationNetworkCapabilities =
7538 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7539 mSelfCertifiedCapabilityCache.put(callerPackageName,
7540 applicationNetworkCapabilities);
7541 }
7542
7543 }
7544 } catch (PackageManager.NameNotFoundException ne) {
7545 throw new SecurityException(
7546 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7547 + " property");
7548 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7549 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007550 } finally {
7551 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007552 }
7553
7554 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7555 networkCapabilities);
7556 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007557 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007558 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007559 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7560 callingPackageName)) {
7561 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7562 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007563 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007564 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7565 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7566 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7567 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007568 }
junyulai96bd9fe2022-03-08 17:36:42 +08007569 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007570 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007571 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007572 }
7573 }
7574
fenglu3f357402015-03-20 11:29:56 -07007575 @Override
fenglub00f4882015-04-21 17:12:05 -07007576 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007577 enforceAccessPermission();
7578 NetworkAgentInfo nai = null;
7579 if (network == null) {
7580 return false;
7581 }
7582 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007583 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007584 }
7585 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007586 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007587 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007588 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007589 Integer uidReqs = mBandwidthRequests.get(uid);
7590 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007591 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007592 }
7593 mBandwidthRequests.put(uid, ++uidReqs);
7594 }
fenglu3f357402015-03-20 11:29:56 -07007595 return true;
7596 }
7597 return false;
7598 }
7599
Felipe Leme0a5ae422016-06-20 16:36:29 -07007600 private boolean isSystem(int uid) {
7601 return uid < Process.FIRST_APPLICATION_UID;
7602 }
fenglu3f357402015-03-20 11:29:56 -07007603
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007604 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007605 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007606 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007607 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007608 return;
7609 }
Hugo Benichi39621362017-02-11 17:04:43 +09007610 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7611 // Policy already enforced.
7612 return;
7613 }
paulhuaf50d7d2020-12-24 19:47:34 +08007614 final long ident = Binder.clearCallingIdentity();
7615 try {
7616 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7617 // If UID is restricted, don't allow them to bring up metered APNs.
7618 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7619 }
7620 } finally {
7621 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007622 }
7623 }
7624
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007625 @Override
7626 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007627 PendingIntent operation, @NonNull String callingPackageName,
7628 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007629 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007630 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007631 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007632 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007633 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007634 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007635 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007636 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007637 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007638 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7639 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007640
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007641 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007642 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007643 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7644 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007645 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007646 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7647 nri));
7648 return networkRequest;
7649 }
7650
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007651 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7652 mHandler.sendMessageDelayed(
7653 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007654 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007655 }
7656
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007657 @Override
7658 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007659 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007660 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007661 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007662 }
7663
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007664 // In order to implement the compatibility measure for pre-M apps that call
7665 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7666 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7667 // This ensures it has permission to do so.
7668 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7669 if (nc == null) {
7670 return false;
7671 }
7672 int[] transportTypes = nc.getTransportTypes();
7673 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7674 return false;
7675 }
7676 try {
7677 mContext.enforceCallingOrSelfPermission(
7678 android.Manifest.permission.ACCESS_WIFI_STATE,
7679 "ConnectivityService");
7680 } catch (SecurityException e) {
7681 return false;
7682 }
7683 return true;
7684 }
7685
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007686 @Override
7687 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007688 Messenger messenger, IBinder binder,
7689 @NetworkCallback.Flag int callbackFlags,
7690 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007691 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007692 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7693 enforceAccessPermission();
7694 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007695
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007696 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007697 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007698 Binder.getCallingPid(), callingUid, callingPackageName);
7699 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007700 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7701 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7702 // onLost and onAvailable callbacks when networks move in and out of the background.
7703 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7704 // can't request networks.
7705 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007706 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007707
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007708 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007709 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007710 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007711 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007712 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007713 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007714
7715 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7716 return networkRequest;
7717 }
7718
7719 @Override
7720 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007721 PendingIntent operation, @NonNull String callingPackageName,
7722 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007723 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007724 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007725 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7726 enforceAccessPermission();
7727 }
Chalard Jeandd421992021-12-16 23:16:02 +09007728 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007729 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007730 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007731 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007732 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007733
7734 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007735 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007736 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7737 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007738 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007739
WeiZhang1cc3f172021-06-03 19:02:04 -05007740 mHandler.sendMessage(mHandler.obtainMessage(
7741 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007742 }
7743
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007744 /** Returns the next Network provider ID. */
7745 public final int nextNetworkProviderId() {
7746 return mNextNetworkProviderId.getAndIncrement();
7747 }
7748
Erik Kline0c04b742016-07-07 16:50:58 +09007749 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007750 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007751 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007752 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007753 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007754 }
7755
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007756 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7757 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007758 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7759 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7760 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007761 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007762 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007763 return;
7764 }
7765
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007766 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7767 mNetworkProviderInfos.put(npi.messenger, npi);
7768 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007769 }
7770
7771 @Override
7772 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007773 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007774 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007775 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007776 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007777 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7778 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007779 }
7780
7781 @Override
7782 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007783 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007784 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007785 }
7786
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007787 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007788 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007789 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7790 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007791 Objects.requireNonNull(score);
7792 Objects.requireNonNull(caps);
7793 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007794 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007795 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007796 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7797 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007798 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7799 }
7800
Chalard Jeanbb902a52021-08-18 01:35:19 +09007801 private void updateOfferScore(final NetworkOffer offer) {
7802 final boolean yieldToBadWiFi =
7803 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7804 final NetworkOffer newOffer = new NetworkOffer(
7805 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7806 offer.caps, offer.callback, offer.providerId);
7807 if (offer.equals(newOffer)) return;
7808 handleRegisterNetworkOffer(newOffer);
7809 }
7810
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007811 @Override
7812 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007813 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007814 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7815 }
7816
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007817 private void handleUnregisterNetworkProvider(Messenger messenger) {
7818 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7819 if (npi == null) {
7820 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007821 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007822 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007823 // Unregister all the offers from this provider
7824 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7825 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007826 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007827 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7828 toRemove.add(noi);
7829 }
7830 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007831 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007832 handleUnregisterNetworkOffer(noi);
7833 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007834 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007835 }
7836
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007837 @Override
James Mattisf7027322020-12-13 16:28:14 -08007838 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007839 if (request.hasTransport(TRANSPORT_TEST)) {
7840 enforceNetworkFactoryOrTestNetworksPermission();
7841 } else {
7842 enforceNetworkFactoryPermission();
7843 }
James Mattisf7027322020-12-13 16:28:14 -08007844 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7845 if (nri != null) {
7846 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7847 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7848 mHandler.post(() -> handleReleaseNetworkRequest(
7849 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7850 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007851 }
7852
Paul Jensen1f567382015-02-13 14:18:39 -05007853 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7854 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007855 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007856 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007857 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007858 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007859 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007860
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007861 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007862 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007863 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007864
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007865 // UID ranges for users that are currently blocked by VPNs.
7866 // This array is accessed and iterated on multiple threads without holding locks, so its
7867 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7868 // (on the handler thread).
7869 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7870
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007871 // Must only be accessed on the handler thread
7872 @NonNull
7873 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7874
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007875 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007876 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007877
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007878 // Current OEM network preferences. This object must only be written to on the handler thread.
7879 // Since it is immutable and always non-null, other threads may read it if they only care
7880 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007881 @NonNull
7882 private OemNetworkPreferences mOemNetworkPreferences =
7883 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007884 // Current per-profile network preferences. This object follows the same threading rules as
7885 // the OEM network preferences above.
7886 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007887 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7888 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007889
lucaslin3ba7cc22022-12-19 02:35:33 +00007890 // Current VPN network preferences. This object follows the same threading rules as the OEM
7891 // network preferences above.
7892 @NonNull
7893 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7894 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7895
paulhu51f77dc2021-06-07 02:34:20 +00007896 // A set of UIDs that should use mobile data preferentially if available. This object follows
7897 // the same threading rules as the OEM network preferences above.
7898 @NonNull
7899 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7900
James Mattiscb1e0362021-04-06 17:07:42 -07007901 // OemNetworkPreferences activity String log entries.
7902 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7903 @NonNull
7904 private final LocalLog mOemNetworkPreferencesLogs =
7905 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7906
James Mattis02220e22021-03-13 19:27:21 -08007907 /**
7908 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7909 * @param packageName the package name to check existence of a mapping for.
7910 * @return true if a mapping exists, false otherwise
7911 */
7912 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7913 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7914 }
7915
James Mattise3ef1912020-12-20 11:09:58 -08007916 // The always-on request for an Internet-capable network that apps without a specific default
7917 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007918 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007919 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007920 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007921 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007922 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007923 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007924 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007925
James Mattisd31bdfa2020-12-23 16:37:26 -08007926 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7927 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7928 }
7929
7930 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007931 * Return the default network request currently tracking the given uid.
7932 * @param uid the uid to check.
7933 * @return the NetworkRequestInfo tracking the given uid.
7934 */
7935 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007936 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007937 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007938 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007939 // Checking the first request is sufficient as only multilayer requests will have more
7940 // than one request and for multilayer, all requests will track the same uids.
7941 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007942 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007943 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007944 highestPriorityNri = nri;
7945 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007946 }
7947 }
paulhuaa0743d2021-05-26 21:56:03 +08007948 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007949 }
7950
7951 /**
7952 * Get a copy of the network requests of the default request that is currently tracking the
7953 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007954 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7955 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007956 * @param requestorUid the uid to check the default for.
7957 * @param requestorPackageName the requestor's package name.
7958 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7959 */
7960 @NonNull
7961 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007962 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007963 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007964 getDefaultRequestTrackingUid(asUid).mRequests,
7965 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007966 }
7967
7968 /**
7969 * Copy the given nri's NetworkRequest collection.
7970 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007971 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7972 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007973 * @param requestorUid the uid to set on the copied collection.
7974 * @param requestorPackageName the package name to set on the copied collection.
7975 * @return the copied NetworkRequest collection.
7976 */
7977 @NonNull
7978 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007979 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7980 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007981 final List<NetworkRequest> requests = new ArrayList<>();
7982 for (final NetworkRequest nr : requestsToCopy) {
7983 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007984 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007985 nr.legacyType, nextNetworkRequestId(), nr.type));
7986 }
7987 return requests;
7988 }
7989
7990 @NonNull
7991 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007992 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7993 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007994 // These capabilities are for a TRACK_DEFAULT callback, so:
7995 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7996 // mDefaultRequest and a per-UID default request.
7997 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007998 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007999 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008000 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8001 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008002 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008003 restrictRequestUidsForCallerAndSetRequestorInfo(
8004 netCap, requestorUid, requestorPackageName);
8005 return netCap;
8006 }
8007
8008 /**
8009 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8010 * @param nr the network request to check for equality against.
8011 * @return the nri if one exists, null otherwise.
8012 */
8013 @Nullable
8014 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8015 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8016 if (nri.getNetworkRequestForCallback().equals(nr)) {
8017 return nri;
8018 }
8019 }
8020 return null;
8021 }
8022
8023 /**
8024 * Check if an nri is currently being managed by per-app default networking.
8025 * @param nri the nri to check.
8026 * @return true if this nri is currently being managed by per-app default networking.
8027 */
8028 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8029 // nri.mRequests.get(0) is only different from the original request filed in
8030 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8031 // functionality therefore if these two don't match, it means this particular nri is
8032 // currently being managed by a per-app default.
8033 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8034 }
8035
8036 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008037 * Determine if an nri is a managed default request that disallows default networking.
8038 * @param nri the request to evaluate
8039 * @return true if device-default networking is disallowed
8040 */
8041 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8042 // Check if this nri is a managed default that supports the default network at its
8043 // lowest priority request.
8044 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8045 final NetworkCapabilities lowestPriorityNetCap =
8046 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8047 return isPerAppDefaultRequest(nri)
8048 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8049 lowestPriorityNetCap));
8050 }
8051
Erik Kline05f2b402015-04-30 12:58:40 +09008052 // Request used to optionally keep mobile data active even when higher
8053 // priority networks like Wi-Fi are active.
8054 private final NetworkRequest mDefaultMobileDataRequest;
8055
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008056 // Request used to optionally keep wifi data active even when higher
8057 // priority networks like ethernet are active.
8058 private final NetworkRequest mDefaultWifiRequest;
8059
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008060 // Request used to optionally keep vehicle internal network always active
8061 private final NetworkRequest mDefaultVehicleRequest;
8062
James Mattisd31bdfa2020-12-23 16:37:26 -08008063 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8064 // network with no service. This NAI should never be matched against, nor should any public API
8065 // ever return the associated network. For this reason, this NAI is not in the list of available
8066 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8067 // default requests that don't support using the device default network which will ultimately
8068 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8069 @VisibleForTesting
8070 final NetworkAgentInfo mNoServiceNetwork;
8071
Chalard Jean5b409c72021-02-04 13:12:59 +09008072 // The NetworkAgentInfo currently satisfying the default request, if any.
8073 private NetworkAgentInfo getDefaultNetwork() {
8074 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008075 }
8076
James Mattis2516da32021-01-31 17:06:19 -08008077 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008078 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008079 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8080 // Currently, all network requests will have the same uids therefore checking the first
8081 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008082 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008083 if (null == uids) {
8084 continue;
8085 }
8086 for (final UidRange range : uids) {
8087 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008088 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008089 highestPriorityNri = nri;
8090 }
James Mattis2516da32021-01-31 17:06:19 -08008091 }
8092 }
8093 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008094 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008095 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008096 }
8097
Varun Ananddf569952019-02-06 10:13:38 -08008098 @Nullable
8099 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8100 return nai != null ? nai.network : null;
8101 }
8102
8103 private void ensureRunningOnConnectivityServiceThread() {
8104 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8105 throw new IllegalStateException(
8106 "Not running on ConnectivityService thread: "
8107 + Thread.currentThread().getName());
8108 }
8109 }
8110
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008111 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008112 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8113 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008114 }
8115
Chalard Jean29d06db2018-05-02 21:14:54 +09008116 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008117 * Returns whether local agents are supported on this device.
8118 *
8119 * Local agents are supported from U on TVs, and from V on all devices.
8120 */
8121 @VisibleForTesting
8122 public boolean areLocalAgentsSupported() {
8123 final PackageManager pm = mContext.getPackageManager();
8124 // Local agents are supported starting on U on TVs and on V on everything else.
8125 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8126 }
8127
8128 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008129 * Register a new agent with ConnectivityService to handle a network.
8130 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008131 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008132 * @param networkInfo the initial info associated with this network. It can be updated later :
8133 * see {@link #updateNetworkInfo}.
8134 * @param linkProperties the initial link properties of this network. They can be updated
8135 * later : see {@link #updateLinkProperties}.
8136 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008137 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008138 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008139 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008140 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008141 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008142 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008143 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008144 public Network registerNetworkAgent(INetworkAgent na,
8145 NetworkInfo networkInfo,
8146 LinkProperties linkProperties,
8147 NetworkCapabilities networkCapabilities,
8148 @NonNull NetworkScore initialScore,
8149 @Nullable LocalNetworkConfig localNetworkConfig,
8150 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008151 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008152 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8153 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8154 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008155 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008156 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008157 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008158 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008159 } else {
8160 enforceNetworkFactoryPermission();
8161 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008162 final boolean hasLocalCap =
8163 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8164 if (hasLocalCap && !areLocalAgentsSupported()) {
8165 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8166 throw new IllegalArgumentException("Local agents are not supported in this version");
8167 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008168 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8169 if (hasLocalCap != hasLocalNetworkConfig) {
8170 throw new IllegalArgumentException(null != localNetworkConfig
8171 ? "Only local network agents can have a LocalNetworkConfig"
8172 : "Local network agents must have a LocalNetworkConfig"
8173 );
8174 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008175
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008176 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008177 final long token = Binder.clearCallingIdentity();
8178 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008179 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008180 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8181 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008182 } finally {
8183 Binder.restoreCallingIdentity(token);
8184 }
8185 }
8186
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008187 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008188 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008189 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8190 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008191 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008192
Chalard Jeandbc46952022-02-02 00:14:18 +09008193 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8194 // and mutate them at any time.
8195 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8196 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8197 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008198 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008199
Chalard Jean366c5252022-01-25 18:27:53 +09008200 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008201 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008202 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8203 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008204 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008205 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008206 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8207 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8208 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008209
Chalard Jeandbc46952022-02-02 00:14:18 +09008210 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008211 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008212 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008213 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008214 mDeps.getNetworkStack().makeNetworkMonitor(
8215 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008216 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8217 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008218 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008219 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008220 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008221 }
8222
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008223 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008224 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008225 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008226 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008227 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008228 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8229 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8230 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008231
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008232 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008233
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008234 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008235 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008236 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008237 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008238
8239 try {
8240 networkMonitor.start();
8241 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008242 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008243 }
Chalard Jean366c5252022-01-25 18:27:53 +09008244
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008245 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008246 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008247 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008248 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008249 }
8250
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008251 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8252 @NonNull public final NetworkOffer offer;
8253
8254 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8255 this.offer = offer;
8256 }
8257
8258 @Override
8259 public void binderDied() {
8260 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8261 }
8262 }
8263
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008264 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8265 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8266 if (npi.providerId == providerId) return true;
8267 }
8268 return false;
8269 }
8270
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008271 /**
8272 * Register or update a network offer.
8273 * @param newOffer The new offer. If the callback member is the same as an existing
8274 * offer, it is an update of that offer.
8275 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008276 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008277 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8278 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008279 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008280 // This may actually happen if a provider updates its score or registers and then
8281 // immediately unregisters. The offer would still be in the handler queue, but the
8282 // provider would have been removed.
8283 if (DBG) log("Received offer from an unregistered provider");
8284 return;
8285 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008286 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8287 if (null != existingOffer) {
8288 handleUnregisterNetworkOffer(existingOffer);
8289 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008290 if (DBG) {
8291 // handleUnregisterNetworkOffer has already logged the old offer
8292 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8293 }
8294 } else {
8295 if (DBG) {
8296 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8297 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008298 }
8299 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8300 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008301 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008302 } catch (RemoteException e) {
8303 noi.binderDied();
8304 return;
8305 }
8306 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008307 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008308 }
8309
8310 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8311 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008312 if (DBG) {
8313 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8314 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008315
8316 // If the provider removes the offer and dies immediately afterwards this
8317 // function may be called twice in a row, but the array will no longer contain
8318 // the offer.
8319 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008320 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008321 }
8322
8323 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8324 @NonNull final INetworkOfferCallback callback) {
8325 ensureRunningOnConnectivityServiceThread();
8326 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008327 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008328 }
8329 return null;
8330 }
8331
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008332 /**
8333 * Called when receiving LinkProperties directly from a NetworkAgent.
8334 * Stores into |nai| any data coming from the agent that might also be written to the network's
8335 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8336 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008337 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008338 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008339 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8340 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008341 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008342 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008343 }
8344
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008345 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008346 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008347 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008348
Lorenzo Colittid523d142020-04-01 20:16:30 +09008349 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8350 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8351 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008352 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008353
Suprabh Shukla1e312032023-01-24 03:36:37 -08008354 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008355
8356 // update filtering rules, need to happen after the interface update so netd knows about the
8357 // new interface (the interface name -> index map becomes initialized)
8358 updateVpnFiltering(newLp, oldLp, networkAgent);
8359
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008360 updateMtu(newLp, oldLp);
8361 // TODO - figure out what to do for clat
8362// for (LinkProperties lp : newLp.getStackedLinks()) {
8363// updateMtu(lp, null);
8364// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008365 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008366 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008367 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8368 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008369
Erik Klineb9888902016-04-05 13:30:49 +09008370 updateRoutes(newLp, oldLp, netId);
8371 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008372 // Make sure LinkProperties represents the latest private DNS status.
8373 // This does not need to be done before updateDnses because the
8374 // LinkProperties are not the source of the private DNS configuration.
8375 // updateDnses will fetch the private DNS configuration from DnsManager.
8376 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008377
Chalard Jean5b409c72021-02-04 13:12:59 +09008378 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008379 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008380 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008381 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008382 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008383
8384 updateWakeOnLan(newLp);
8385
Hai Shalome58bdc62021-01-11 18:45:34 -08008386 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8387 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8388 // does, it needs to be merged here.
8389 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8390 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008391
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008392 // TODO - move this check to cover the whole function
8393 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008394 synchronized (networkAgent) {
8395 networkAgent.linkProperties = newLp;
8396 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008397 // Start or stop DNS64 detection and 464xlat according to network state.
8398 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008399 // Notify NSS when relevant events happened. Currently, NSS only cares about
8400 // interface changed to update clat interfaces accounting.
8401 final boolean interfacesChanged = oldLp == null
8402 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8403 if (interfacesChanged) {
8404 notifyIfacesChangedForNetworkStats();
8405 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008406 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8407 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008408 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008409 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008410
8411 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008412 }
8413
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008414 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8415 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8416 }
8417
Hai Shalome58bdc62021-01-11 18:45:34 -08008418 /**
8419 * @param naData captive portal data from NetworkAgent
8420 * @param apiData captive portal data from capport API
8421 */
8422 @Nullable
8423 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8424 CaptivePortalData apiData) {
8425 if (naData == null || apiData == null) {
8426 return naData == null ? apiData : naData;
8427 }
8428 final CaptivePortalData.Builder captivePortalBuilder =
8429 new CaptivePortalData.Builder(naData);
8430
8431 if (apiData.isCaptive()) {
8432 captivePortalBuilder.setCaptive(true);
8433 }
8434 if (apiData.isSessionExtendable()) {
8435 captivePortalBuilder.setSessionExtendable(true);
8436 }
8437 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8438 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8439 // otherwise data would be inconsistent. Prefer the capport API info if present,
8440 // as it can generally be refreshed more often.
8441 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8442 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8443 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8444 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8445 // No source has time / bytes remaining information: surface the newest refresh time
8446 // for other fields
8447 captivePortalBuilder.setRefreshTime(
8448 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8449 }
8450
Hai Shalom7c6ab402021-02-04 19:34:06 -08008451 // Prioritize the user portal URL from the network agent if the source is authenticated.
8452 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8453 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8454 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8455 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008456 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008457 // Prioritize the venue information URL from the network agent if the source is
8458 // authenticated.
8459 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8460 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8461 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8462 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008463 }
8464 return captivePortalBuilder.build();
8465 }
8466
Suprabh Shukla53e16392023-04-26 18:47:36 -07008467 @VisibleForTesting
8468 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008469 // This needs to be kept in sync and backwards compatible with the decoding logic in
8470 // NetdEventListenerService, which is non-mainline code.
8471 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8472 }
8473
Suprabh Shukla75642282023-04-25 23:15:43 -07008474 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8475 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8476 return true;
8477 }
8478 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8479 return true;
8480 }
8481 return false;
8482 }
8483
Suprabh Shukla1e312032023-01-24 03:36:37 -08008484 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008485 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008486 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008487 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008488 return;
8489 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008490
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008491 // Mask/mark of zero will not detect anything interesting.
8492 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008493 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008494 return;
8495 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008496
Suprabh Shukla1e312032023-01-24 03:36:37 -08008497 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008498 try {
8499 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008500 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008501 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008502 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008503 }
8504 } catch (Exception e) {
8505 loge("Exception modifying wakeup packet monitoring: " + e);
8506 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008507 }
8508
Junyu Lai970963e2022-10-25 15:46:47 +08008509 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008510 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008511 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008512 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008513 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008514 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008515 for (final String iface : interfaceDiff.added) {
8516 try {
8517 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008518 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008519 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008520 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008521 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008522 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008523 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008524 }
Paul Jensenbff73492014-04-28 10:33:11 -04008525 }
8526 }
Chalard Jean9589e722019-11-19 19:03:53 +09008527 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008528 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008529 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008530 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008531 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008532 } catch (Exception e) {
8533 loge("Exception removing interface: " + e);
8534 }
8535 }
8536 }
8537
Tyler Weare4314862019-12-05 14:55:30 -08008538 // TODO: move to frameworks/libs/net.
8539 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8540 final String nextHop;
8541
8542 switch (route.getType()) {
8543 case RouteInfo.RTN_UNICAST:
8544 if (route.hasGateway()) {
8545 nextHop = route.getGateway().getHostAddress();
8546 } else {
8547 nextHop = INetd.NEXTHOP_NONE;
8548 }
8549 break;
8550 case RouteInfo.RTN_UNREACHABLE:
8551 nextHop = INetd.NEXTHOP_UNREACHABLE;
8552 break;
8553 case RouteInfo.RTN_THROW:
8554 nextHop = INetd.NEXTHOP_THROW;
8555 break;
8556 default:
8557 nextHop = INetd.NEXTHOP_NONE;
8558 break;
8559 }
8560
8561 final RouteInfoParcel rip = new RouteInfoParcel();
8562 rip.ifName = route.getInterface();
8563 rip.destination = route.getDestination().toString();
8564 rip.nextHop = nextHop;
8565 rip.mtu = route.getMtu();
8566
8567 return rip;
8568 }
8569
Paul Jensene0fd4a82014-08-06 15:51:33 -04008570 /**
8571 * Have netd update routes from oldLp to newLp.
8572 * @return true if routes changed between oldLp and newLp
8573 */
Junyu Lai970963e2022-10-25 15:46:47 +08008574 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8575 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008576 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008577 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8578 new CompareOrUpdateResult<>(
8579 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008580 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008581 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008582
8583 // add routes before removing old in case it helps with continuous connectivity
8584
Chalard Jean9dd11612018-06-04 16:52:49 +09008585 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008586 for (RouteInfo route : routeDiff.added) {
8587 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008588 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008589 try {
Tyler Weare4314862019-12-05 14:55:30 -08008590 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008591 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008592 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008593 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008594 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008595 }
8596 }
8597 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008598 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008599 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008600 try {
Tyler Weare4314862019-12-05 14:55:30 -08008601 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008602 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008603 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008604 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008605 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008606 }
8607 }
8608
8609 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008610 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008611 try {
Tyler Weare4314862019-12-05 14:55:30 -08008612 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008613 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008614 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008615 }
8616 }
Tyler Weare4314862019-12-05 14:55:30 -08008617
8618 for (RouteInfo route : routeDiff.updated) {
8619 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8620 try {
8621 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8622 } catch (Exception e) {
8623 loge("Exception in networkUpdateRouteParcel: " + e);
8624 }
8625 }
8626 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8627 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008628 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008629
Junyu Lai970963e2022-10-25 15:46:47 +08008630 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8631 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008632 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8633 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008634 }
Erik Klineb9888902016-04-05 13:30:49 +09008635
Erik Kline31b4a9e2018-01-11 21:07:29 +09008636 if (DBG) {
8637 final Collection<InetAddress> dnses = newLp.getDnsServers();
8638 log("Setting DNS servers for network " + netId + " to " + dnses);
8639 }
Erik Klineb9888902016-04-05 13:30:49 +09008640 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008641 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008642 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008643 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008644 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008645 }
Erik Kline54e35c02017-04-07 15:29:29 +09008646 }
8647
Junyu Lai970963e2022-10-25 15:46:47 +08008648 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8649 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008650 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8651 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008652 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8653 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008654
8655 if (!wasFiltering && !needsFiltering) {
8656 // Nothing to do.
8657 return;
8658 }
8659
8660 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8661 // Nothing changed.
8662 return;
8663 }
8664
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008665 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008666 if (ranges == null || ranges.isEmpty()) {
8667 return;
8668 }
8669
Qingxi Libb8da982020-01-17 17:54:27 -08008670 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008671 // TODO: this create a window of opportunity for apps to receive traffic between the time
8672 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008673 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008674 // old rules are being removed.
8675 if (wasFiltering) {
8676 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8677 }
8678 if (needsFiltering) {
8679 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8680 }
8681 }
8682
Valentin Iftime9fa35092019-09-24 13:32:13 +02008683 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008684 if (mWolSupportedInterfaces == null) {
8685 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008686 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008687 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008688 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8689 }
8690
Luke Huangb913c812018-08-24 20:33:16 +08008691 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008692 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008693 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008694 }
8695 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008696 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008697 }
Luke Huangb913c812018-08-24 20:33:16 +08008698 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008699 }
8700
Chalard Jean62edfd82019-12-02 18:39:29 +09008701 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8702 @NonNull final NetworkCapabilities newNc) {
8703 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8704 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008705 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008706 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008707 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008708 } catch (RemoteException | ServiceSpecificException e) {
8709 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008710 }
8711 }
8712 }
8713
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008714 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008715 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008716 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008717 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008718 underlyingNetworks = underlyingNetworksOrDefault(
8719 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008720 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008721 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8722 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008723 // metered if any underlying is metered, or originally declared metered by the agent.
8724 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008725 boolean roaming = false; // roaming if any underlying is roaming
8726 boolean congested = false; // congested if any underlying is congested
8727 boolean suspended = true; // suspended if all underlying are suspended
8728
8729 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008730 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008731 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008732 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008733 for (Network underlyingNetwork : underlyingNetworks) {
8734 final NetworkAgentInfo underlying =
8735 getNetworkAgentInfoForNetwork(underlyingNetwork);
8736 if (underlying == null) continue;
8737
8738 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8739 hadUnderlyingNetworks = true;
8740 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008741 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008742 }
8743
8744 // Merge capabilities of this underlying network. For bandwidth, assume the
8745 // worst case.
8746 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8747 underlyingCaps.getLinkDownstreamBandwidthKbps());
8748 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8749 underlyingCaps.getLinkUpstreamBandwidthKbps());
8750 // If this underlying network is metered, the VPN is metered (it may cost money
8751 // to send packets on this network).
8752 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8753 // If this underlying network is roaming, the VPN is roaming (the billing structure
8754 // is different than the usual, local one).
8755 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8756 // If this underlying network is congested, the VPN is congested (the current
8757 // condition of the network affects the performance of this network).
8758 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8759 // If this network is not suspended, the VPN is not suspended (the VPN
8760 // is able to transfer some data).
8761 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008762 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008763 }
8764 }
8765 if (!hadUnderlyingNetworks) {
8766 // No idea what the underlying networks are; assume reasonable defaults
8767 metered = true;
8768 roaming = false;
8769 congested = false;
8770 suspended = false;
8771 }
8772
Chalard Jean1d420b32022-10-12 16:39:37 +09008773 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008774 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8775 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8776 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8777 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8778 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8779 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008780 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008781 }
8782
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008783 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008784 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8785 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8786 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008787 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008788 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008789 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008790 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008791 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8792 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008793 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008794 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008795 if (nai.everConnected()
8796 && !nai.isVPN()
8797 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008798 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008799 // does not cause any request (that is not a listen) currently matching that agent to
8800 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008801 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008802 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008803 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008804 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008805 }
8806
Paul Jensen53f08952015-06-16 14:27:36 -04008807 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008808 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008809 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008810 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008811 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008812 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008813 }
Chalard Jean254bd162022-08-25 13:04:51 +09008814 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008815 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008816 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008817 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008818 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008819 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008820 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008821 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008822 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008823 }
Chalard Jean254bd162022-08-25 13:04:51 +09008824 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008825 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8826 } else {
8827 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8828 }
lucasline117e2e2019-10-22 18:27:33 +08008829 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008830
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008831 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008832 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8833 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008834 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008835 }
8836
Lorenzo Colittibd079452021-07-02 11:47:57 +09008837 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008838 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008839 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008840 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008841 }
8842
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008843 return newNc;
8844 }
8845
Lorenzo Colitti44840702021-01-11 22:27:57 +09008846 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8847 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8848 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8849 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8850 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8851 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8852 if (prevSuspended != suspended) {
8853 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8854 // onResumed have been removed.
8855 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8856 : ConnectivityManager.CALLBACK_RESUMED);
8857 }
8858 if (prevSuspended != suspended || prevRoaming != roaming) {
8859 // updateNetworkInfo will mix in the suspended info from the capabilities and
8860 // take appropriate action for the network having possibly changed state.
8861 updateNetworkInfo(nai, nai.networkInfo);
8862 }
8863 }
8864
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008865 /**
8866 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8867 *
8868 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8869 * capabilities we manage and store in {@code nai}, such as validated status and captive
8870 * portal status)
8871 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8872 * potentially triggers rematches.
8873 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8874 * change.)
8875 *
8876 * @param oldScore score of the network before any of the changes that prompted us
8877 * to call this function.
8878 * @param nai the network having its capabilities updated.
8879 * @param nc the new network capabilities.
8880 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008881 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008882 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008883 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008884 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008885 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8886 if (null != differences) {
8887 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8888 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008889 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008890 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008891
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008892 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008893 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008894 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008895
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008896 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008897 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8898 // the change we're processing can't affect any requests, it can only affect the listens
8899 // on this network. We might have been called by rematchNetworkAndRequests when a
8900 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008901 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008902 } else {
8903 // If the requestable capabilities have changed or the score changed, we can't have been
8904 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008905 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008906 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008907 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008908 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008909
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008910 final boolean oldMetered = prevNc.isMetered();
8911 final boolean newMetered = newNc.isMetered();
8912 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008913
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008914 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008915 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8916 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008917 }
junyulaif2c67e42018-08-07 19:50:45 +08008918
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008919 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8920 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008921
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008922 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008923 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008924 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008925 }
8926
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008927 // This network might have been underlying another network. Propagate its capabilities.
8928 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008929
8930 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008931 mDnsManager.updateTransportsForNetwork(
8932 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008933 }
lucaslin53e8a262021-06-08 01:43:59 +08008934
8935 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008936 }
8937
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008938 /** Convenience method to update the capabilities for a given network. */
8939 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008940 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008941 }
8942
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008943 private void updateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
8944 @NonNull final LocalNetworkConfig config) {
8945 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK)) {
8946 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
8947 return;
8948 }
8949 // TODO : actually apply the diff.
8950 nai.localNetworkConfig = config;
8951 }
8952
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008953 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008954 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008955 *
8956 * Ingress interface filtering enforces that all apps under the given network can only receive
8957 * packets from the network's interface (and loopback). This is important for VPNs because
8958 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8959 * non-VPN interfaces.
8960 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008961 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008962 * 1. the network is an app VPN (not legacy VPN)
8963 * 2. the VPN does not allow bypass
8964 * 3. the VPN is fully-routed
8965 * 4. the VPN interface is non-null
8966 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008967 * @see INetd#firewallAddUidInterfaceRules
8968 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008969 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008970 @Nullable
8971 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008972 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008973 if (nc == null || lp == null) return null;
8974 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008975 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008976 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008977 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008978 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008979 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008980 && !lp.hasExcludeRoute()) {
8981 return lp.getInterfaceName();
8982 }
8983 return null;
8984 }
8985
8986 /**
8987 * Returns whether we need to set interface filtering rule or not
8988 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008989 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008990 String isolationIface) {
8991 // Allow rules are always needed if VPN isolation is enabled.
8992 if (isolationIface != null) return true;
8993
8994 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8995 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8996 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09008997 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008998 }
8999
Chiachang Wang28afaff2020-12-10 22:24:47 +08009000 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9001 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9002 int index = 0;
9003 for (UidRange range : ranges) {
9004 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9005 index++;
9006 }
9007 return stableRanges;
9008 }
9009
Chalard Jeane6c95272022-01-25 21:04:21 +09009010 private static UidRangeParcel[] intsToUidRangeStableParcels(
9011 final @NonNull ArraySet<Integer> uids) {
9012 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9013 int index = 0;
9014 for (int uid : uids) {
9015 stableRanges[index] = new UidRangeParcel(uid, uid);
9016 index++;
9017 }
9018 return stableRanges;
9019 }
9020
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009021 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9022 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9023 for (int i = 0; i < ranges.length; i++) {
9024 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9025 }
9026 return stableRanges;
9027 }
9028
Motomu Utsumi93a22182023-03-16 17:04:21 +09009029 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009030 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009031 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9032 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009033 if (mDeps.isAtLeastU()) {
9034 final Set<Integer> exemptUidSet = new ArraySet<>();
9035 for (final int uid: exemptUids) {
9036 exemptUidSet.add(uid);
9037 }
9038 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9039 } else {
9040 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9041 }
Ken Chen5e65a852020-12-24 12:59:10 +08009042 } catch (Exception e) {
9043 loge("Exception in socket destroy: ", e);
9044 }
9045 }
9046 }
9047
paulhuaa0743d2021-05-26 21:56:03 +08009048 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009049 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009050 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9051 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9052 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009053 exemptUids[0] = VPN_UID;
9054 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009055 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9056
Motomu Utsumi6345e462023-03-13 13:24:50 +09009057 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009058 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009059 try {
9060 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009061 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009062 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009063 } else {
paulhu0e79d952021-06-09 16:11:35 +08009064 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009065 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009066 }
9067 } catch (Exception e) {
9068 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9069 " on netId " + nai.network.netId + ". " + e);
9070 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009071 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009072 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009073 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009074
lucaslin53e8a262021-06-08 01:43:59 +08009075 private boolean isProxySetOnAnyDefaultNetwork() {
9076 ensureRunningOnConnectivityServiceThread();
9077 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9078 final NetworkAgentInfo nai = nri.getSatisfier();
9079 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9080 return true;
9081 }
9082 }
9083 return false;
9084 }
9085
9086 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9087 NetworkCapabilities newNc) {
9088 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9089 // the proxy might be changed since the default network satisfied by the apps might also
9090 // changed.
9091 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9092 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009093 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9094 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009095 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009096 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9097 mProxyTracker.sendProxyBroadcast();
9098 }
9099 }
9100
Chalard Jeane6c95272022-01-25 21:04:21 +09009101 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9102 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009103 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9104 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009105 if (null == prevRanges) prevRanges = new ArraySet<>();
9106 if (null == newRanges) newRanges = new ArraySet<>();
9107 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9108
9109 prevRanges.removeAll(newRanges);
9110 newRanges.removeAll(prevRangesCopy);
9111
9112 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009113 // When updating the VPN uid routing rules, add the new range first then remove the old
9114 // range. If old range were removed first, there would be a window between the old
9115 // range being removed and the new range being added, during which UIDs contained
9116 // in both ranges are not subject to any VPN routing rules. Adding new range before
9117 // removing old range works because, unlike the filtering rules below, it's possible to
9118 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009119 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9120 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9121 // [1-5] & [1-2],[4-5] == [3]
9122 // Then we can do:
9123 // maybeCloseSockets([3])
9124 // mNetd.networkAddUidRanges([1-2],[4-5])
9125 // mNetd.networkRemoveUidRanges([1-5])
9126 // maybeCloseSockets([3])
9127 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9128 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009129 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009130 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009131 }
9132 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009133 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009134 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009135 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9136 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009137 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9138 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009139 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009140 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009141 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9142 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9143 // were added first and then newRanges got removed later, there would be only one uid
9144 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9145 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9146 // Note that this is in contrast with the (more robust) update of VPN routing rules
9147 // above, where the addition of new ranges happens before the removal of old ranges.
9148 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9149 // to be removed will never overlap with the new range to be added.
9150 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009151 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9152 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009153 }
9154 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009155 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009156 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009157 } catch (Exception e) {
9158 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009159 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009160 }
9161 }
9162
Chalard Jeande665262022-02-25 16:12:12 +09009163 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009164 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9165 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009166 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9167 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009168 if (prevEmpty && newEmpty) return;
9169
9170 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009171 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009172 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009173 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009174
9175 if (prevUids.equals(newUids)) return;
9176
9177 // This implementation is very simple and vastly faster for sets of Integers than
9178 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9179 // a key computed from the value and has storage for that.
9180 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9181 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9182 toRemove.removeAll(newUids);
9183 toAdd.removeAll(prevUids);
9184
9185 try {
9186 if (!toAdd.isEmpty()) {
9187 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9188 nai.network.netId,
9189 intsToUidRangeStableParcels(toAdd),
9190 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9191 }
9192 if (!toRemove.isEmpty()) {
9193 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9194 nai.network.netId,
9195 intsToUidRangeStableParcels(toRemove),
9196 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9197 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009198 } catch (ServiceSpecificException e) {
9199 // Has the interface disappeared since the network was built ?
9200 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009201 } catch (RemoteException e) {
9202 // Netd died. This usually causes a runtime restart anyway.
9203 }
9204 }
9205
Junyu Lai2ed7d412022-10-07 16:52:21 +08009206 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9207 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009208 ensureRunningOnConnectivityServiceThread();
9209
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009210 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009211 // Ignore updates for disconnected networks
9212 return;
9213 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009214 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009215 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009216 + "; created=" + nai.getCreatedTime()
9217 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009218 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009219 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9220 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009221 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009222 }
9223
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009224 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9225 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009226 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009227 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009228 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009229 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9230 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9231 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009232 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9233 // need to be sent as a separate extra.
9234 final NetworkRequest req = nri.isMultilayerRequest()
9235 ? nri.getActiveRequest()
9236 // Non-multilayer listen requests do not have an active request
9237 : nri.mRequests.get(0);
9238 if (req == null) {
9239 Log.wtf(TAG, "No request in NRI " + nri);
9240 }
9241 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009242 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009243 sendIntent(nri.mPendingIntent, intent);
9244 }
9245 // else not handled
9246 }
9247
Michael Groover73f69482023-01-27 11:01:25 -06009248 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9249 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009250 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9251 mPendingIntentWakeLock.acquire();
9252 try {
9253 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009254 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009255 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009256 // Explicitly disallow the receiver from starting activities, to prevent apps from
9257 // utilizing the PendingIntent as a backdoor to do this.
9258 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9259 }
9260 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9261 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009262 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009263 } catch (PendingIntent.CanceledException e) {
9264 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9265 mPendingIntentWakeLock.release();
9266 releasePendingNetworkRequest(pendingIntent);
9267 }
9268 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9269 }
9270
9271 @Override
9272 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9273 String resultData, Bundle resultExtras) {
9274 if (DBG) log("Finished sending " + pendingIntent);
9275 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009276 // Release with a delay so the receiving client has an opportunity to put in its
9277 // own request.
9278 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009279 }
9280
Chalard Jean46bfbf02022-02-02 00:56:25 +09009281 // networkAgent is only allowed to be null if notificationType is
9282 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9283 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009284 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009285 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009286 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009287 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009288 // Default request has no msgr. Also prevents callbacks from being invoked for
9289 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9290 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9291 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009292 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009293 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009294 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009295 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009296 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009297 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009298 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009299 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9300 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009301 }
Roshan Pius951c0032020-12-22 15:10:42 -08009302 final boolean includeLocationSensitiveInfo =
9303 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009304 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009305 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009306 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009307 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009308 networkCapabilitiesRestrictedForCallerPermissions(
9309 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9310 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009311 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009312 nri.mCallingAttributionTag);
9313 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009314 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9315 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009316 // For this notification, arg1 contains the blocked status.
9317 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009318 break;
9319 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009320 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009321 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009322 break;
9323 }
9324 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009325 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009326 final NetworkCapabilities netCap =
9327 networkCapabilitiesRestrictedForCallerPermissions(
9328 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9329 putParcelable(
9330 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009331 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009332 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009333 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009334 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009335 break;
9336 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009337 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009338 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9339 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009340 break;
9341 }
junyulaif2c67e42018-08-07 19:50:45 +08009342 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009343 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009344 msg.arg1 = arg1;
9345 break;
9346 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009347 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009348 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009349 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009350 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009351 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009352 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009353 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009354 }
James Mattis45d81842021-01-10 14:24:24 -08009355 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009356 } catch (RemoteException e) {
9357 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009358 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009359 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009360 }
9361
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009362 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9363 bundle.putParcelable(t.getClass().getSimpleName(), t);
9364 }
9365
Chalard Jean0702f982021-09-16 21:50:07 +09009366 /**
9367 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9368 *
9369 * When a request should be assigned to a new network, it is normally lingered to give
9370 * time for apps to gracefully migrate their connections. When both networks are on the same
9371 * radio, but that radio can't do time-sharing efficiently, this may end up being
9372 * counter-productive because any traffic on the old network may drastically reduce the
9373 * performance of the new network.
9374 * The stack supports a configuration to let modem vendors state that their radio can't
9375 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9376 * from one cell network to another can't be done gracefully.
9377 *
9378 * @param oldNai the old network serving the request
9379 * @param newNai the new network serving the request
9380 * @return whether the switch can be graceful
9381 */
9382 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9383 @NonNull final NetworkAgentInfo newSatisfier) {
9384 if (mCellularRadioTimesharingCapable) return true;
9385 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9386 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9387 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9388 }
9389
Paul Jensenaf94b982014-09-30 15:37:41 -04009390 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009391 if (nai.numRequestNetworkRequests() != 0) {
9392 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9393 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009394 // Ignore listening and track default requests.
9395 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009396 loge("Dead network still had at least " + nr);
9397 break;
9398 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009399 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009400 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009401 }
9402
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009403 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9404 if (oldNetwork == null) {
9405 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9406 return;
9407 }
Chalard Jean49707572019-12-10 21:07:02 +09009408 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009409
9410 // If we get here it means that the last linger timeout for this network expired. So there
9411 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009412 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009413
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009414 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009415 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009416 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009417 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009418 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009419 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009420 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009421 }
9422
James Mattise3ef1912020-12-20 11:09:58 -08009423 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9424 boolean isDefaultChanged = false;
9425 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9426 final NetworkReassignment.RequestReassignment reassignment =
9427 changes.getReassignment(defaultRequestInfo);
9428 if (null == reassignment) {
9429 continue;
9430 }
9431 // reassignment only contains those instances where the satisfying network changed.
9432 isDefaultChanged = true;
9433 // Notify system services of the new default.
9434 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9435 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009436
James Mattise3ef1912020-12-20 11:09:58 -08009437 if (isDefaultChanged) {
9438 // Hold a wakelock for a short time to help apps in migrating to a new default.
9439 scheduleReleaseNetworkTransitionWakelock();
9440 }
9441 }
9442
Aaron Huang9fe47be2021-06-08 13:11:45 +08009443 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9444 if (null == oldDefaultNetwork) return;
9445 // The network stopped being the default. If it was using a PAC proxy, then the
9446 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9447 // to the local proxy server, which would forward them over the newly default network.
9448 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9449 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9450 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9451 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9452 }
9453
James Mattise3ef1912020-12-20 11:09:58 -08009454 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9455 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9456 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9457 if (DBG) {
9458 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9459 }
Chalard Jean8e382112019-12-03 20:45:30 +09009460
James Mattisd31bdfa2020-12-23 16:37:26 -08009461 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9462 if (newDefaultNetwork != null) {
9463 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009464 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009465
James Mattisd31bdfa2020-12-23 16:37:26 -08009466 // Set an app level managed default and return since further processing only applies to the
9467 // default network.
9468 if (mDefaultRequest != nri) {
9469 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9470 return;
9471 }
9472
9473 makeDefaultNetwork(newDefaultNetwork);
9474
James Mattise3ef1912020-12-20 11:09:58 -08009475 if (oldDefaultNetwork != null) {
9476 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9477 }
9478 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009479 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009480 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009481 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009482 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009483 updateTcpBufferSizes(null != newDefaultNetwork
9484 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009485 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009486 }
9487
James Mattisd31bdfa2020-12-23 16:37:26 -08009488 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9489 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9490 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9491 try {
9492 if (VDBG) {
9493 log("Setting default network for " + nri
9494 + " using UIDs " + nri.getUids()
9495 + " with old network " + (oldDefaultNetwork != null
9496 ? oldDefaultNetwork.network().getNetId() : "null")
9497 + " and new network " + (newDefaultNetwork != null
9498 ? newDefaultNetwork.network().getNetId() : "null"));
9499 }
9500 if (nri.getUids().isEmpty()) {
9501 throw new IllegalStateException("makeDefaultForApps called without specifying"
9502 + " any applications to set as the default." + nri);
9503 }
9504 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009505 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009506 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009507 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009508 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009509 }
9510 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009511 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009512 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009513 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009514 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009515 }
9516 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009517 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009518 }
9519 }
9520
Junyu Lai35665cc2022-12-19 17:37:48 +08009521 /**
9522 * Collect restricted uid ranges for the given network and UserHandle, these uids
9523 * are not restricted for matched enterprise networks but being restricted for non-matched
9524 * enterprise networks and non-enterprise networks.
9525 */
9526 @NonNull
9527 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9528 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9529 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9530 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9531 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9532
9533 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9534 // The NC is built from a `ProfileNetworkPreference` which has only one
9535 // enterprise ID, so it's guaranteed to have exactly one.
9536 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9537 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9538 continue;
9539 }
9540 }
9541
9542 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9543 pref.capabilities.getUidRanges())) {
9544 throw new IllegalArgumentException(
9545 "Overlapping uid range in preference: " + pref);
9546 }
9547 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9548 }
9549 return restrictedUidRanges;
9550 }
9551
9552 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009553 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009554 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009555
Junyu Lai35665cc2022-12-19 17:37:48 +08009556 ensureRunningOnConnectivityServiceThread();
9557 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9558 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9559 .getUserHandles(true /* excludeDying */);
9560 if (users.isEmpty()) {
9561 throw new IllegalStateException("No user is available");
9562 }
9563
9564 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9565 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9566 for (final UserHandle user : users) {
9567 final ArraySet<UidRange> restrictedUidRanges =
9568 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9569 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9570 UidRange.createForUser(user), restrictedUidRanges));
9571 }
9572
9573 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9574 configs.add(new NativeUidRangeConfig(
9575 nai.network.netId, rangesParcel, 0 /* subPriority */));
9576 }
9577
9578 // The netd API replaces the previous configs with the current configs.
9579 // Thus, for network disconnection or preference removal, no need to
9580 // unset previous config. Instead, collecting all currently needed
9581 // configs and issue to netd.
9582 try {
9583 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9584 } catch (ServiceSpecificException e) {
9585 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009586 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009587 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009588 // Netd died. This will cause a runtime restart anyway.
9589 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009590 }
9591 }
9592
James Mattisd31bdfa2020-12-23 16:37:26 -08009593 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9594 try {
9595 if (null != newDefaultNetwork) {
9596 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9597 } else {
9598 mNetd.networkClearDefault();
9599 }
9600 } catch (RemoteException | ServiceSpecificException e) {
9601 loge("Exception setting default network :" + e);
9602 }
9603 }
9604
Chalard Jean05cbe972019-12-09 11:50:38 +09009605 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009606 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009607 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009608 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009609 processNewlySatisfiedListenRequests(nai);
9610 }
9611
9612 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009613 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9614 if (nri.isMultilayerRequest()) {
9615 continue;
9616 }
9617 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009618 if (!nr.isListen()) continue;
9619 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009620 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009621 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9622 }
9623 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009624 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009625
Chalard Jeancd397a22019-11-22 22:33:33 +09009626 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009627 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9628 if (nri.isMultilayerRequest()) {
9629 continue;
9630 }
9631 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009632 if (!nr.isListen()) continue;
9633 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9634 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009635 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009636 }
9637 }
9638 }
9639
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009640 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009641 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009642 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009643 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009644 @Nullable public final NetworkRequest mOldNetworkRequest;
9645 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009646 @Nullable public final NetworkAgentInfo mOldNetwork;
9647 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009648 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009649 @Nullable final NetworkRequest oldNetworkRequest,
9650 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009651 @Nullable final NetworkAgentInfo oldNetwork,
9652 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009653 mNetworkRequestInfo = networkRequestInfo;
9654 mOldNetworkRequest = oldNetworkRequest;
9655 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009656 mOldNetwork = oldNetwork;
9657 mNewNetwork = newNetwork;
9658 }
Chalard Jean49707572019-12-10 21:07:02 +09009659
9660 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009661 final NetworkRequest requestToShow = null != mNewNetworkRequest
9662 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9663 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009664 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9665 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009666 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009667 }
9668
Chalard Jean46a62372019-12-10 21:25:24 +09009669 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009670
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009671 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009672 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009673 }
9674
9675 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009676 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009677 // The code is never supposed to add two reassignments of the same request. Make
9678 // sure this stays true, but without imposing this expensive check on all
9679 // reassignments on all user devices.
9680 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009681 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009682 throw new IllegalStateException("Trying to reassign ["
9683 + reassignment + "] but already have ["
9684 + existing + "]");
9685 }
9686 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009687 }
Chalard Jean46a62372019-12-10 21:25:24 +09009688 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009689 }
9690
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009691 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009692 // the passed request.
9693 @Nullable
9694 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009695 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009696 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009697 }
9698 return null;
9699 }
Chalard Jean49707572019-12-10 21:07:02 +09009700
9701 public String toString() {
9702 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9703 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009704 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009705 for (final RequestReassignment rr : getRequestReassignments()) {
9706 sj.add(rr.toString());
9707 }
9708 return sj.toString();
9709 }
9710
9711 public String debugString() {
9712 final StringBuilder sb = new StringBuilder();
9713 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009714 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009715 for (final RequestReassignment rr : getRequestReassignments()) {
9716 sb.append("\n ").append(rr);
9717 }
9718 return sb.append("\n").toString();
9719 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009720 }
9721
Chalard Jean24344d72019-12-04 13:32:31 +09009722 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009723 @Nullable final NetworkRequest previousRequest,
9724 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009725 @Nullable final NetworkAgentInfo previousSatisfier,
9726 @Nullable final NetworkAgentInfo newSatisfier,
9727 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009728 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009729 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009730 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009731 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009732 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009733 }
James Mattisa076c532020-12-02 14:12:41 -08009734 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009735 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009736 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009737 // If this network switch can't be supported gracefully, the request is not
9738 // lingered. This allows letting go of the network sooner to reclaim some
9739 // performance on the new network, since the radio can't do both at the same
9740 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009741 //
9742 // Also don't linger the request if the old network has been destroyed.
9743 // A destroyed network does not provide actual network connectivity, so
9744 // lingering it is not useful. In particular this ensures that a destroyed
9745 // network is outscored by its replacement,
9746 // then it is torn down immediately instead of being lingered, and any apps that
9747 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009748 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9749 }
Chalard Jean24344d72019-12-04 13:32:31 +09009750 } else {
9751 if (VDBG || DDBG) log(" accepting network in place of null");
9752 }
junyulai0ac374f2020-12-14 18:41:52 +08009753
9754 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9755 // and immediately satisfies a request then remove the timer. This will happen for
9756 // all networks except in the case of an underlying network for a VCN.
9757 if (newSatisfier.isNascent()) {
9758 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009759 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009760 }
9761
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009762 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009763 newSatisfier.unlingerRequest(newRequest.requestId);
9764 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009765 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009766 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009767 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009768 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009769 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009770 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009771 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009772 }
James Mattisa076c532020-12-02 14:12:41 -08009773 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009774 }
James Mattisa076c532020-12-02 14:12:41 -08009775 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009776 }
9777
James Mattisa076c532020-12-02 14:12:41 -08009778 /**
9779 * This function is triggered when something can affect what network should satisfy what
9780 * request, and it computes the network reassignment from the passed collection of requests to
9781 * network match to the one that the system should now have. That data is encoded in an
9782 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9783 * satisfier.
9784 *
9785 * After the reassignment is computed, it is applied to the state objects.
9786 *
9787 * @param networkRequests the nri objects to evaluate for possible network reassignment
9788 * @return NetworkReassignment listing of proposed network assignment changes
9789 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009790 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009791 private NetworkReassignment computeNetworkReassignment(
9792 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009793 final NetworkReassignment changes = new NetworkReassignment();
9794
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009795 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009796 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009797 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009798 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009799 }
Chalard Jean857a1712019-12-10 21:08:07 +09009800
James Mattisa076c532020-12-02 14:12:41 -08009801 for (final NetworkRequestInfo nri : networkRequests) {
9802 // Non-multilayer listen requests can be ignored.
9803 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9804 continue;
9805 }
9806 NetworkAgentInfo bestNetwork = null;
9807 NetworkRequest bestRequest = null;
9808 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009809 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009810 // Stop evaluating as the highest possible priority request is satisfied.
9811 if (null != bestNetwork) {
9812 bestRequest = req;
9813 break;
9814 }
9815 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009816 if (null == bestNetwork && isDefaultBlocked(nri)) {
9817 // Remove default networking if disallowed for managed default requests.
9818 bestNetwork = mNoServiceNetwork;
9819 }
9820 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009821 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009822 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009823 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009824 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009825 }
9826 return changes;
9827 }
9828
James Mattisa076c532020-12-02 14:12:41 -08009829 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9830 return new HashSet<>(mNetworkRequests.values());
9831 }
9832
Paul Jensenc88b39b2015-06-16 14:27:36 -04009833 /**
James Mattisa076c532020-12-02 14:12:41 -08009834 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009835 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009836 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009837 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009838 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9839 }
9840
9841 /**
9842 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9843 * being disconnected.
9844 */
9845 private void rematchNetworksAndRequests(
9846 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9847 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009848 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009849 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009850 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009851 final long computed = SystemClock.elapsedRealtime();
9852 applyNetworkReassignment(changes, start);
9853 final long applied = SystemClock.elapsedRealtime();
9854 issueNetworkNeeds();
9855 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009856 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009857 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9858 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009859 log(changes.debugString());
9860 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009861 // Shorter form, only one line of log
9862 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9863 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009864 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009865 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009866
Chalard Jeand7f762d2019-12-10 19:01:29 +09009867 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009868 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009869 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009870
9871 // Since most of the time there are only 0 or 1 background networks, it would probably
9872 // be more efficient to just use an ArrayList here. TODO : measure performance
9873 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9874 for (final NetworkAgentInfo nai : nais) {
9875 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9876 }
9877
Chalard Jeand7f762d2019-12-10 19:01:29 +09009878 // First, update the lists of satisfied requests in the network agents. This is necessary
9879 // because some code later depends on this state to be correct, most prominently computing
9880 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009881 for (final NetworkReassignment.RequestReassignment event :
9882 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009883 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9884 event.mOldNetworkRequest, event.mNewNetworkRequest,
9885 event.mOldNetwork, event.mNewNetwork,
9886 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009887 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009888
James Mattise3ef1912020-12-20 11:09:58 -08009889 // Process default network changes if applicable.
9890 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009891
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009892 // Notify requested networks are available after the default net is switched, but
9893 // before LegacyTypeTracker sends legacy broadcasts
9894 for (final NetworkReassignment.RequestReassignment event :
9895 changes.getRequestReassignments()) {
9896 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009897 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009898 } else {
James Mattisa076c532020-12-02 14:12:41 -08009899 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009900 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009901 }
9902 }
9903
junyulai0ac374f2020-12-14 18:41:52 +08009904 // Update the inactivity state before processing listen callbacks, because the background
9905 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009906 // just yet though, because they have to be sent after the listens are processed to keep
9907 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009908 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009909 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009910 // Rematching may have altered the inactivity state of some networks, so update all
9911 // inactivity timers. updateInactivityState reads the state from the network agent
9912 // and does nothing if the state has not changed : the source of truth is controlled
9913 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9914 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009915 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009916 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009917 }
9918 }
9919
Chalard Jeanb10ab412019-12-11 14:12:30 +09009920 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009921 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009922 // Process listen requests and update capabilities if the background state has
9923 // changed for this network. For consistency with previous behavior, send onLost
9924 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009925 processNewlyLostListenRequests(nai);
9926 if (oldBackground != nai.isBackgroundNetwork()) {
9927 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009928 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009929 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009930 }
9931
junyulai0ac374f2020-12-14 18:41:52 +08009932 for (final NetworkAgentInfo nai : inactiveNetworks) {
9933 // For nascent networks, if connecting with no foreground request, skip broadcasting
9934 // LOSING for backward compatibility. This is typical when mobile data connected while
9935 // wifi connected with mobile data always-on enabled.
9936 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009937 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009938 }
9939
James Mattise3ef1912020-12-20 11:09:58 -08009940 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009941
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009942 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +00009943 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009944 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009945 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009946 // This network has active linger timers and no requests, but is not
9947 // lingering. Linger it.
9948 //
9949 // One way (the only way?) this can happen if this network is unvalidated
9950 // and became unneeded due to another network improving its score to the
9951 // point where this network will no longer be able to satisfy any requests
9952 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009953 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009954 notifyNetworkLosing(nai, now);
9955 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009956 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009957 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009958 teardownUnneededNetwork(nai);
9959 }
9960 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009961 }
9962 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009963
Chalard Jean62edfd82019-12-02 18:39:29 +09009964 /**
9965 * Apply a change in background state resulting from rematching networks with requests.
9966 *
9967 * During rematch, a network may change background states by starting to satisfy or stopping
9968 * to satisfy a foreground request. Listens don't count for this. When a network changes
9969 * background states, its capabilities need to be updated and callbacks fired for the
9970 * capability change.
9971 *
9972 * @param nai The network that changed background states
9973 */
9974 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9975 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9976 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9977 updateNetworkPermissions(nai, newNc);
9978 nai.getAndSetNetworkCapabilities(newNc);
9979 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9980 }
9981
Chalard Jeanf0344532019-11-19 19:23:38 +09009982 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009983 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009984 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009985 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9986 changes.getReassignment(mDefaultRequest);
9987 final NetworkAgentInfo oldDefaultNetwork =
9988 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9989 final NetworkAgentInfo newDefaultNetwork =
9990 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009991
Chalard Jean5b409c72021-02-04 13:12:59 +09009992 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009993 // Maintain the illusion : since the legacy API only understands one network at a time,
9994 // if the default network changed, apps should see a disconnected broadcast for the
9995 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009996 if (oldDefaultNetwork != null) {
9997 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9998 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009999 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010000 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010001 // The new default network can be newly null if and only if the old default
10002 // network doesn't satisfy the default request any more because it lost a
10003 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010004 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010005 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010006 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010007 }
10008 }
10009
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010010 // Now that all the callbacks have been sent, send the legacy network broadcasts
10011 // as needed. This is necessary so that legacy requests correctly bind dns
10012 // requests to this network. The legacy users are listening for this broadcast
10013 // and will generally do a dns request so they can ensureRouteToHost and if
10014 // they do that before the callbacks happen they'll use the default network.
10015 //
10016 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10017 // callbacks, but if apps can receive the broadcast before the callback, they still might
10018 // have an inconsistent view of networking.
10019 //
10020 // This *does* introduce a race where if the user uses the new api
10021 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10022 // they may get old info. Reverse this after the old startUsing api is removed.
10023 // This is on top of the multiple intent sequencing referenced in the todo above.
10024 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010025 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010026 addNetworkToLegacyTypeTracker(nai);
10027 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010028 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010029 }
10030
Chalard Jean0354d8c2021-01-12 10:58:56 +090010031 private void issueNetworkNeeds() {
10032 ensureRunningOnConnectivityServiceThread();
10033 for (final NetworkOfferInfo noi : mNetworkOffers) {
10034 issueNetworkNeeds(noi);
10035 }
10036 }
10037
10038 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10039 ensureRunningOnConnectivityServiceThread();
10040 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10041 informOffer(nri, noi.offer, mNetworkRanker);
10042 }
10043 }
10044
10045 /**
10046 * Inform a NetworkOffer about any new situation of a request.
10047 *
10048 * This function handles updates to offers. A number of events may happen that require
10049 * updating the registrant for this offer about the situation :
10050 * • The offer itself was updated. This may lead the offer to no longer being able
10051 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10052 * or conversely being strengthened enough to beat the satisfier (and therefore
10053 * start being needed)
10054 * • The network satisfying a request changed (including cases where the request
10055 * starts or stops being satisfied). The new network may be a stronger or weaker
10056 * match than the old one, possibly affecting whether the offer is needed.
10057 * • The network satisfying a request updated their score. This may lead the offer
10058 * to no longer be able to beat it if the current satisfier got better, or
10059 * conversely start being a good choice if the current satisfier got weaker.
10060 *
10061 * @param nri The request
10062 * @param offer The offer. This may be an updated offer.
10063 */
10064 private static void informOffer(@NonNull NetworkRequestInfo nri,
10065 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10066 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10067 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010068
10069 // Multi-layer requests have a currently active request, the one being satisfied.
10070 // Since the system will try to bring up a better network than is currently satisfying
10071 // the request, NetworkProviders need to be told the offers matching the requests *above*
10072 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10073 // not needed, and the offer is needed for the active request iff the offer can beat
10074 // the satisfier.
10075 // For non-multilayer requests, the logic above gracefully degenerates to only the
10076 // last case.
10077 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10078 // providers that the offer is needed for this request, until the active request is found.
10079 // In a second phase, deal with the currently active request. In a third phase, inform
10080 // the providers that offer is unneeded for the remaining requests.
10081
10082 // First phase : inform providers of all requests above the active request.
10083 int i;
10084 for (i = 0; nri.mRequests.size() > i; ++i) {
10085 final NetworkRequest request = nri.mRequests.get(i);
10086 if (activeRequest == request) break; // Found the active request : go to phase 2
10087 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10088 // Since this request is higher-priority than the one currently satisfied, if the
10089 // offer can satisfy it, the provider should try and bring up the network for sure ;
10090 // no need to even ask the ranker – an offer that can satisfy is always better than
10091 // no network. Hence tell the provider so unless it already knew.
10092 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10093 offer.onNetworkNeeded(request);
10094 }
10095 }
10096
10097 // Second phase : deal with the active request (if any)
10098 if (null != activeRequest && activeRequest.isRequest()) {
10099 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010100 // If an offer can satisfy the request, it is considered needed if it is currently
10101 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010102 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010103 && satisfier.factorySerialNumber == offer.providerId
10104 && activeRequest.canBeSatisfiedBy(offer.caps);
10105 final boolean newNeeded = currentlyServing
10106 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010107 if (newNeeded != oldNeeded) {
10108 if (newNeeded) {
10109 offer.onNetworkNeeded(activeRequest);
10110 } else {
10111 // The offer used to be able to beat the satisfier. Now it can't.
10112 offer.onNetworkUnneeded(activeRequest);
10113 }
10114 }
10115 }
10116
10117 // Third phase : inform the providers that the offer isn't needed for any request
10118 // below the active one.
10119 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10120 final NetworkRequest request = nri.mRequests.get(i);
10121 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10122 // Since this request is lower-priority than the one currently satisfied, if the
10123 // offer can satisfy it, the provider should not try and bring up the network.
10124 // Hence tell the provider so unless it already knew.
10125 if (offer.neededFor(request)) {
10126 offer.onNetworkUnneeded(request);
10127 }
10128 }
10129 }
10130
Chalard Jean61c79252019-11-07 23:07:32 +090010131 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10132 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10133 NetworkRequest nr = nai.requestAt(i);
10134 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10135 // legacy type tracker filters out repeat adds
10136 mLegacyTypeTracker.add(nr.legacyType, nai);
10137 }
10138 }
10139
10140 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010141 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010142 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10143 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10144 if (nai.isVPN()) {
10145 mLegacyTypeTracker.add(TYPE_VPN, nai);
10146 }
10147 }
10148
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010149 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010150 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010151 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010152 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010153 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010154 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010155
Chalard Jean254bd162022-08-25 13:04:51 +090010156 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010157 // Don't repeat publish.
10158 if (newInetCondition == mDefaultInetConditionPublished) return;
10159
10160 mDefaultInetConditionPublished = newInetCondition;
10161 sendInetConditionBroadcast(nai.networkInfo);
10162 }
10163
Chalard Jeand61375d2020-01-14 22:46:36 +090010164 @NonNull
10165 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10166 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010167 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010168 final boolean suspended =
10169 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10170 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10171 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10172 // state. This is because the network could have been suspended before connecting,
10173 // or it could be disconnecting while being suspended, and in both these cases
10174 // the state should not be overridden. Note that the only detailed state that
10175 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10176 // worry about multiple different substates of CONNECTED.
10177 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10178 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010179 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10180 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10181 // network agent is created, then goes to suspended, then goes out of suspended without
10182 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010183 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010184 ? NetworkInfo.DetailedState.CONNECTED
10185 : NetworkInfo.DetailedState.CONNECTING,
10186 info.getReason(),
10187 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010188 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010189 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010190 return newInfo;
10191 }
10192
10193 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10194 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10195
Erik Kline99f301b2017-02-15 19:59:17 +090010196 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010197 NetworkInfo oldInfo = null;
10198 synchronized (networkAgent) {
10199 oldInfo = networkAgent.networkInfo;
10200 networkAgent.networkInfo = newInfo;
10201 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010202
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010203 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010204 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10205 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010206 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010207
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010208 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010209 // A network that has just connected has zero requests and is thus a foreground network.
10210 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10211
Luke Huangfdd11f82019-04-09 18:41:49 +080010212 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010213
10214 networkAgent.setCreated();
10215
10216 // If the network is created immediately on register, then apply the LinkProperties now.
10217 // Otherwise, this is done further down when the network goes into connected state.
10218 // Applying the LinkProperties means that the network is ready to carry traffic -
10219 // interfaces and routing rules have been added, DNS servers programmed, etc.
10220 // For VPNs, this must be done before the capabilities are updated, because as soon as
10221 // that happens, UIDs are routed to the network.
10222 if (shouldCreateNetworksImmediately()) {
10223 applyInitialLinkProperties(networkAgent);
10224 }
10225
10226 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10227 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010228 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010229 // Initialize the network's capabilities to their starting values according to the
10230 // underlying networks. This ensures that the capabilities are correct before
10231 // anything happens to the network.
10232 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010233 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010234 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010235 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010236 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010237 }
10238
Chalard Jean254bd162022-08-25 13:04:51 +090010239 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10240 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010241
lucaslin45e639b2019-04-03 17:09:28 +080010242 // NetworkCapabilities need to be set before sending the private DNS config to
10243 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010244 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10245
Erik Kline9a62f012018-03-21 07:18:33 -070010246 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010247 if (!shouldCreateNetworksImmediately()) {
10248 applyInitialLinkProperties(networkAgent);
10249 } else {
10250 // The network was created when the agent registered, and the LinkProperties are
10251 // already up-to-date. However, updateLinkProperties also makes some changes only
10252 // when the network connects. Apply those changes here. On T and below these are
10253 // handled by the applyInitialLinkProperties call just above.
10254 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10255 // If something depends on both LinkProperties and connected state, it should be in
10256 // this method as well.
10257 networkAgent.clatd.update();
10258 updateProxy(networkAgent.linkProperties, null);
10259 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010260
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010261 // If a rate limit has been configured and is applicable to this network (network
10262 // provides internet connectivity), apply it. The tc police filter cannot be attached
10263 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
10264 // updateInterfaces -> INetd#networkAddInterface.
10265 // Note: in case of a system server crash, the NetworkController constructor in netd
10266 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10267 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10268 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10269 mIngressRateLimit);
10270 }
10271
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010272 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10273 // command must be sent after updating LinkProperties to maximize chances of
10274 // NetworkMonitor seeing the correct LinkProperties when starting.
10275 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010276 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010277 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010278 }
Chalard Jeand4900722022-02-06 12:25:38 +090010279 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10280 params.networkAgentConfig = networkAgent.networkAgentConfig;
10281 params.networkCapabilities = networkAgent.networkCapabilities;
10282 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10283 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010284 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10285 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10286 // call that would cause a Log.wtf to be emitted from the system_server process, and
10287 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10288 // process to check the interface version, just use an SDK check. NetworkStack will
10289 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010290 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010291 networkAgent.networkMonitor().notifyNetworkConnected(params);
10292 } else {
10293 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10294 params.networkCapabilities);
10295 }
Chalard Jean0f141332023-06-05 19:26:17 +090010296 final long evaluationDelay;
10297 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10298 // If the network is anything other than pure wifi, use the default timeout.
10299 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10300 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10301 // If the network is explicitly selected, use the default timeout because it's
10302 // shorter and the user is likely staring at the screen expecting it to validate
10303 // right away.
10304 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10305 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10306 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10307 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10308 } else {
10309 // It's wifi, automatically connected, and bad wifi is preferred : use the
10310 // longer timeout to avoid the device switching to captive portals with bad
10311 // signal or very slow response.
10312 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10313 }
10314 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010315
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010316 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10317 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10318 // capabilities, so it only needs to be done once on initial connect, not every time the
10319 // network's capabilities change. Note that we do this before rematching the network,
10320 // so we could decide to tear it down immediately afterwards. That's fine though - on
10321 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10322 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010323 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010324
junyulai0ac374f2020-12-14 18:41:52 +080010325 // Before first rematching networks, put an inactivity timer without any request, this
10326 // allows {@code updateInactivityState} to update the state accordingly and prevent
10327 // tearing down for any {@code unneeded} evaluation in this period.
10328 // Note that the timer will not be rescheduled since the expiry time is
10329 // fixed after connection regardless of the network satisfying other requests or not.
10330 // But it will be removed as soon as the network satisfies a request for the first time.
10331 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10332 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010333 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010334
Paul Jensen05e85ee2014-09-11 11:00:39 -040010335 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010336 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010337
10338 // This has to happen after matching the requests, because callbacks are just requests.
10339 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010340 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010341 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010342 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010343 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010344 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010345 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010346 if (networkAgent.isVPN()) {
10347 // As the active or bound network changes for apps, broadcast the default proxy, as
10348 // apps may need to update their proxy data. This is called after disconnecting from
10349 // VPN to make sure we do not broadcast the old proxy data.
10350 // TODO(b/122649188): send the broadcast only to VPN users.
10351 mProxyTracker.sendProxyBroadcast();
10352 }
Chalard Jean254bd162022-08-25 13:04:51 +090010353 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10354 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010355 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010356 }
10357 }
10358
Chalard Jean28018572020-12-21 18:36:52 +090010359 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010360 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10361 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010362 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010363 }
10364
Erik Kline99f301b2017-02-15 19:59:17 +090010365 // Notify only this one new request of the current state. Transfer all the
10366 // current state by calling NetworkCapabilities and LinkProperties callbacks
10367 // so that callers can be guaranteed to have as close to atomicity in state
10368 // transfer as can be supported by this current API.
10369 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010370 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010371 if (nri.mPendingIntent != null) {
10372 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10373 // Attempt no subsequent state pushes where intents are involved.
10374 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010375 }
Erik Kline99f301b2017-02-15 19:59:17 +090010376
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010377 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010378 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010379 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10380 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10381 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010382 }
10383
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010384 // Notify the requests on this NAI that the network is now lingered.
10385 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010386 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010387 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10388 }
10389
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010390 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10391 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10392 return vpnBlocked
10393 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10394 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10395 }
10396
10397 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10398 if (blockedReasons == BLOCKED_REASON_NONE) {
10399 mUidBlockedReasons.delete(uid);
10400 } else {
10401 mUidBlockedReasons.put(uid, blockedReasons);
10402 }
10403 }
10404
junyulaif2c67e42018-08-07 19:50:45 +080010405 /**
10406 * Notify of the blocked state apps with a registered callback matching a given NAI.
10407 *
10408 * Unlike other callbacks, blocked status is different between each individual uid. So for
10409 * any given nai, all requests need to be considered according to the uid who filed it.
10410 *
10411 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010412 * @param oldMetered True if the previous network capabilities were metered.
10413 * @param newMetered True if the current network capabilities are metered.
10414 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10415 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010416 */
10417 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010418 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10419 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010420
10421 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10422 NetworkRequest nr = nai.requestAt(i);
10423 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010424
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010425 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10426 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10427 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010428 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010429 : oldVpnBlocked;
10430
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010431 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10432 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10433 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010434 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010435 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010436 }
10437 }
10438 }
10439
10440 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010441 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010442 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010443 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010444 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010445 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010446 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010447 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010448 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010449
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010450 final int oldBlockedState = getBlockedState(
10451 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10452 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10453 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010454 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010455 }
junyulaif2c67e42018-08-07 19:50:45 +080010456 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10457 NetworkRequest nr = nai.requestAt(i);
10458 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010459 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010460 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10461 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010462 }
10463 }
10464 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010465 }
10466
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010467 @VisibleForTesting
10468 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010469 // The NetworkInfo we actually send out has no bearing on the real
10470 // state of affairs. For example, if the default connection is mobile,
10471 // and a request for HIPRI has just gone away, we need to pretend that
10472 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10473 // the state to DISCONNECTED, even though the network is of type MOBILE
10474 // and is still connected.
10475 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10476 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010477 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010478 if (state != DetailedState.DISCONNECTED) {
10479 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010480 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010481 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010482 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010483 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10484 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10485 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10486 if (info.isFailover()) {
10487 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10488 nai.networkInfo.setFailover(false);
10489 }
10490 if (info.getReason() != null) {
10491 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10492 }
10493 if (info.getExtraInfo() != null) {
10494 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10495 }
10496 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010497 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010498 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010499 if (newDefaultAgent != null) {
10500 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10501 newDefaultAgent.networkInfo);
10502 } else {
10503 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10504 }
10505 }
10506 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10507 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010508 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010509 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010510 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010511 }
10512 }
10513 }
10514
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010515 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010516 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010517 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010518 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010519 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010520 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10521 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010522 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10523 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010524 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010525 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010526 } else {
10527 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10528 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010529 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010530 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010531
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010532 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10533 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10534 }
10535
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010536 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010537 * Returns the list of all interfaces that could be used by network traffic that does not
10538 * explicitly specify a network. This includes the default network, but also all VPNs that are
10539 * currently connected.
10540 *
10541 * Must be called on the handler thread.
10542 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010543 @NonNull
10544 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010545 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010546 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010547 final Set<Integer> activeNetIds = new ArraySet<>();
10548 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10549 if (nri.isBeingSatisfied()) {
10550 activeNetIds.add(nri.getSatisfier().network().netId);
10551 }
10552 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010553 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010554 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010555 defaultNetworks.add(nai.network);
10556 }
10557 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010558 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010559 }
10560
10561 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010562 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10563 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010564 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010565 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010566 ensureRunningOnConnectivityServiceThread();
10567 String activeIface = null;
10568 LinkProperties activeLinkProperties = getActiveLinkProperties();
10569 if (activeLinkProperties != null) {
10570 activeIface = activeLinkProperties.getInterfaceName();
10571 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010572
junyulai2050bed2021-01-23 09:46:34 +080010573 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010574 try {
junyulaide41fc22021-01-22 22:46:01 +080010575 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010576 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010577 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10578 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010579 } catch (Exception ignored) {
10580 }
10581 }
10582
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010583 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010584 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010585 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010586 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010587 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010588
10589 if (!TextUtils.isEmpty(settingUrl)) {
10590 return settingUrl;
10591 }
10592
10593 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010594 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010595 if (!TextUtils.isEmpty(settingUrl)) {
10596 return settingUrl;
10597 }
10598
10599 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010600 }
10601
10602 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010603 public void startNattKeepalive(Network network, int intervalSeconds,
10604 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010605 enforceKeepalivePermission();
10606 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010607 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010608 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10609 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010610 // false and set the underpinned network to null because there is no way and no
10611 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10612 // deprecated method.
10613 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010614 }
10615
10616 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010617 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010618 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010619 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010620 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010621 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010622 mKeepaliveTracker.startNattKeepalive(
10623 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010624 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10625 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010626 } finally {
10627 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10628 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010629 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10630 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010631 }
10632 }
junyulaid05a1922019-01-15 11:32:44 +080010633 }
10634
10635 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010636 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010637 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010638 try {
10639 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010640 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010641 mKeepaliveTracker.startTcpKeepalive(
10642 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10643 } finally {
10644 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10645 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010646 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10647 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010648 }
10649 }
junyulai0835a1e2019-01-08 20:04:33 +080010650 }
10651
10652 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010653 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010654 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010655 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10656 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010657 }
10658
10659 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010660 public int[] getSupportedKeepalives() {
10661 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10662 // Backwards compatibility with CTS 13
10663 android.Manifest.permission.QUERY_ALL_PACKAGES);
10664
10665 return BinderUtils.withCleanCallingIdentity(() ->
10666 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10667 }
10668
10669 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010670 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010671 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010672
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010673 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010674 final long token = Binder.clearCallingIdentity();
10675 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010676 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10677 UserHandle.getUserHandleForUid(uid))) {
10678 return;
10679 }
10680
Heemin Seogdb8489d2019-06-12 09:21:44 -070010681 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10682 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010683
10684 // Turn airplane mode off
10685 setAirplaneMode(false);
10686
10687 // restore private DNS settings to default mode (opportunistic)
10688 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10689 UserHandle.getUserHandleForUid(uid))) {
10690 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10691 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10692 }
10693
10694 Settings.Global.putString(mContext.getContentResolver(),
10695 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010696 } finally {
10697 Binder.restoreCallingIdentity(token);
10698 }
Stuart Scottd5463642015-04-02 18:00:02 -070010699 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010700
Ricky Wai7097cc92018-01-23 04:09:45 +000010701 @Override
10702 public byte[] getNetworkWatchlistConfigHash() {
10703 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10704 if (nwm == null) {
10705 loge("Unable to get NetworkWatchlistManager");
10706 return null;
10707 }
10708 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10709 return nwm.getWatchlistConfigHash();
10710 }
10711
Hugo Benichibe0c7652016-05-31 16:28:06 +090010712 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010713 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010714 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010715 }
Hugo Benichif4210292017-04-21 15:07:12 +090010716
10717 private static boolean toBool(int encodedBoolean) {
10718 return encodedBoolean != 0; // Only 0 means false.
10719 }
10720
10721 private static int encodeBool(boolean b) {
10722 return b ? 1 : 0;
10723 }
mswest4632928412018-03-12 10:34:34 -070010724
10725 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010726 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10727 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10728 @NonNull String[] args) {
10729 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10730 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010731 }
10732
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010733 private Boolean parseBooleanArgument(final String arg) {
10734 if ("true".equals(arg)) {
10735 return true;
10736 } else if ("false".equals(arg)) {
10737 return false;
10738 } else {
10739 return null;
10740 }
10741 }
10742
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010743 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010744 @Override
10745 public int onCommand(String cmd) {
10746 if (cmd == null) {
10747 return handleDefaultCommands(cmd);
10748 }
10749 final PrintWriter pw = getOutPrintWriter();
10750 try {
10751 switch (cmd) {
10752 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010753 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10754 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010755 final String action = getNextArg();
10756 if ("enable".equals(action)) {
10757 setAirplaneMode(true);
10758 return 0;
10759 } else if ("disable".equals(action)) {
10760 setAirplaneMode(false);
10761 return 0;
10762 } else if (action == null) {
10763 final ContentResolver cr = mContext.getContentResolver();
10764 final int enabled = Settings.Global.getInt(cr,
10765 Settings.Global.AIRPLANE_MODE_ON);
10766 pw.println(enabled == 0 ? "disabled" : "enabled");
10767 return 0;
10768 } else {
10769 onHelp();
10770 return -1;
10771 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010772 case "set-chain3-enabled": {
10773 final Boolean enabled = parseBooleanArgument(getNextArg());
10774 if (null == enabled) {
10775 onHelp();
10776 return -1;
10777 }
10778 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
10779 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10780 enabled);
10781 return 0;
10782 }
10783 case "get-chain3-enabled": {
10784 final boolean chainEnabled = getFirewallChainEnabled(
10785 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
10786 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
10787 return 0;
10788 }
10789 case "set-package-networking-enabled": {
10790 final Boolean enabled = parseBooleanArgument(getNextArg());
10791 final String packageName = getNextArg();
10792 if (null == enabled || null == packageName) {
10793 onHelp();
10794 return -1;
10795 }
10796 // Throws NameNotFound if the package doesn't exist.
10797 final int appId = setPackageFirewallRule(
10798 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10799 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
10800 final String msg = (enabled ? "Enabled" : "Disabled")
10801 + " networking for " + packageName + ", appId " + appId;
10802 Log.i(TAG, msg);
10803 pw.println(msg);
10804 return 0;
10805 }
10806 case "get-package-networking-enabled": {
10807 final String packageName = getNextArg();
10808 final int rule = getPackageFirewallRule(
10809 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
10810 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
10811 pw.println(packageName + ":" + "allow");
10812 } else if (FIREWALL_RULE_DENY == rule) {
10813 pw.println(packageName + ":" + "deny");
10814 } else {
10815 throw new IllegalStateException("Unknown rule " + rule + " for package "
10816 + packageName);
10817 }
10818 return 0;
10819 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010820 case "reevaluate":
10821 // Usage : adb shell cmd connectivity reevaluate <netId>
10822 // If netId is omitted, then reevaluate the default network
10823 final String netId = getNextArg();
10824 final NetworkAgentInfo nai;
10825 if (null == netId) {
10826 // Note that the command is running on the wrong thread to call this,
10827 // so this could in principle return stale data. But it can't crash.
10828 nai = getDefaultNetwork();
10829 } else {
10830 // If netId can't be parsed, this throws NumberFormatException, which
10831 // is passed back to adb who prints it.
10832 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10833 }
10834 if (null == nai) {
10835 pw.println("Unknown network (net ID not found or no default network)");
10836 return 0;
10837 }
10838 Log.d(TAG, "Reevaluating network " + nai.network);
10839 reportNetworkConnectivity(nai.network, !nai.isValidated());
10840 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080010841 case "bpf-get-cgroup-program-id": {
10842 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
10843 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
10844 // for more detail.
10845 // If type can't be parsed, this throws NumberFormatException, which
10846 // is passed back to adb who prints it.
10847 final int type = Integer.parseInt(getNextArg());
10848 final int ret = BpfUtils.getProgramId(type, BpfUtils.CGROUP_PATH);
10849 pw.println(ret);
10850 return 0;
10851 }
mswest4632928412018-03-12 10:34:34 -070010852 default:
10853 return handleDefaultCommands(cmd);
10854 }
10855 } catch (Exception e) {
10856 pw.println(e);
10857 }
10858 return -1;
10859 }
10860
10861 @Override
10862 public void onHelp() {
10863 PrintWriter pw = getOutPrintWriter();
10864 pw.println("Connectivity service commands:");
10865 pw.println(" help");
10866 pw.println(" Print this help text.");
10867 pw.println(" airplane-mode [enable|disable]");
10868 pw.println(" Turn airplane mode on or off.");
10869 pw.println(" airplane-mode");
10870 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010871 pw.println(" set-chain3-enabled [true|false]");
10872 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
10873 pw.println(" get-chain3-enabled");
10874 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
10875 pw.println(" set-package-networking-enabled [true|false] [package name]");
10876 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
10877 + " no effect if the chain is disabled.");
10878 pw.println(" get-package-networking-enabled [package name]");
10879 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070010880 }
10881 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010882
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010883 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010884 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10885 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10886 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010887 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010888 }
10889
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010890 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10891 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010892 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10893 final TransportInfo newInfo = nc.getTransportInfo();
10894 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10895 return;
10896 }
10897 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010898 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010899 }
10900 }
10901
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010902 /**
10903 * @param connectionInfo the connection to resolve.
10904 * @return {@code uid} if the connection is found and the app has permission to observe it
10905 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10906 * connection is not found.
10907 */
10908 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010909 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10910 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10911 }
10912
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010913 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010914 connectionInfo.local, connectionInfo.remote);
10915
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010916 if (uid == INVALID_UID) return uid; // Not found.
10917
10918 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10919 // VPN, if any, that applies to the UID that owns the connection.
10920 if (checkNetworkStackPermission()) return uid;
10921
10922 final NetworkAgentInfo vpn = getVpnForUid(uid);
10923 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010924 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010925 return INVALID_UID;
10926 }
10927
10928 return uid;
10929 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010930
Benedict Wong493e04b2018-11-09 14:45:34 -080010931 /**
10932 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10933 *
10934 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10935 */
10936 @Override
10937 public IBinder startOrGetTestNetworkService() {
10938 synchronized (mTNSLock) {
10939 TestNetworkService.enforceTestNetworkPermissions(mContext);
10940
10941 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010942 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010943 }
10944
10945 return mTNS;
10946 }
10947 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010948
Cody Kesting73708bf2019-12-18 10:57:50 -080010949 /**
10950 * Handler used for managing all Connectivity Diagnostics related functions.
10951 *
10952 * @see android.net.ConnectivityDiagnosticsManager
10953 *
10954 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10955 */
10956 @VisibleForTesting
10957 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010958 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10959
Cody Kesting73708bf2019-12-18 10:57:50 -080010960 /**
10961 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10962 * android.net.ConnectivityDiagnosticsManager}.
10963 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10964 * NetworkRequestInfo to be registered
10965 */
10966 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10967
10968 /**
10969 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10970 * android.net.ConnectivityDiagnosticsManager}.
10971 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10972 * arg1 = the uid of the caller
10973 */
10974 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10975
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010976 /**
10977 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010978 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010979 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10980 * NetworkMonitor.
10981 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010982 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010983 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010984
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010985 /**
10986 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10987 * been detected on the network.
10988 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10989 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10990 * arg2 = NetID.
10991 * data = PersistableBundle of extras passed from NetworkMonitor.
10992 */
10993 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10994
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010995 /**
10996 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10997 * the platform. This event will invoke {@link
10998 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10999 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011000 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011001 */
11002 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11003
Cody Kesting73708bf2019-12-18 10:57:50 -080011004 private ConnectivityDiagnosticsHandler(Looper looper) {
11005 super(looper);
11006 }
11007
11008 @Override
11009 public void handleMessage(Message msg) {
11010 switch (msg.what) {
11011 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11012 handleRegisterConnectivityDiagnosticsCallback(
11013 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11014 break;
11015 }
11016 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11017 handleUnregisterConnectivityDiagnosticsCallback(
11018 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11019 break;
11020 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011021 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011022 final ConnectivityReportEvent reportEvent =
11023 (ConnectivityReportEvent) msg.obj;
11024
Aaron Huang959d3642021-01-21 15:47:41 +080011025 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011026 break;
11027 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011028 case EVENT_DATA_STALL_SUSPECTED: {
11029 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011030 final Pair<Long, PersistableBundle> arg =
11031 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011032 if (nai == null) break;
11033
Aaron Huang959d3642021-01-21 15:47:41 +080011034 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011035 break;
11036 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011037 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011038 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011039 break;
11040 }
11041 default: {
11042 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11043 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011044 }
11045 }
11046 }
11047
11048 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11049 @VisibleForTesting
11050 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11051 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11052 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011053 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011054
11055 @VisibleForTesting
11056 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011057 @NonNull IConnectivityDiagnosticsCallback cb,
11058 @NonNull NetworkRequestInfo nri,
11059 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011060 mCb = cb;
11061 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011062 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011063 }
11064
11065 @Override
11066 public void binderDied() {
11067 log("ConnectivityDiagnosticsCallback IBinder died.");
11068 unregisterConnectivityDiagnosticsCallback(mCb);
11069 }
11070 }
11071
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011072 /**
11073 * Class used for sending information from {@link
11074 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11075 */
11076 private static class NetworkTestedResults {
11077 private final int mNetId;
11078 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011079 @Nullable private final String mRedirectUrl;
11080
11081 private NetworkTestedResults(
11082 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11083 mNetId = netId;
11084 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011085 mRedirectUrl = redirectUrl;
11086 }
11087 }
11088
11089 /**
11090 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11091 * ConnectivityDiagnosticsHandler}.
11092 */
11093 private static class ConnectivityReportEvent {
11094 private final long mTimestampMillis;
11095 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011096 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011097
Aaron Huang959d3642021-01-21 15:47:41 +080011098 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11099 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011100 mTimestampMillis = timestampMillis;
11101 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011102 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011103 }
11104 }
11105
Cody Kestingf1120be2020-08-03 18:01:40 -070011106 /**
11107 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11108 * ConnectivityDiagnosticsHandler}.
11109 */
11110 private static class ReportedNetworkConnectivityInfo {
11111 public final boolean hasConnectivity;
11112 public final boolean isNetworkRevalidating;
11113 public final int reporterUid;
11114 @NonNull public final NetworkAgentInfo nai;
11115
11116 private ReportedNetworkConnectivityInfo(
11117 boolean hasConnectivity,
11118 boolean isNetworkRevalidating,
11119 int reporterUid,
11120 @NonNull NetworkAgentInfo nai) {
11121 this.hasConnectivity = hasConnectivity;
11122 this.isNetworkRevalidating = isNetworkRevalidating;
11123 this.reporterUid = reporterUid;
11124 this.nai = nai;
11125 }
11126 }
11127
Cody Kesting73708bf2019-12-18 10:57:50 -080011128 private void handleRegisterConnectivityDiagnosticsCallback(
11129 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11130 ensureRunningOnConnectivityServiceThread();
11131
11132 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011133 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011134 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11135
James Mattis64b8b0f2020-11-24 17:40:49 -080011136 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11137 // confusing for these networks to change when an NRI is satisfied in another layer.
11138 if (nri.isMultilayerRequest()) {
11139 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11140 + "network requests.");
11141 }
11142
Cody Kesting73708bf2019-12-18 10:57:50 -080011143 // This means that the client registered the same callback multiple times. Do
11144 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011145 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011146 if (VDBG) log("Diagnostics callback is already registered");
11147
11148 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11149 // incremented when the NetworkRequestInfo is created as part of
11150 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011151 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011152 return;
11153 }
11154
Cody Kesting31f1ff62020-03-05 10:46:02 -080011155 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011156
11157 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011158 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011159 } catch (RemoteException e) {
11160 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011161 return;
11162 }
11163
11164 // Once registered, provide ConnectivityReports for matching Networks
11165 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11166 synchronized (mNetworkForNetId) {
11167 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11168 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011169 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11170 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011171 matchingNetworks.add(nai);
11172 }
11173 }
11174 }
11175 for (final NetworkAgentInfo nai : matchingNetworks) {
11176 final ConnectivityReport report = nai.getConnectivityReport();
11177 if (report == null) {
11178 continue;
11179 }
11180 if (!checkConnectivityDiagnosticsPermissions(
11181 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11182 continue;
11183 }
11184
11185 try {
11186 cb.onConnectivityReportAvailable(report);
11187 } catch (RemoteException e) {
11188 // Exception while sending the ConnectivityReport. Move on to the next network.
11189 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011190 }
11191 }
11192
11193 private void handleUnregisterConnectivityDiagnosticsCallback(
11194 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11195 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011196 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011197
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011198 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11199 mConnectivityDiagnosticsCallbacks.remove(iCb);
11200 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011201 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11202 return;
11203 }
11204
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011205 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011206
Cody Kesting70fa2b22020-12-02 12:16:56 -080011207 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11208 // (if the Binder died)
11209 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11210 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011211 return;
11212 }
11213
Cody Kesting46cb1672020-03-04 13:35:20 -080011214 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11215 // incremented when the NetworkRequestInfo is created as part of
11216 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011217 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011218
Cody Kesting31f1ff62020-03-05 10:46:02 -080011219 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011220 }
11221
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011222 private void handleNetworkTestedWithExtras(
11223 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11224 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011225 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011226 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011227 final ConnectivityReport report =
11228 new ConnectivityReport(
11229 reportEvent.mNai.network,
11230 reportEvent.mTimestampMillis,
11231 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011232 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011233 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011234 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011235
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011236 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011237 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011238 for (final IConnectivityDiagnosticsCallback cb : results) {
11239 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011240 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011241 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011242 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011243 }
11244 }
11245 }
11246
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011247 private void handleDataStallSuspected(
11248 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11249 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011250 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011251 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011252 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011253 new DataStallReport(
11254 nai.network,
11255 timestampMillis,
11256 detectionMethod,
11257 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011258 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011259 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011260 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011261 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011262 for (final IConnectivityDiagnosticsCallback cb : results) {
11263 try {
11264 cb.onDataStallSuspected(report);
11265 } catch (RemoteException ex) {
11266 loge("Error invoking onDataStallSuspected", ex);
11267 }
11268 }
11269 }
11270
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011271 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011272 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11273 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11274 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11275
11276 // If the Network is being re-validated as a result of this call to
11277 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11278 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011279 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011280 getMatchingPermissionedCallbacks(
11281 nai,
11282 reportedNetworkConnectivityInfo.isNetworkRevalidating
11283 ? Process.INVALID_UID
11284 : reportedNetworkConnectivityInfo.reporterUid);
11285
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011286 for (final IConnectivityDiagnosticsCallback cb : results) {
11287 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011288 cb.onNetworkConnectivityReported(
11289 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011290 } catch (RemoteException ex) {
11291 loge("Error invoking onNetworkConnectivityReported", ex);
11292 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011293
11294 // If the Network isn't re-validating, also provide the cached report. If there is no
11295 // cached report, the Network is still being validated and a report will be sent once
11296 // validation is complete. Note that networks which never undergo validation will still
11297 // have a cached ConnectivityReport with RESULT_SKIPPED.
11298 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11299 try {
11300 cb.onConnectivityReportAvailable(cachedReport);
11301 } catch (RemoteException ex) {
11302 loge("Error invoking onConnectivityReportAvailable", ex);
11303 }
11304 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011305 }
11306 }
11307
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011308 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011309 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11310 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011311 sanitized.setUids(null);
11312 sanitized.setAdministratorUids(new int[0]);
11313 sanitized.setOwnerUid(Process.INVALID_UID);
11314 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011315 }
11316
Cody Kestingf1120be2020-08-03 18:01:40 -070011317 /**
11318 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11319 *
11320 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11321 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011322 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011323 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011324 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011325 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011326 mConnectivityDiagnosticsCallbacks.entrySet()) {
11327 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11328 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011329
James Mattis64b8b0f2020-11-24 17:40:49 -080011330 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011331 if (!nai.satisfies(nri.mRequests.get(0))) {
11332 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011333 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011334
11335 // UID for this callback must either be:
11336 // - INVALID_UID (which sends callbacks to all UIDs), or
11337 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11338 // notified as a result)
11339 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11340 continue;
11341 }
11342
11343 if (!checkConnectivityDiagnosticsPermissions(
11344 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11345 continue;
11346 }
11347
11348 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011349 }
11350 return results;
11351 }
11352
Cody Kesting7474f672021-05-11 14:22:40 -070011353 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11354 @NonNull NetworkAgentInfo nai) {
11355 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11356 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11357 }
11358
Cody Kesting160ef392021-05-05 13:17:22 -070011359 private boolean hasLocationPermission(String packageName, int uid) {
11360 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11361 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11362 // call in a try-catch.
11363 try {
11364 if (!mLocationPermissionChecker.checkLocationPermission(
11365 packageName, null /* featureId */, uid, null /* message */)) {
11366 return false;
11367 }
11368 } catch (SecurityException e) {
11369 return false;
11370 }
11371
11372 return true;
11373 }
11374
11375 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11376 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011377 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011378 && virtual.networkCapabilities.getOwnerUid() == uid
11379 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11380 return true;
11381 }
11382 }
11383
11384 return false;
11385 }
11386
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011387 @VisibleForTesting
11388 boolean checkConnectivityDiagnosticsPermissions(
11389 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11390 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11391 return true;
11392 }
11393
Cody Kesting160ef392021-05-05 13:17:22 -070011394 // Administrator UIDs also contains the Owner UID
11395 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11396 if (!CollectionUtils.contains(administratorUids, callbackUid)
11397 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011398 return false;
11399 }
11400
Cody Kesting7474f672021-05-11 14:22:40 -070011401 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11402 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011403 }
11404
Cody Kestingd199a9d2019-12-17 12:55:28 -080011405 @Override
11406 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011407 @NonNull IConnectivityDiagnosticsCallback callback,
11408 @NonNull NetworkRequest request,
11409 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011410 Objects.requireNonNull(callback, "callback must not be null");
11411 Objects.requireNonNull(request, "request must not be null");
11412 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11413
Cody Kesting73708bf2019-12-18 10:57:50 -080011414 if (request.legacyType != TYPE_NONE) {
11415 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11416 + " Please use NetworkCapabilities instead.");
11417 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011418 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011419 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011420
11421 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11422 // and administrator uids to be safe.
11423 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011424 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011425
11426 final NetworkRequest requestWithId =
11427 new NetworkRequest(
11428 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11429
11430 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11431 //
11432 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11433 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11434 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011435 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011436 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011437 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011438
11439 mConnectivityDiagnosticsHandler.sendMessage(
11440 mConnectivityDiagnosticsHandler.obtainMessage(
11441 ConnectivityDiagnosticsHandler
11442 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11443 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011444 }
11445
11446 @Override
11447 public void unregisterConnectivityDiagnosticsCallback(
11448 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011449 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011450 mConnectivityDiagnosticsHandler.sendMessage(
11451 mConnectivityDiagnosticsHandler.obtainMessage(
11452 ConnectivityDiagnosticsHandler
11453 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011454 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011455 0,
11456 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011457 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011458
Yan Yanfe96dde2022-12-05 23:00:01 +000011459 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11460 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11461 if (underlyingNetworks == null) return false;
11462
11463 for (Network network : underlyingNetworks) {
11464 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11465 return true;
11466 }
11467 }
11468 return false;
11469 }
11470
Cody Kestingf53a0752020-04-15 12:33:28 -070011471 @Override
11472 public void simulateDataStall(int detectionMethod, long timestampMillis,
11473 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011474 Objects.requireNonNull(network, "network must not be null");
11475 Objects.requireNonNull(extras, "extras must not be null");
11476
paulhu3ffffe72021-09-16 10:15:22 +080011477 enforceAnyPermissionOf(mContext,
11478 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011479 android.Manifest.permission.NETWORK_STACK);
11480 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011481 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11482 throw new SecurityException(
11483 "Data Stall simulation is only possible for test networks or networks built on"
11484 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011485 }
11486
11487 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011488 if (nai == null
11489 || (nai.creatorUid != mDeps.getCallingUid()
11490 && nai.creatorUid != Process.SYSTEM_UID)) {
11491 throw new SecurityException(
11492 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011493 }
11494
Cody Kesting652e3ec2020-05-21 12:08:21 -070011495 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11496 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11497 // Data Stall information as a DataStallReportParcelable and passing to
11498 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11499 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011500 final DataStallReportParcelable p = new DataStallReportParcelable();
11501 p.timestampMillis = timestampMillis;
11502 p.detectionMethod = detectionMethod;
11503
11504 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11505 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11506 }
11507 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11508 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11509 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11510 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11511 }
11512
Serik Beketayevec8ad212020-12-07 22:43:07 -080011513 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011514 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011515
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011516 /**
11517 * Class to hold the information for network activity change event from idle timers
11518 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11519 */
11520 private static final class NetworkActivityParams {
11521 public final boolean isActive;
11522 // Label used for idle timer. Transport type is used as label.
11523 // label is int since NMS was using the identifier as int, and it has not been changed
11524 public final int label;
11525 public final long timestampNs;
11526 // Uid represents the uid that was responsible for waking the radio.
11527 // -1 for no uid and uid is -1 if isActive is false.
11528 public final int uid;
11529
11530 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11531 this.isActive = isActive;
11532 this.label = label;
11533 this.timestampNs = timestampNs;
11534 this.uid = uid;
11535 }
11536 }
11537
lucaslin66f44212021-02-23 01:12:55 +080011538 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11539 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011540 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011541 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011542 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11543 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011544 }
lucaslin37a16d92021-01-21 19:48:09 +080011545
11546 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011547 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011548 mHandler.post(() -> {
11549 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011550 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011551 }
11552 });
lucaslin37a16d92021-01-21 19:48:09 +080011553 }
11554
11555 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011556 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011557 mHandler.post(() -> {
11558 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011559 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011560 }
11561 });
lucaslin66f44212021-02-23 01:12:55 +080011562 }
11563 }
11564
lucaslin1a8b4c62021-01-21 02:02:55 +080011565 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11566
11567 /**
11568 * Class used for updating network activity tracking with netd and notify network activity
11569 * changes.
11570 */
11571 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011572 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011573 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011574 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011575 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011576 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11577 new RemoteCallbackList<>();
11578 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011579 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011580 // If there is no default network, default network is considered active to keep the existing
11581 // behavior. Initial value is used until first connect to the default network.
11582 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011583 // Key is netId. Value is configured idle timer information.
11584 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011585
Chalard Jean46bfbf02022-02-02 00:56:25 +090011586 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011587 public final int timeout;
11588 public final int transportType;
11589
11590 IdleTimerParams(int timeout, int transport) {
11591 this.timeout = timeout;
11592 this.transportType = transport;
11593 }
11594 }
11595
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011596 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011597 @NonNull Handler handler) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011598 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011599 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011600 mHandler = handler;
11601 }
11602
11603 private void ensureRunningOnConnectivityServiceThread() {
11604 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11605 throw new IllegalStateException("Not running on ConnectivityService thread: "
11606 + Thread.currentThread().getName());
11607 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011608 }
11609
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011610 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011611 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011612 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011613 // This activity change is not for the current default network.
11614 // This can happen if netd callback post activity change event message but
11615 // the default network is lost before processing this message.
11616 return;
11617 }
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011618 sendDataActivityBroadcast(transportTypeToLegacyType(activityParams.label),
11619 activityParams.isActive, activityParams.timestampNs);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011620 mIsDefaultNetworkActive = activityParams.isActive;
11621 if (mIsDefaultNetworkActive) {
11622 reportNetworkActive();
lucaslin66f44212021-02-23 01:12:55 +080011623 }
11624 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011625
lucaslin1193a5d2021-01-21 02:04:15 +080011626 private void reportNetworkActive() {
11627 final int length = mNetworkActivityListeners.beginBroadcast();
11628 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11629 try {
11630 for (int i = 0; i < length; i++) {
11631 try {
11632 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11633 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011634 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011635 }
11636 }
11637 } finally {
11638 mNetworkActivityListeners.finishBroadcast();
11639 }
11640 }
11641
lucaslin1a8b4c62021-01-21 02:02:55 +080011642 // This is deprecated and only to support legacy use cases.
11643 private int transportTypeToLegacyType(int type) {
11644 switch (type) {
11645 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011646 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011647 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011648 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011649 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011650 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011651 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011652 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011653 default:
11654 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11655 }
11656 return ConnectivityManager.TYPE_NONE;
11657 }
11658
11659 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11660 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11661 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11662 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11663 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11664 final long ident = Binder.clearCallingIdentity();
11665 try {
11666 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11667 RECEIVE_DATA_ACTIVITY_CHANGE,
11668 null /* resultReceiver */,
11669 null /* scheduler */,
11670 0 /* initialCode */,
11671 null /* initialData */,
11672 null /* initialExtra */);
11673 } finally {
11674 Binder.restoreCallingIdentity(ident);
11675 }
11676 }
11677
11678 /**
11679 * Setup data activity tracking for the given network.
11680 *
11681 * Every {@code setupDataActivityTracking} should be paired with a
11682 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090011683 *
11684 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080011685 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090011686 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011687 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011688 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011689
11690 final int timeout;
11691 final int type;
11692
11693 if (networkAgent.networkCapabilities.hasTransport(
11694 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11695 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011696 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011697 10);
11698 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11699 } else if (networkAgent.networkCapabilities.hasTransport(
11700 NetworkCapabilities.TRANSPORT_WIFI)) {
11701 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011702 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011703 15);
11704 type = NetworkCapabilities.TRANSPORT_WIFI;
11705 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011706 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080011707 }
11708
lucaslinb961efc2021-01-21 02:03:17 +080011709 updateRadioPowerState(true /* isActive */, type);
11710
lucaslin1a8b4c62021-01-21 02:02:55 +080011711 if (timeout > 0 && iface != null) {
11712 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011713 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, type));
Motomu Utsumic298cf02023-05-31 12:06:12 +090011714 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
Motomu Utsumi6225d572023-05-29 15:08:57 +090011715 return true;
lucaslin1a8b4c62021-01-21 02:02:55 +080011716 } catch (Exception e) {
11717 // You shall not crash!
11718 loge("Exception in setupDataActivityTracking " + e);
11719 }
11720 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011721 return false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011722 }
11723
11724 /**
11725 * Remove data activity tracking when network disconnects.
11726 */
11727 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11728 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011729 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011730 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11731
lucaslinb961efc2021-01-21 02:03:17 +080011732 if (iface == null) return;
11733
11734 final int type;
11735 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11736 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11737 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11738 type = NetworkCapabilities.TRANSPORT_WIFI;
11739 } else {
11740 return; // do not track any other networks
11741 }
11742
11743 try {
11744 updateRadioPowerState(false /* isActive */, type);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011745 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011746 if (params == null) {
11747 // IdleTimer is not added if the configured timeout is 0 or negative value
11748 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080011749 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011750 mActiveIdleTimers.remove(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011751 // The call fails silently if no idle timer setup for this interface
11752 mNetd.idletimerRemoveInterface(iface, params.timeout,
11753 Integer.toString(params.transportType));
lucaslinb961efc2021-01-21 02:03:17 +080011754 } catch (Exception e) {
11755 // You shall not crash!
11756 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011757 }
11758 }
11759
Motomu Utsumi6225d572023-05-29 15:08:57 +090011760 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
11761 boolean hasIdleTimer) {
11762 if (defaultNetwork != null) {
11763 mIsDefaultNetworkActive = true;
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011764 // Callbacks are called only when the network has the idle timer.
11765 if (hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011766 reportNetworkActive();
11767 }
11768 } else {
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011769 // If there is no default network, default network is considered active to keep the
11770 // existing behavior.
11771 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090011772 }
11773 }
11774
lucaslin1a8b4c62021-01-21 02:02:55 +080011775 /**
11776 * Update data activity tracking when network state is updated.
11777 */
11778 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11779 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011780 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi6225d572023-05-29 15:08:57 +090011781 boolean hasIdleTimer = false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011782 if (newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011783 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080011784 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011785 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
lucaslin1a8b4c62021-01-21 02:02:55 +080011786 if (oldNetwork != null) {
11787 removeDataActivityTracking(oldNetwork);
11788 }
11789 }
lucaslinb961efc2021-01-21 02:03:17 +080011790
11791 private void updateRadioPowerState(boolean isActive, int transportType) {
11792 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11793 switch (transportType) {
11794 case NetworkCapabilities.TRANSPORT_CELLULAR:
11795 bs.reportMobileRadioPowerState(isActive, NO_UID);
11796 break;
11797 case NetworkCapabilities.TRANSPORT_WIFI:
11798 bs.reportWifiRadioPowerState(isActive, NO_UID);
11799 break;
11800 default:
11801 logw("Untracked transport type:" + transportType);
11802 }
11803 }
lucaslin1193a5d2021-01-21 02:04:15 +080011804
11805 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011806 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080011807 }
11808
11809 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11810 mNetworkActivityListeners.register(l);
11811 }
11812
11813 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11814 mNetworkActivityListeners.unregister(l);
11815 }
lucaslin012f7a12021-01-21 02:04:35 +080011816
11817 public void dump(IndentingPrintWriter pw) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011818 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
11819 pw.println("Idle timers:");
11820 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011821 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
11822 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
11823 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080011824 pw.print(" timeout="); pw.print(params.timeout);
11825 pw.print(" type="); pw.println(params.transportType);
11826 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011827 } catch (Exception e) {
11828 // mActiveIdleTimers should only be accessed from handler thread, except dump().
11829 // As dump() is never called in normal usage, it would be needlessly expensive
11830 // to lock the collection only for its benefit.
11831 // Also, mActiveIdleTimers is not expected to be updated frequently.
11832 // So catching the exception and logging.
11833 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080011834 }
11835 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011836 }
James Mattis47db0582021-01-01 14:13:35 -080011837
Daniel Brightf9e945b2020-06-15 16:10:01 -070011838 /**
11839 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11840 *
11841 * @param socketInfo the socket information
11842 * @param callback the callback to register
11843 */
11844 @Override
11845 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11846 @NonNull final IQosCallback callback) {
11847 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11848 if (nai == null || nai.networkCapabilities == null) {
11849 try {
11850 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11851 } catch (final RemoteException ex) {
11852 loge("registerQosCallbackInternal: RemoteException", ex);
11853 }
11854 return;
11855 }
11856 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11857 }
11858
11859 /**
11860 * Register a {@link IQosCallback} with base {@link QosFilter}.
11861 *
11862 * @param filter the filter to register
11863 * @param callback the callback to register
11864 * @param nai the agent information related to the filter's network
11865 */
11866 @VisibleForTesting
11867 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11868 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011869 Objects.requireNonNull(filter, "filter must be non-null");
11870 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011871
11872 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011873 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11874 // on this network is unregistered when the app loses permission or b) no QoS
11875 // callbacks are sent for restricted networks unless the app currently has permission
11876 // to access restricted networks.
11877 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011878 }
11879 mQosCallbackTracker.registerCallback(callback, filter, nai);
11880 }
11881
11882 /**
11883 * Unregisters the given callback.
11884 *
11885 * @param callback the callback to unregister
11886 */
11887 @Override
11888 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011889 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011890 mQosCallbackTracker.unregisterCallback(callback);
11891 }
James Mattis47db0582021-01-01 14:13:35 -080011892
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011893 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11894 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11895 // Enterprise device can be fully managed like device owner and such use case
11896 // also should be supported. Calling app check for work profile and fully managed device
11897 // is already done in DevicePolicyManager.
11898 // This check is an extra caution to be sure device is fully managed or not.
11899 final UserManager um = mContext.getSystemService(UserManager.class);
11900 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11901 if (um.isManagedProfile(profile.getIdentifier())) {
11902 return true;
11903 }
Chalard Jeandf29a852023-05-29 17:02:43 +090011904 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011905 return false;
11906 }
11907
James Mattis45d81842021-01-10 14:24:24 -080011908 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011909 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011910 *
11911 * See the documentation for the individual preferences for a description of the supported
11912 * behaviors.
11913 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011914 * @param profile If the device owner is set, any profile is allowed.
11915 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011916 * @param preferences the list of profile network preferences for the
11917 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011918 * @param listener an optional listener to listen for completion of the operation.
11919 */
11920 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011921 public void setProfileNetworkPreferences(
11922 @NonNull final UserHandle profile,
11923 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011924 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011925 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011926 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011927
11928 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011929 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11930 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11931 .build();
11932 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011933 }
11934
paulhu3ffffe72021-09-16 10:15:22 +080011935 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011936 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011937 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011938 }
11939 if (profile.getIdentifier() < 0) {
11940 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11941 + "UserHandle.CURRENT not supported)");
11942 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011943 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11944 throw new IllegalArgumentException("Profile must be a managed profile "
11945 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011946 }
paulhuaa0743d2021-05-26 21:56:03 +080011947
Chalard Jean0606fc82022-12-14 20:34:43 +090011948 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011949 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011950 for (final ProfileNetworkPreference preference : preferences) {
11951 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011952 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011953 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011954 switch (preference.getPreference()) {
11955 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11956 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011957 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011958 if (preference.getPreferenceEnterpriseId() != 0) {
11959 throw new IllegalArgumentException(
11960 "Invalid enterprise identifier in setProfileNetworkPreferences");
11961 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011962 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011963 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11964 blockingNonEnterprise = true;
11965 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011966 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11967 allowFallback = false;
11968 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011969 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011970 // This code is needed even though there is a check later on,
11971 // because isRangeAlreadyInPreferenceList assumes that every preference
11972 // has a UID list.
11973 if (hasDefaultPreference) {
11974 throw new IllegalArgumentException(
11975 "Default profile preference should not be set along with other "
11976 + "preference");
11977 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011978 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11979 throw new IllegalArgumentException(
11980 "Invalid enterprise identifier in setProfileNetworkPreferences");
11981 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011982 final Set<UidRange> uidRangeSet =
11983 getUidListToBeAppliedForNetworkPreference(profile, preference);
11984 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11985 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11986 } else {
11987 throw new IllegalArgumentException(
11988 "Overlapping uid range in setProfileNetworkPreferences");
11989 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011990 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011991 nc.addEnterpriseId(
11992 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011993 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11994 break;
11995 default:
11996 throw new IllegalArgumentException(
11997 "Invalid preference in setProfileNetworkPreferences");
11998 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011999 preferenceList.add(new ProfileNetworkPreferenceInfo(
12000 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012001 if (hasDefaultPreference && preferenceList.size() > 1) {
12002 throw new IllegalArgumentException(
12003 "Default profile preference should not be set along with other preference");
12004 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012005 }
12006 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012007 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012008 }
12009
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012010 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12011 @NonNull final UserHandle profile,
12012 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12013 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012014 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12015 profileNetworkPreference.getIncludedUids());
12016
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012017 if (uidRangeSet.size() > 0) {
12018 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12019 throw new IllegalArgumentException(
12020 "Allow uid range is outside the uid range of profile.");
12021 }
12022 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012023 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012024 profileNetworkPreference.getExcludedUids());
12025 if (disallowUidRangeSet.size() > 0) {
12026 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12027 throw new IllegalArgumentException(
12028 "disallow uid range is outside the uid range of profile.");
12029 }
12030 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12031 disallowUidRangeSet);
12032 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012033 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012034 uidRangeSet.add(profileUids);
12035 }
12036 }
12037 return uidRangeSet;
12038 }
12039
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012040 private boolean isEnterpriseIdentifierValid(
12041 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012042 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012043 return true;
12044 }
12045 return false;
12046 }
12047
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012048 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012049 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012050 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012051 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012052 // The NRI for a user should contain the request for capabilities.
12053 // If fallback to default network is needed then NRI should include
12054 // the request for the default network. Create an image of it to
12055 // have the correct UIDs in it (also a request can only be part of one NRI, because
12056 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012057 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12058 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012059 if (pref.allowFallback) {
12060 nrs.add(createDefaultInternetRequestForTransport(
12061 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12062 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012063 if (VDBG) {
12064 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12065 pref.capabilities.getUids()));
12066 }
12067
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012068 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012069 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012070 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012071 result.add(nri);
12072 }
12073 return result;
12074 }
12075
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012076 /**
12077 * Compare if the given UID range sets have the same UIDs.
12078 *
12079 */
12080 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012081 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012082 @NonNull Set<UidRange> uidRangeSet) {
12083 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12084 return false;
12085 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012086 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012087 if (UidRangeUtils.doesRangeSetOverlap(
12088 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12089 return true;
12090 }
12091 }
12092 return false;
12093 }
12094
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012095 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012096 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012097 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012098 /*
12099 * handleSetProfileNetworkPreference is always called for single user.
12100 * preferenceList only contains preferences for different uids within the same user
12101 * (enforced by getUidListToBeAppliedForNetworkPreference).
12102 * Clear all the existing preferences for the user before applying new preferences.
12103 *
12104 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012105 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12106 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012107 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12108 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012109
paulhu74128522021-09-28 02:29:03 +000012110 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12111 addPerAppDefaultNetworkRequests(
12112 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012113 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012114
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012115 // Finally, rematch.
12116 rematchAllNetworksAndRequests();
12117
12118 if (null != listener) {
12119 try {
12120 listener.onComplete();
12121 } catch (RemoteException e) {
12122 loge("Listener for setProfileNetworkPreference has died");
12123 }
12124 }
12125 }
12126
paulhu51f77dc2021-06-07 02:34:20 +000012127 @VisibleForTesting
12128 @NonNull
12129 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12130 @NonNull final Set<Integer> uids) {
12131 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12132 if (uids.size() == 0) {
12133 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12134 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12135 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12136 return nris;
12137 }
12138
12139 final List<NetworkRequest> requests = new ArrayList<>();
12140 // The NRI should be comprised of two layers:
12141 // - The request for the mobile network preferred.
12142 // - The request for the default network, for fallback.
12143 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012144 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012145 requests.add(createDefaultInternetRequestForTransport(
12146 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12147 final Set<UidRange> ranges = new ArraySet<>();
12148 for (final int uid : uids) {
12149 ranges.add(new UidRange(uid, uid));
12150 }
12151 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012152 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012153 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012154 return nris;
12155 }
12156
12157 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012158 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012159 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12160 addPerAppDefaultNetworkRequests(
12161 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012162 // Finally, rematch.
12163 rematchAllNetworksAndRequests();
12164 }
12165
Patrick Rohr2857ac42022-01-21 14:58:16 +010012166 private void handleIngressRateLimitChanged() {
12167 final long oldIngressRateLimit = mIngressRateLimit;
12168 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12169 mContext);
12170 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12171 if (canNetworkBeRateLimited(networkAgent)) {
12172 // If rate limit has previously been enabled, remove the old limit first.
12173 if (oldIngressRateLimit >= 0) {
12174 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12175 }
12176 if (mIngressRateLimit >= 0) {
12177 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12178 mIngressRateLimit);
12179 }
12180 }
12181 }
12182 }
12183
12184 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012185 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012186 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012187
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012188 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12189 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12190 // internet connectivity can be rate limited.
12191 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12192 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012193 return false;
12194 }
12195
12196 final String iface = networkAgent.linkProperties.getInterfaceName();
12197 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012198 // This may happen in tests, but if there is no interface then there is nothing that
12199 // can be rate limited.
12200 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012201 return false;
12202 }
12203 return true;
12204 }
12205
James Mattis45d81842021-01-10 14:24:24 -080012206 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012207 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12208 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012209 }
12210
12211 /**
12212 * Used by automotive devices to set the network preferences used to direct traffic at an
12213 * application level as per the given OemNetworkPreferences. An example use-case would be an
12214 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12215 * vehicle via a particular network.
12216 *
12217 * Calling this will overwrite the existing preference.
12218 *
James Mattisda32cfe2021-01-26 16:23:52 -080012219 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012220 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012221 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012222 */
James Mattis47db0582021-01-01 14:13:35 -080012223 @Override
James Mattis45d81842021-01-10 14:24:24 -080012224 public void setOemNetworkPreference(
12225 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012226 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012227
James Mattisfa270db2021-05-31 17:11:10 -070012228 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12229 // Only bypass the permission/device checks if this is a valid test request.
12230 if (isValidTestOemNetworkPreference(preference)) {
12231 enforceManageTestNetworksPermission();
12232 } else {
12233 enforceAutomotiveDevice();
12234 enforceOemNetworkPreferencesPermission();
12235 validateOemNetworkPreferences(preference);
12236 }
James Mattis45d81842021-01-10 14:24:24 -080012237
James Mattis45d81842021-01-10 14:24:24 -080012238 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12239 new Pair<>(preference, listener)));
12240 }
12241
James Mattisfa270db2021-05-31 17:11:10 -070012242 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012243 * Sets the specified UIDs to get/receive the VPN as the only default network.
12244 *
12245 * Calling this will overwrite the existing network preference for this session, and the
12246 * specified UIDs won't get any default network when no VPN is connected.
12247 *
12248 * @param session The VPN session which manages the passed UIDs.
12249 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12250 * setting for this session if the array is empty. Null is not allowed, the
12251 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12252 * @hide
12253 */
12254 @Override
12255 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12256 Objects.requireNonNull(ranges);
12257 enforceNetworkStackOrSettingsPermission();
12258 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12259 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12260 throw new IllegalArgumentException(
12261 "setVpnNetworkPreference: Passed UID ranges overlap");
12262 }
12263
12264 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12265 new VpnNetworkPreferenceInfo(session,
12266 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12267 }
12268
12269 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12270 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12271
12272 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12273 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12274
12275 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12276 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12277 // Finally, rematch.
12278 rematchAllNetworksAndRequests();
12279 }
12280
12281 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12282 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12283 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12284 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12285 final List<NetworkRequest> requests = new ArrayList<>();
12286 // Request VPN only, so other networks won't be the fallback options when VPN is not
12287 // connected temporarily.
12288 requests.add(createVpnRequest());
12289 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12290 setNetworkRequestUids(requests, uidRanges);
12291 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12292 }
12293 return nris;
12294 }
12295
12296 /**
James Mattisfa270db2021-05-31 17:11:10 -070012297 * Check the validity of an OEM network preference to be used for testing purposes.
12298 * @param preference the preference to validate
12299 * @return true if this is a valid OEM network preference test request.
12300 */
12301 private boolean isValidTestOemNetworkPreference(
12302 @NonNull final OemNetworkPreferences preference) {
12303 // Allow for clearing of an existing OemNetworkPreference used for testing.
12304 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12305 // changes after this check is complete. This is an unlikely scenario as calling of this API
12306 // is controlled by the OEM therefore the added complexity is not worth adding given those
12307 // circumstances. That said, it is an edge case to be aware of hence this comment.
12308 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12309 && isTestOemNetworkPreference(mOemNetworkPreferences);
12310 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12311 }
12312
12313 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12314 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12315 return prefMap.size() == 1
12316 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12317 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12318 }
12319
James Mattis45d81842021-01-10 14:24:24 -080012320 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12321 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12322 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012323 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12324 throw new IllegalArgumentException(
12325 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12326 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012327 }
12328 }
12329 }
12330
12331 private void handleSetOemNetworkPreference(
12332 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012333 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012334 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12335 if (DBG) {
12336 log("set OEM network preferences :" + preference.toString());
12337 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012338
James Mattiscb1e0362021-04-06 17:07:42 -070012339 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012340 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12341 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12342 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012343 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012344
12345 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012346 try {
12347 listener.onComplete();
12348 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012349 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012350 }
James Mattis45d81842021-01-10 14:24:24 -080012351 }
12352 }
12353
paulhu74128522021-09-28 02:29:03 +000012354 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012355 // Skip the requests which are set by other network preference. Because the uid range rules
12356 // should stay in netd.
12357 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012358 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012359 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012360 }
12361
James Mattis3ce3d3c2021-02-09 18:18:28 -080012362 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12363 ensureRunningOnConnectivityServiceThread();
12364 mDefaultNetworkRequests.addAll(nris);
12365 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12366 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012367 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012368 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12369 nrisToRegister.addAll(
12370 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12371 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012372 }
12373
12374 /**
12375 * All current requests that are tracking the default network need to be assessed as to whether
12376 * or not the current set of per-application default requests will be changing their default
12377 * network. If so, those requests will need to be updated so that they will send callbacks for
12378 * default network changes at the appropriate time. Additionally, those requests tracking the
12379 * default that were previously updated by this flow will need to be reassessed.
12380 * @return the nris which will need to be updated.
12381 */
12382 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12383 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12384 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12385 // same nri in the map's values for each of its NetworkRequest objects.
12386 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012387 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012388 // Include this nri if it is currently being tracked.
12389 if (isPerAppTrackedNri(nri)) {
12390 defaultCallbackRequests.add(nri);
12391 continue;
12392 }
12393 // We only track callbacks for requests tracking the default.
12394 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12395 continue;
12396 }
12397 // Include this nri if it will be tracked by the new per-app default requests.
12398 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012399 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012400 if (isNriGoingToBeTracked) {
12401 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012402 }
12403 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012404 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012405 }
12406
James Mattis3ce3d3c2021-02-09 18:18:28 -080012407 /**
12408 * Create nris for those network requests that are currently tracking the default network that
12409 * are being controlled by a per-application default.
12410 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12411 * foundation when creating the nri. Important items include the calling uid's original
12412 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12413 * requests are assumed to have already been validated as needing to be updated.
12414 * @return the Set of nris to use when registering network requests.
12415 */
12416 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12417 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12418 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12419 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12420 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012421 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012422
Chalard Jean9473c982021-07-29 20:03:04 +090012423 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012424 if (trackingNri == mDefaultRequest) {
12425 callbackRequestsToRegister.add(new NetworkRequestInfo(
12426 callbackRequest,
12427 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12428 continue;
12429 }
12430
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012431 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012432 callbackRequestsToRegister.add(new NetworkRequestInfo(
12433 callbackRequest,
12434 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012435 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012436 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012437 }
12438 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012439 }
12440
Chalard Jean17215832021-03-01 14:06:28 +090012441 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12442 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012443 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012444 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012445 }
12446 }
12447
James Mattis45d81842021-01-10 14:24:24 -080012448 /**
12449 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12450 */
12451 @VisibleForTesting
12452 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012453 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012454 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012455 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012456 final SparseArray<Set<Integer>> uids =
12457 createUidsFromOemNetworkPreferences(preference);
12458 for (int i = 0; i < uids.size(); i++) {
12459 final int key = uids.keyAt(i);
12460 final Set<Integer> value = uids.valueAt(i);
12461 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12462 // No need to add an nri without any requests.
12463 if (0 == nri.mRequests.size()) {
12464 continue;
12465 }
12466 nris.add(nri);
12467 }
12468
12469 return nris;
12470 }
12471
12472 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12473 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012474 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012475 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012476 final List<UserHandle> users =
12477 mContext.getSystemService(UserManager.class).getUserHandles(true);
12478 if (null == users || users.size() == 0) {
12479 if (VDBG || DDBG) {
12480 log("No users currently available for setting the OEM network preference.");
12481 }
James Mattisb6b6a432021-06-01 22:30:36 -070012482 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012483 }
James Mattis45d81842021-01-10 14:24:24 -080012484 for (final Map.Entry<String, Integer> entry :
12485 preference.getNetworkPreferences().entrySet()) {
12486 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012487 // Add the rules for all users as this policy is device wide.
12488 for (final UserHandle user : users) {
12489 try {
12490 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12491 if (!prefToUids.contains(pref)) {
12492 prefToUids.put(pref, new ArraySet<>());
12493 }
12494 prefToUids.get(pref).add(uid);
12495 } catch (PackageManager.NameNotFoundException e) {
12496 // Although this may seem like an error scenario, it is ok that uninstalled
12497 // packages are sent on a network preference as the system will watch for
12498 // package installations associated with this network preference and update
12499 // accordingly. This is done to minimize race conditions on app install.
12500 continue;
James Mattis45d81842021-01-10 14:24:24 -080012501 }
James Mattis45d81842021-01-10 14:24:24 -080012502 }
12503 }
James Mattisb6b6a432021-06-01 22:30:36 -070012504 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012505 }
12506
12507 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12508 @OemNetworkPreferences.OemNetworkPreference final int preference,
12509 @NonNull final Set<Integer> uids) {
12510 final List<NetworkRequest> requests = new ArrayList<>();
12511 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12512 switch (preference) {
12513 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12514 requests.add(createUnmeteredNetworkRequest());
12515 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012516 requests.add(createDefaultInternetRequestForTransport(
12517 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012518 break;
12519 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12520 requests.add(createUnmeteredNetworkRequest());
12521 requests.add(createOemPaidNetworkRequest());
12522 break;
12523 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12524 requests.add(createOemPaidNetworkRequest());
12525 break;
12526 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12527 requests.add(createOemPrivateNetworkRequest());
12528 break;
James Mattisfa270db2021-05-31 17:11:10 -070012529 case OEM_NETWORK_PREFERENCE_TEST:
12530 requests.add(createUnmeteredNetworkRequest());
12531 requests.add(createTestNetworkRequest());
12532 requests.add(createDefaultRequest());
12533 break;
12534 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12535 requests.add(createTestNetworkRequest());
12536 break;
James Mattis45d81842021-01-10 14:24:24 -080012537 default:
12538 // This should never happen.
12539 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12540 + " called with invalid preference of " + preference);
12541 }
12542
James Mattisfa270db2021-05-31 17:11:10 -070012543 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012544 for (final int uid : uids) {
12545 ranges.add(new UidRange(uid, uid));
12546 }
12547 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012548 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012549 }
12550
12551 private NetworkRequest createUnmeteredNetworkRequest() {
12552 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12553 .addCapability(NET_CAPABILITY_NOT_METERED)
12554 .addCapability(NET_CAPABILITY_VALIDATED);
12555 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12556 }
12557
12558 private NetworkRequest createOemPaidNetworkRequest() {
12559 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12560 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12561 .addCapability(NET_CAPABILITY_OEM_PAID)
12562 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12563 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12564 }
12565
12566 private NetworkRequest createOemPrivateNetworkRequest() {
12567 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12568 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12569 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12570 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12571 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12572 }
12573
12574 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012575 final NetworkCapabilities netcap = new NetworkCapabilities();
12576 netcap.addCapability(NET_CAPABILITY_INTERNET);
12577 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12578 return netcap;
12579 }
12580
12581 private NetworkRequest createTestNetworkRequest() {
12582 final NetworkCapabilities netcap = new NetworkCapabilities();
12583 netcap.clearAll();
12584 netcap.addTransportType(TRANSPORT_TEST);
12585 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012586 }
James Mattis47db0582021-01-01 14:13:35 -080012587 }
markchien738ad912021-12-09 18:15:45 +080012588
12589 @Override
Junyu Laic279f182023-09-07 15:25:52 +080012590 public void setDataSaverEnabled(final boolean enable) {
12591 enforceNetworkStackOrSettingsPermission();
12592 try {
12593 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
12594 if (!ret) {
12595 throw new IllegalStateException("Error when changing iptables: " + enable);
12596 }
12597 } catch (RemoteException e) {
12598 // Lack of permission or binder errors.
12599 throw new IllegalStateException(e);
12600 }
12601 }
12602
12603 @Override
markchien738ad912021-12-09 18:15:45 +080012604 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12605 enforceNetworkStackOrSettingsPermission();
12606
12607 try {
12608 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012609 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012610 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012611 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012612 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012613 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012614 throw new IllegalStateException(e);
12615 }
12616 }
12617
12618 @Override
12619 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12620 enforceNetworkStackOrSettingsPermission();
12621
12622 try {
12623 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012624 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012625 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012626 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012627 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012628 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012629 throw new IllegalStateException(e);
12630 }
12631 }
markchiene1561fa2021-12-09 22:00:56 +080012632
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012633 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
12634 throws PackageManager.NameNotFoundException {
12635 final PackageManager pm = mContext.getPackageManager();
12636 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12637 if (appId < Process.FIRST_APPLICATION_UID) {
12638 throw new RuntimeException("Can't set package firewall rule for system app "
12639 + packageName + " with appId " + appId);
12640 }
12641 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
12642 final int uid = uh.getUid(appId);
12643 setUidFirewallRule(chain, uid, rule);
12644 }
12645 return appId;
12646 }
12647
markchiene1561fa2021-12-09 22:00:56 +080012648 @Override
markchien3c04e662022-03-22 16:29:56 +080012649 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012650 enforceNetworkStackOrSettingsPermission();
12651
markchien3c04e662022-03-22 16:29:56 +080012652 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12653 int firewallRule = getFirewallRuleType(chain, rule);
12654
12655 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12656 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12657 }
12658
markchiene1561fa2021-12-09 22:00:56 +080012659 try {
markchien3c04e662022-03-22 16:29:56 +080012660 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012661 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012662 throw new IllegalStateException(e);
12663 }
12664 }
markchien98a6f952022-01-13 23:43:53 +080012665
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012666 private int getPackageFirewallRule(final int chain, final String packageName)
12667 throws PackageManager.NameNotFoundException {
12668 final PackageManager pm = mContext.getPackageManager();
12669 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12670 return getUidFirewallRule(chain, appId);
12671 }
12672
Motomu Utsumi900b8062023-01-19 16:16:49 +090012673 @Override
12674 public int getUidFirewallRule(final int chain, final int uid) {
12675 enforceNetworkStackOrSettingsPermission();
12676 return mBpfNetMaps.getUidRule(chain, uid);
12677 }
12678
markchien3c04e662022-03-22 16:29:56 +080012679 private int getFirewallRuleType(int chain, int rule) {
12680 final int defaultRule;
12681 switch (chain) {
12682 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012683 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12684 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012685 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012686 defaultRule = FIREWALL_RULE_ALLOW;
12687 break;
12688 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12689 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12690 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12691 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12692 defaultRule = FIREWALL_RULE_DENY;
12693 break;
12694 default:
12695 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12696 }
12697 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12698
12699 return rule;
12700 }
12701
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012702 private void closeSocketsForFirewallChainLocked(final int chain)
12703 throws ErrnoException, SocketException, InterruptedIOException {
12704 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12705 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12706 // So, close all non-system socket owned by uids that are not explicitly allowed
12707 Set<Range<Integer>> ranges = new ArraySet<>();
12708 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12709 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12710 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12711 } else {
12712 // Denylist means the firewall allows all by default, uids must be explicitly denied
12713 // So, close socket owned by uids that are explicitly denied
12714 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12715 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12716 }
12717 }
12718
markchien98a6f952022-01-13 23:43:53 +080012719 @Override
12720 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12721 enforceNetworkStackOrSettingsPermission();
12722
12723 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012724 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012725 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012726 throw new IllegalStateException(e);
12727 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012728
Chalard Jeandf29a852023-05-29 17:02:43 +090012729 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012730 try {
12731 closeSocketsForFirewallChainLocked(chain);
12732 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12733 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12734 }
12735 }
markchien98a6f952022-01-13 23:43:53 +080012736 }
12737
markchien00a0bed2022-01-13 23:46:13 +080012738 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012739 public boolean getFirewallChainEnabled(final int chain) {
12740 enforceNetworkStackOrSettingsPermission();
12741
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012742 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012743 }
12744
12745 @Override
markchien00a0bed2022-01-13 23:46:13 +080012746 public void replaceFirewallChain(final int chain, final int[] uids) {
12747 enforceNetworkStackOrSettingsPermission();
12748
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012749 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012750 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012751
12752 @Override
12753 public IBinder getCompanionDeviceManagerProxyService() {
12754 enforceNetworkStackPermission(mContext);
12755 return mCdmps;
12756 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012757}