blob: b31b94c5cd4d6cf30ed69f4a220217e12c7e1d67 [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;
junyulai011b1f12019-01-03 18:50:15 +0800202import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800203import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900204import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400205import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800206import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800207import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400208import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800209import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900210import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900211import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900212import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900213import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800214import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900215import android.net.networkstack.ModuleNetworkStackClient;
216import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900217import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800218import android.net.resolv.aidl.DnsHealthEventParcel;
219import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
220import android.net.resolv.aidl.Nat64PrefixEventParcel;
221import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900222import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900223import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800224import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800225import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800226import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700227import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000228import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700230import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700231import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232import android.os.Looper;
233import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700234import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700235import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900236import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800237import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700238import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700239import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800240import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700241import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900242import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900243import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700244import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700245import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400246import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800247import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900248import android.stats.connectivity.MeteredState;
249import android.stats.connectivity.RequestType;
250import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900251import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700252import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700253import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700254import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800255import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900256import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000257import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600258import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900259import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900260import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700261import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700262import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900263import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800264
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800265import androidx.annotation.RequiresApi;
266
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900267import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400268import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400269import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700270import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900271import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900272import com.android.metrics.ConnectionDurationForTransports;
273import com.android.metrics.ConnectionDurationPerTransports;
274import com.android.metrics.ConnectivitySampleMetricsHelper;
275import com.android.metrics.ConnectivityStateSample;
276import com.android.metrics.NetworkCountForTransports;
277import com.android.metrics.NetworkCountPerTransports;
278import com.android.metrics.NetworkDescription;
279import com.android.metrics.NetworkList;
280import com.android.metrics.NetworkRequestCount;
281import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800282import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900283import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800284import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000285import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900286import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800287import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900288import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900289import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100290import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900291import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
292import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900293import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800294import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800295import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100296import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000297import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800298import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
299import com.android.networkstack.apishim.ConstantsShim;
300import com.android.networkstack.apishim.common.BroadcastOptionsShim;
301import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900302import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900303import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000304import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900305import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800306import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800307import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900308import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900309import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900310import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500311import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700312import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900313import com.android.server.connectivity.FullScore;
Junyu Laif8dba342023-10-12 17:01:03 +0800314import com.android.server.connectivity.HandlerUtils;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900315import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900316import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000317import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100318import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700319import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900320import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700321import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600322import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900323import com.android.server.connectivity.NetworkNotificationManager;
324import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900325import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900326import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900327import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700328import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900329import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900330import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700331import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900332import com.android.server.connectivity.RoutingCoordinatorService;
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;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900496 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800497
498 private final Object mTNSLock = new Object();
499
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700500 private String mCurrentTcpBufferSizes;
501
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900502 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000503 new Class[] {
504 ConnectivityService.class,
505 NetworkAgent.class,
506 NetworkAgentInfo.class,
507 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900508
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500509 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400510 // Tear down networks that have no chance (e.g. even if validated) of becoming
511 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500512 // all networks have been rematched against all NetworkRequests.
513 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400514 // Don't reap networks. This should be passed when some networks have not yet been
515 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500516 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900517 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500518
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900519 private enum UnneededFor {
520 LINGER, // Determine whether this network is unneeded and should be lingered.
521 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
522 }
523
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700524 /**
paulhuaa0743d2021-05-26 21:56:03 +0800525 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800526 * should have priority. The order is passed to netd which will use it together
527 * with UID ranges to generate the corresponding IP rule. This serves to
528 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800529 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800530 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000531 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800532 *
paulhu48291862021-07-14 14:53:57 +0800533 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
534 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800535 */
paulhu48291862021-07-14 14:53:57 +0800536 // Used when sending to netd to code for "no order".
537 static final int PREFERENCE_ORDER_NONE = 0;
538 // Order for requests that don't code for a per-app preference. As it is
539 // out of the valid range, the corresponding order should be
540 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800541 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800542 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800543 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800544 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
545 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800546 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800547 static final int PREFERENCE_ORDER_OEM = 10;
548 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800549 // See {@link #setProfileNetworkPreference}.
550 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800551 static final int PREFERENCE_ORDER_PROFILE = 20;
552 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800553 // better scores are connected.
554 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800555 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800556 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900557 // Preference order that signifies the network shouldn't be set as a default network for
558 // the UIDs, only give them access to it. TODO : replace this with a boolean
559 // in NativeUidRangeConfig
560 @VisibleForTesting
561 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
562 // Bound for the lowest valid preference order.
563 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800564
565 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700566 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700567 * from one net to another. Clear happens when we get a new
568 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
569 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700570 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700571 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700572
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700573 /**
574 * used internally to reload global proxy settings
575 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700576 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700577
Robert Greenwalt34848c02011-03-25 13:09:25 -0700578 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400579 * PAC manager has received new port.
580 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800581 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400582
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700583 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900584 * used internally when registering NetworkProviders
585 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700586 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900587 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700588
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700589 /**
590 * used internally when registering NetworkAgents
591 * obj = Messenger
592 */
593 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
594
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700595 /**
596 * used to add a network request
597 * includes a NetworkRequestInfo
598 */
599 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
600
601 /**
602 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900603 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700604 * cancel it.
605 * includes a NetworkRequestInfo
606 */
607 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
608
609 /**
610 * used to add a network listener - no request
611 * includes a NetworkRequestInfo
612 */
613 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
614
615 /**
616 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400617 * arg1 = UID of caller
618 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700619 */
620 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
621
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700622 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900623 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700624 * obj = Messenger
625 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900626 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700627
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700628 /**
629 * used internally to expire a wakelock when transitioning
630 * from one net to another. Expire happens when we fail to find
631 * a new network (typically after 1 minute) -
632 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
633 * a replacement network.
634 */
635 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
636
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700637 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800638 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400639 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800640 */
641 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
642
643 /**
644 * used to remove a pending intent and its associated network request.
645 * arg1 = UID of caller
646 * obj = PendingIntent
647 */
648 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
649
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900650 /**
651 * used to specify whether a network should be used even if unvalidated.
652 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
653 * arg2 = whether to remember this choice in the future (1 or 0)
654 * obj = network
655 */
656 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
657
658 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700659 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900660 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700661 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900662
Paul Jensenc8873fc2015-06-17 14:15:39 -0400663 /**
664 * used to add a network listener with a pending intent
665 * obj = NetworkRequestInfo
666 */
667 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
668
Hugo Benichid6b510a2017-04-06 17:22:18 +0900669 /**
670 * used to specify whether a network should not be penalized when it becomes unvalidated.
671 */
672 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
673
674 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700675 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900676 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700677 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900678
Erik Kline31b4a9e2018-01-11 21:07:29 +0900679 // Handle changes in Private DNS settings.
680 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
681
dalyk1720e542018-03-05 12:42:22 -0500682 // Handle private DNS validation status updates.
683 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
684
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900685 /**
686 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
687 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800688 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
689 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
690 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900691 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900692 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900693
694 /**
695 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
696 * config was resolved.
697 * obj = PrivateDnsConfig
698 * arg2 = netid
699 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900700 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900701
702 /**
703 * Request ConnectivityService display provisioning notification.
704 * arg1 = Whether to make the notification visible.
705 * arg2 = NetID.
706 * obj = Intent to be launched when notification selected by user, null if !arg1.
707 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900708 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900709
710 /**
lucaslin2240ef62019-03-12 13:08:03 +0800711 * Used to specify whether a network should be used even if connectivity is partial.
712 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
713 * false)
714 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
715 * obj = network
716 */
lucaslin444d43a2020-02-20 16:56:59 +0800717 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800718
719 /**
lucasline117e2e2019-10-22 18:27:33 +0800720 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
721 * Both of the arguments are bitmasks, and the value of bits come from
722 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900723 * arg1 = unused
724 * arg2 = netId
725 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800726 */
lucaslin444d43a2020-02-20 16:56:59 +0800727 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800728
729 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900730 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
731 * arg1 = unused
732 * arg2 = netId
733 * obj = captive portal data
734 */
lucaslin444d43a2020-02-20 16:56:59 +0800735 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900736
737 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900738 * Used by setRequireVpnForUids.
739 * arg1 = whether the specified UID ranges are required to use a VPN.
740 * obj = Array of UidRange objects.
741 */
742 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
743
744 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900745 * Used internally when setting the default networks for OemNetworkPreferences.
746 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800747 */
748 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
749
750 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800751 * Used to indicate the system default network becomes active.
752 */
753 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
754
755 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900756 * Used internally when setting a network preference for a user profile.
757 * obj = Pair<ProfileNetworkPreference, Listener>
758 */
759 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
760
761 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000762 * Event to specify that reasons for why an uid is blocked changed.
763 * arg1 = uid
764 * arg2 = blockedReasons
765 */
766 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
767
768 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900769 * Event to register a new network offer
770 * obj = NetworkOffer
771 */
772 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
773
774 /**
775 * Event to unregister an existing network offer
776 * obj = INetworkOfferCallback
777 */
778 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
779
780 /**
paulhu51f77dc2021-06-07 02:34:20 +0000781 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
782 */
783 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
784
785 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800786 * Event to set temporary allow bad wifi within a limited time to override
787 * {@code config_networkAvoidBadWifi}.
788 */
789 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
790
791 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100792 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
793 */
794 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
795
796 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900797 * The initial evaluation period is over for this network.
798 *
799 * If no form of connectivity has been found on this network (valid, partial, captive portal)
800 * then the stack will now consider it to have been determined bad.
801 */
802 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
803
804 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000805 * Used internally when the user does not want the network from captive portal app.
806 * obj = Network
807 */
808 private static final int EVENT_USER_DOES_NOT_WANT = 58;
809
810 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000811 * Event to set VPN as preferred network for specific apps.
812 * obj = VpnNetworkPreferenceInfo
813 */
814 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
815
816 /**
chiachangwange0192a72023-02-06 13:25:01 +0000817 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
818 */
819 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
820
821 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000822 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
823 */
824 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
825
826 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900827 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
828 * should be shown.
829 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900830 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900831
832 /**
833 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
834 * should be hidden.
835 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900836 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900837
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800838 /**
839 * The maximum alive time to allow bad wifi configuration for testing.
840 */
841 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
842
Patrick Rohr2857ac42022-01-21 14:58:16 +0100843 /**
chiachangwange0192a72023-02-06 13:25:01 +0000844 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
845 * testing.
846 */
847 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
848
849 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100850 * The priority of the tc police rate limiter -- smaller value is higher priority.
851 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
852 */
853 private static final short TC_PRIO_POLICE = 1;
854
855 /**
856 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
857 */
858 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700859 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100860
Hugo Benichi47011212017-03-30 10:46:05 +0900861 private static String eventName(int what) {
862 return sMagicDecoderRing.get(what, Integer.toString(what));
863 }
864
paulhua10d8212020-11-10 15:32:56 +0800865 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900866 final DnsResolverServiceManager dsm = context.getSystemService(
867 DnsResolverServiceManager.class);
868 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800869 }
870
Cody Kesting73708bf2019-12-18 10:57:50 -0800871 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900872 @VisibleForTesting
873 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700874 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700875 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700876 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700877 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800878 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
879 @VisibleForTesting
880 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
881
Erik Kline32120082017-12-13 19:40:49 +0900882 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900883 @VisibleForTesting
884 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700885
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400886 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800887 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400888
Chalard Jean46bfbf02022-02-02 00:56:25 +0900889 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800890 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700891
Chalard Jean5d70ba42018-06-07 16:44:04 +0900892 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
893 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800894 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400895
Erik Kline05f2b402015-04-30 12:58:40 +0900896 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700897
Chalard Jean46bfbf02022-02-02 00:56:25 +0900898 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400899
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700900 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900901 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700902
Valentin Iftime9fa35092019-09-24 13:32:13 +0200903 private Set<String> mWolSupportedInterfaces;
904
Roshan Pius08c94fb2020-01-16 12:17:17 -0800905 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800906 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800907 private final AppOpsManager mAppOpsManager;
908
909 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400910
chiachangwang3d60bac2023-01-17 14:38:08 +0000911 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900912 private final QosCallbackTracker mQosCallbackTracker;
913 private final NetworkNotificationManager mNotifier;
914 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900915
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700916 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800917 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700918
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900919 // Sequence number for NetworkProvider IDs.
920 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
921 NetworkProvider.FIRST_PROVIDER_ID);
922
Erik Klineedf878b2015-07-09 18:24:03 +0900923 // NetworkRequest activity String log entries.
924 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
925 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
926
Hugo Benichid159fdd2016-07-11 11:05:12 +0900927 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900928 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900929 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
930
Hugo Benichi47011212017-03-30 10:46:05 +0900931 private static final int MAX_WAKELOCK_LOGS = 20;
932 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900933 private int mTotalWakelockAcquisitions = 0;
934 private int mTotalWakelockReleases = 0;
935 private long mTotalWakelockDurationMs = 0;
936 private long mMaxWakelockDurationMs = 0;
937 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900938
Hugo Benichi208c0102016-07-28 17:53:06 +0900939 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900940
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700941 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900942 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700943
Erik Kline95ecfee2016-10-02 18:02:14 +0900944 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900945 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900946
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900947 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800948 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
949 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800950
Patrick Rohr2857ac42022-01-21 14:58:16 +0100951 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
952 // configured via {@link
953 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
954 // Only the handler thread is allowed to access this field.
955 private long mIngressRateLimit = -1;
956
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900957 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
958 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900959 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900960 @GuardedBy("mSelfCertifiedCapabilityCache")
961 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
962 mSelfCertifiedCapabilityCache = new HashMap<>();
963
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900964 // Flag to enable the feature of closing frozen app sockets.
965 private final boolean mDestroyFrozenSockets;
966
967 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
968 private final boolean mDelayDestroyFrozenSockets;
969
970 // Uids that ConnectivityService is pending to close sockets of.
971 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
972
Robert Greenwalt802c1102014-06-02 15:32:02 -0700973 /**
974 * Implements support for the legacy "one network per network type" model.
975 *
976 * We used to have a static array of NetworkStateTrackers, one for each
977 * network type, but that doesn't work any more now that we can have,
978 * for example, more that one wifi network. This class stores all the
979 * NetworkAgentInfo objects that support a given type, but the legacy
980 * API will only see the first one.
981 *
982 * It serves two main purposes:
983 *
984 * 1. Provide information about "the network for a given type" (since this
985 * API only supports one).
986 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
987 * the first network for a given type changes, or if the default network
988 * changes.
989 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900990 @VisibleForTesting
991 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900992
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900993 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900994 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900995
Robert Greenwalt802c1102014-06-02 15:32:02 -0700996 /**
997 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
998 * Each list holds references to all NetworkAgentInfos that are used to
999 * satisfy requests for that network type.
1000 *
1001 * This array is built out at startup such that an unsupported network
1002 * doesn't get an ArrayList instance, making this a tristate:
1003 * unsupported, supported but not active and active.
1004 *
1005 * The actual lists are populated when we scan the network types that
1006 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001007 *
1008 * Threading model:
1009 * - addSupportedType() is only called in the constructor
1010 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1011 * They are therefore not thread-safe with respect to each other.
1012 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1013 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001014 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001015 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001016 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001017 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001018 @NonNull
1019 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001020
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001021 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1022 // an entry have no timer (equivalent to -1). Lazily loaded.
1023 @NonNull
1024 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1025
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001026 LegacyTypeTracker(@NonNull ConnectivityService service) {
1027 mService = service;
1028 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001029 }
1030
Chiachang Wang3bc52762021-11-25 14:17:57 +08001031 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1032 // addressed.
1033 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001034 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1035 final PackageManager pm = ctx.getPackageManager();
1036 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1037 addSupportedType(TYPE_WIFI);
1038 }
1039 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1040 addSupportedType(TYPE_WIFI_P2P);
1041 }
1042 if (tm.isDataCapable()) {
1043 // Telephony does not have granular support for these types: they are either all
1044 // supported, or none is supported
1045 addSupportedType(TYPE_MOBILE);
1046 addSupportedType(TYPE_MOBILE_MMS);
1047 addSupportedType(TYPE_MOBILE_SUPL);
1048 addSupportedType(TYPE_MOBILE_DUN);
1049 addSupportedType(TYPE_MOBILE_HIPRI);
1050 addSupportedType(TYPE_MOBILE_FOTA);
1051 addSupportedType(TYPE_MOBILE_IMS);
1052 addSupportedType(TYPE_MOBILE_CBS);
1053 addSupportedType(TYPE_MOBILE_IA);
1054 addSupportedType(TYPE_MOBILE_EMERGENCY);
1055 }
1056 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1057 addSupportedType(TYPE_BLUETOOTH);
1058 }
1059 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1060 // TYPE_PROXY is only used on Wear
1061 addSupportedType(TYPE_PROXY);
1062 }
1063 // Ethernet is often not specified in the configs, although many devices can use it via
1064 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001065 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001066 addSupportedType(TYPE_ETHERNET);
1067 }
1068
1069 // Always add TYPE_VPN as a supported type
1070 addSupportedType(TYPE_VPN);
1071 }
1072
1073 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001074 if (mTypeLists[type] != null) {
1075 throw new IllegalStateException(
1076 "legacy list for type " + type + "already initialized");
1077 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001078 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001079 }
1080
Robert Greenwalt802c1102014-06-02 15:32:02 -07001081 public boolean isTypeSupported(int type) {
1082 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1083 }
1084
1085 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001086 synchronized (mTypeLists) {
1087 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1088 return mTypeLists[type].get(0);
1089 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001090 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001091 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001092 }
1093
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001094 public int getRestoreTimerForType(int type) {
1095 synchronized (mTypeLists) {
1096 if (mRestoreTimers == null) {
1097 mRestoreTimers = loadRestoreTimers();
1098 }
1099 return mRestoreTimers.getOrDefault(type, -1);
1100 }
1101 }
1102
1103 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1104 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001105 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001106 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1107 for (final String config : configs) {
1108 final String[] splits = TextUtils.split(config, ",");
1109 if (splits.length != 2) {
1110 logwtf("Invalid restore timer token count: " + config);
1111 continue;
1112 }
1113 try {
1114 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1115 } catch (NumberFormatException e) {
1116 logwtf("Invalid restore timer number format: " + config, e);
1117 }
1118 }
1119 return ret;
1120 }
1121
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001122 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001123 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001124 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001125 log("Sending " + state
1126 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001127 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001128 }
1129 }
1130
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001131 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1132 // network type, to preserve previous behaviour.
1133 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1134 if (vpnNai != mService.getLegacyLockdownNai()) return;
1135
1136 if (vpnNai.declaredUnderlyingNetworks == null
1137 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1138 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1139 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1140 return;
1141 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001142 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001143 vpnNai.declaredUnderlyingNetworks[0]);
1144 if (underlyingNai == null) return;
1145
1146 final int type = underlyingNai.networkInfo.getType();
1147 final DetailedState state = DetailedState.CONNECTED;
1148 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1149 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1150 }
1151
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001152 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001153 public void add(int type, NetworkAgentInfo nai) {
1154 if (!isTypeSupported(type)) {
1155 return; // Invalid network type.
1156 }
1157 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1158
1159 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1160 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001161 return;
1162 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001163 synchronized (mTypeLists) {
1164 list.add(nai);
1165 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001166
Chalard Jean5b409c72021-02-04 13:12:59 +09001167 // Send a broadcast if this is the first network of its type or if it's the default.
1168 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001169
1170 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1171 // to preserve previous behaviour.
1172 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001173 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001174 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1175 mService.sendLegacyNetworkBroadcast(nai, state, type);
1176 }
1177
1178 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1179 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001180 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001181 }
1182
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001183 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001184 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001185 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1186 if (list == null || list.isEmpty()) {
1187 return;
1188 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001189 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001190
Hugo Benichi389633f2016-06-21 09:48:07 +09001191 synchronized (mTypeLists) {
1192 if (!list.remove(nai)) {
1193 return;
1194 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001195 }
1196
Lorenzo Colitti49767722015-05-01 00:30:10 +09001197 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001198 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1199 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001200 }
1201
1202 if (!list.isEmpty() && wasFirstNetwork) {
1203 if (DBG) log("Other network available for type " + type +
1204 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001205 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001206 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001207 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001208 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001209 }
1210 }
1211
1212 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001213 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1214 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001215 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001216 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001217 }
1218 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001219
Chalard Jean46bfbf02022-02-02 00:56:25 +09001220 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001221 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001222 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001223 final DetailedState state = nai.networkInfo.getDetailedState();
1224 for (int type = 0; type < mTypeLists.length; type++) {
1225 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001226 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001227 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001228 if (isFirst || contains && isDefault) {
1229 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001230 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001231 }
1232 }
1233 }
1234
Robert Greenwalt94e22142014-07-30 16:31:24 -07001235 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001236 pw.println("mLegacyTypeTracker:");
1237 pw.increaseIndent();
1238 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001239 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001240 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001241 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001242 pw.println();
1243 pw.println("Current state:");
1244 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001245 synchronized (mTypeLists) {
1246 for (int type = 0; type < mTypeLists.length; type++) {
1247 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1248 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001249 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001250 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001251 }
1252 }
1253 pw.decreaseIndent();
1254 pw.decreaseIndent();
1255 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001256 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001257 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001258 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001259
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001260 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001261 /**
1262 * Helper class which parses out priority arguments and dumps sections according to their
1263 * priority. If priority arguments are omitted, function calls the legacy dump command.
1264 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001265 private class LocalPriorityDump {
1266 private static final String PRIORITY_ARG = "--dump-priority";
1267 private static final String PRIORITY_ARG_HIGH = "HIGH";
1268 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001269 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001270
1271 LocalPriorityDump() {}
1272
1273 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Laif8dba342023-10-12 17:01:03 +08001274 if (!HandlerUtils.runWithScissors(mHandler, () -> {
1275 doDump(fd, pw, new String[]{DIAG_ARG});
1276 doDump(fd, pw, new String[]{SHORT_ARG});
1277 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1278 pw.println("dumpHigh timeout");
1279 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001280 }
1281
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001282 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Laif8dba342023-10-12 17:01:03 +08001283 if (!HandlerUtils.runWithScissors(mHandler, () -> doDump(fd, pw, args),
1284 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1285 pw.println("dumpNormal timeout");
1286 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001287 }
1288
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001289 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1290 if (args == null) {
1291 dumpNormal(fd, pw, args);
1292 return;
1293 }
1294
1295 String priority = null;
1296 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1297 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1298 argIndex++;
1299 priority = args[argIndex];
1300 }
1301 }
1302
1303 if (PRIORITY_ARG_HIGH.equals(priority)) {
1304 dumpHigh(fd, pw);
1305 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1306 dumpNormal(fd, pw, args);
1307 } else {
1308 // ConnectivityService publishes binder service using publishBinderService() with
1309 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001310 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1311 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001312 // TODO: Integrate into signal dump.
1313 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001314 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001315 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001316 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001317
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001318 /**
1319 * Dependencies of ConnectivityService, for injection in tests.
1320 */
1321 @VisibleForTesting
1322 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001323 public int getCallingUid() {
1324 return Binder.getCallingUid();
1325 }
1326
Chalard Jeandf29a852023-05-29 17:02:43 +09001327 public boolean isAtLeastS() {
1328 return SdkLevel.isAtLeastS();
1329 }
1330
1331 public boolean isAtLeastT() {
1332 return SdkLevel.isAtLeastT();
1333 }
1334
1335 public boolean isAtLeastU() {
1336 return SdkLevel.isAtLeastU();
1337 }
1338
Chalard Jeaneb663892023-10-07 15:17:07 +09001339 public boolean isAtLeastV() {
1340 return SdkLevel.isAtLeastV();
1341 }
1342
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001343 /**
1344 * Get system properties to use in ConnectivityService.
1345 */
1346 public MockableSystemProperties getSystemProperties() {
1347 return new MockableSystemProperties();
1348 }
1349
1350 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001351 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1352 */
1353 public ConnectivityResources getResources(@NonNull Context ctx) {
1354 return new ConnectivityResources(ctx);
1355 }
1356
1357 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001358 * Create a HandlerThread to use in ConnectivityService.
1359 */
1360 public HandlerThread makeHandlerThread() {
1361 return new HandlerThread("ConnectivityServiceThread");
1362 }
1363
1364 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001365 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001366 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001367 public NetworkStackClientBase getNetworkStack() {
1368 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001369 }
1370
1371 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001372 * @see ProxyTracker
1373 */
1374 public ProxyTracker makeProxyTracker(@NonNull Context context,
1375 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001376 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001377 }
1378
1379 /**
1380 * @see NetIdManager
1381 */
1382 public NetIdManager makeNetIdManager() {
1383 return new NetIdManager();
1384 }
1385
1386 /**
1387 * @see NetworkUtils#queryUserAccess(int, int)
1388 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001389 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1390 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001391 }
1392
1393 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001394 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1395 * requires CAP_NET_ADMIN, which the unit tests do not have.
1396 */
1397 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1398 InetSocketAddress remote) {
1399 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1400 }
1401
1402 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001403 * @see MultinetworkPolicyTracker
1404 */
1405 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1406 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1407 return new MultinetworkPolicyTracker(c, h, r);
1408 }
1409
Aaron Huang330a4c02020-10-27 03:36:19 +08001410 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001411 * @see AutomaticOnOffKeepaliveTracker
1412 */
1413 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1414 @NonNull Context c, @NonNull Handler h) {
1415 return new AutomaticOnOffKeepaliveTracker(c, h);
1416 }
1417
1418 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001419 * @see BatteryStatsManager
1420 */
1421 public void reportNetworkInterfaceForTransports(Context context, String iface,
1422 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001423 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001424 context.getSystemService(BatteryStatsManager.class);
1425 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1426 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001427
1428 public boolean getCellular464XlatEnabled() {
1429 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1430 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001431
1432 /**
1433 * @see PendingIntent#intentFilterEquals
1434 */
1435 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1436 return a.intentFilterEquals(b);
1437 }
1438
1439 /**
1440 * @see LocationPermissionChecker
1441 */
1442 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1443 return new LocationPermissionChecker(context);
1444 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001445
1446 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001447 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001448 *
1449 * This method returns null in versions before T, where carrier privilege
1450 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001451 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001452 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001453 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1454 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001455 if (isAtLeastT()) {
Chalard Jean84dfa9f2023-01-30 11:23:20 +09001456 return new CarrierPrivilegeAuthenticator(context, this, tm);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001457 } else {
1458 return null;
1459 }
1460 }
1461
1462 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001463 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001464 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001465 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001466 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001467 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001468
1469 /**
1470 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001471 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001472 * @return BpfNetMaps implementation.
1473 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001474 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1475 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001476 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001477
1478 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001479 * @see ClatCoordinator
1480 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001481 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001482 public ClatCoordinator getClatCoordinator(INetd netd) {
1483 return new ClatCoordinator(
1484 new ClatCoordinator.Dependencies() {
1485 @NonNull
1486 public INetd getNetd() {
1487 return netd;
1488 }
1489 });
1490 }
1491
1492 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001493 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1494 */
1495 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1496 final InterfaceParams params = InterfaceParams.getByName(iface);
1497 if (params == null) {
1498 // the interface might have disappeared.
1499 logw("Failed to get interface params for interface " + iface);
1500 return;
1501 }
1502 try {
1503 // converting rateInBytesPerSecond from long to int is safe here because the
1504 // setting's range is limited to INT_MAX.
1505 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001506 Log.i(TAG,
1507 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001508 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1509 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1510 } catch (IOException e) {
1511 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1512 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1513 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1514 + ") failure: ", e);
1515 }
1516 }
1517
1518 /**
1519 * Wraps {@link TcUtils#tcFilterDelDev}
1520 */
1521 public void disableIngressRateLimit(String iface) {
1522 final InterfaceParams params = InterfaceParams.getByName(iface);
1523 if (params == null) {
1524 // the interface might have disappeared.
1525 logw("Failed to get interface params for interface " + iface);
1526 return;
1527 }
1528 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001529 Log.i(TAG,
1530 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001531 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1532 } catch (IOException e) {
1533 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1534 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1535 }
1536 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001537
1538 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001539 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1540 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001541 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001542 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001543 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001544 }
1545
1546 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001547 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1548 */
1549 // TODO: when available in all active branches:
1550 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1551 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1552 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1553 return BroadcastOptionsShimImpl.newInstance(options);
1554 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001555
1556 /**
1557 * Wrapper method for
1558 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1559 *
1560 * @param changeId The ID of the compatibility change in question.
1561 * @param packageName The package name of the app in question.
1562 * @param user The user that the operation is done for.
1563 * @return {@code true} if the change is enabled for the specified package.
1564 */
1565 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1566 @NonNull final UserHandle user) {
1567 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1568 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001569
1570 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001571 * As above but with a UID.
1572 * @see CompatChanges#isChangeEnabled(long, int)
1573 */
1574 public boolean isChangeEnabled(final long changeId, final int uid) {
1575 return CompatChanges.isChangeEnabled(changeId, uid);
1576 }
1577
1578 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001579 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1580 *
1581 * @param ranges target uid ranges
1582 * @param exemptUids uids to skip close socket
1583 */
1584 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1585 @NonNull final Set<Integer> exemptUids)
1586 throws SocketException, InterruptedIOException, ErrnoException {
1587 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1588 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001589
1590 /**
1591 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1592 *
1593 * @param ownerUids target uids to close sockets
1594 */
1595 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1596 throws SocketException, InterruptedIOException, ErrnoException {
1597 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1598 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001599
1600 /**
1601 * Schedule the evaluation timeout.
1602 *
1603 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1604 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1605 * of these events happen, this time will run out, after which the network is considered
1606 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1607 * on this network and considers it won't provide connectivity. In particular, that means
1608 * it's when the system prefers it to cell if it's wifi and configuration says it should
1609 * prefer bad wifi to cell.
1610 */
1611 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1612 @NonNull final Network network, final long delayMs) {
1613 handler.sendMessageDelayed(
1614 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1615 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001616 }
1617
junyulaie7c7d2a2021-01-26 15:29:15 +08001618 public ConnectivityService(Context context) {
1619 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001620 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1621 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001622 }
1623
1624 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001625 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1626 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001627 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001628
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001629 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001630 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001631 mSystemProperties = mDeps.getSystemProperties();
1632 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001633 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001634 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001635 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1636 // Pass limit - 1 to maintain backward compatibility.
1637 // TODO: Remove the workaround.
1638 mNetworkRequestCounter =
1639 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1640 mSystemNetworkRequestCounter =
1641 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001642
Hugo Benichi208c0102016-07-28 17:53:06 +09001643 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001644 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1645 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001646 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001647 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001648 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001649 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1650 mDefaultNetworkRequests.add(mDefaultRequest);
1651 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001652
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001653 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001654 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001655
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001656 // The default WiFi request is a background request so that apps using WiFi are
1657 // migrated to a better network (typically ethernet) when one comes up, instead
1658 // of staying on WiFi forever.
1659 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1660 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1661
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001662 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1663 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1664 NetworkRequest.Type.BACKGROUND_REQUEST);
1665
Chalard Jean0702f982021-09-16 21:50:07 +09001666 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1667 // TODO: Consider making the timer customizable.
1668 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1669 mCellularRadioTimesharingCapable =
1670 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1671
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001672 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1673 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1674
1675 if (SdkLevel.isAtLeastU()) {
1676 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1677 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1678 final int defaultUMarkMask = 0x80000000; // u32
1679
1680 if ((mark == 0) || (mask == 0)) {
1681 // simply treat unset/disabled as the default U value
1682 mark = defaultUMarkMask;
1683 mask = defaultUMarkMask;
1684 }
1685 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1686 // invalid device overlay settings
1687 throw new IllegalArgumentException(
1688 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1689 }
1690 }
1691
1692 mWakeUpMark = mark;
1693 mWakeUpMask = mask;
1694
Paul Hu51f816b2022-08-11 14:43:47 +00001695 mNetd = netd;
1696 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001697 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001698 mPermissionMonitor =
1699 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001700 mHandlerThread.start();
1701 mHandler = new InternalHandler(mHandlerThread.getLooper());
1702 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001703 mConnectivityDiagnosticsHandler =
1704 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001705
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001706 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001707 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001708
junyulaie7c7d2a2021-01-26 15:29:15 +08001709 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001710 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001711 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001712 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001713
Wink Saville32506bc2013-06-29 21:10:57 -07001714 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001715 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001716 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001717 mCarrierPrivilegeAuthenticator =
1718 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001719
Sudheer Shanka9967d462021-03-18 19:09:25 +00001720 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001721 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1722 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001723 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001724
1725 final PowerManager powerManager = (PowerManager) context.getSystemService(
1726 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001727 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001728 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001729
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001730 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1731 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001732 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001733 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001734 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001735 mProtectedNetworks.add(p);
1736 } else {
1737 if (DBG) loge("Ignoring protectedNetwork " + p);
1738 }
1739 }
1740
soma, kawata29444ae2019-05-23 09:30:40 +09001741 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1742
James Mattis02220e22021-03-13 19:27:21 -08001743 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001744 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001745 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001746 final IntentFilter userIntentFilter = new IntentFilter();
1747 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1748 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1749 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1750 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001751
James Mattis02220e22021-03-13 19:27:21 -08001752 // Listen to package add/removes for netd
1753 final IntentFilter packageIntentFilter = new IntentFilter();
1754 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1755 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1756 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1757 packageIntentFilter.addDataScheme("package");
1758 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001759 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001760
Motomu Utsumi1e51a642023-07-18 15:11:41 +09001761 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001762
Chalard Jean46bfbf02022-02-02 00:56:25 +09001763 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001764 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001765 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001766 } catch (RemoteException | ServiceSpecificException e) {
1767 loge("Error registering event listener :" + e);
1768 }
1769
Erik Kline05f2b402015-04-30 12:58:40 +09001770 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1771 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001772
chiachangwang7c17c282023-02-02 05:58:59 +00001773 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001774 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001775 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001776
1777 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001778 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001779 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1780 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001781 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001782 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1783 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001784
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001785 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001786 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001787 mNetworkRanker =
1788 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1789
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001790 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001791
Chiachang Wangc1215d32020-10-20 15:38:58 +08001792 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001793 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001794
Chalard Jean28018572020-12-21 18:36:52 +09001795 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1796 // request that doesn't allow fallback to the default network. It should never be visible
1797 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1798 // arguments like the handler or the DnsResolver.
1799 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001800 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001801 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001802 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001803 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001804 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001805 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1806 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001807
1808 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001809 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1810 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1811 // Even if it could, running on S would at least require mocking out the BPF map,
1812 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1813 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001814 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001815 mDscpPolicyTracker = new DscpPolicyTracker();
1816 }
Tyler Wear72388212021-09-09 14:49:02 -07001817 } catch (ErrnoException e) {
1818 loge("Unable to create DscpPolicyTracker");
1819 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001820
1821 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1822 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001823
Chalard Jeandf29a852023-05-29 17:02:43 +09001824 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001825 mCdmps = new CompanionDeviceManagerProxyService(context);
1826 } else {
1827 mCdmps = null;
1828 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001829
Chalard Jean2fb66f12023-08-25 12:50:37 +09001830 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
1831
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001832 mDestroyFrozenSockets = mDeps.isAtLeastU()
1833 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1834 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1835 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
1836 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001837 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1838 new UidFrozenStateChangedCallback() {
1839 @Override
1840 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1841 if (uids.length != frozenStates.length) {
1842 Log.wtf(TAG, "uids has length " + uids.length
1843 + " but frozenStates has length " + frozenStates.length);
1844 return;
1845 }
1846
1847 final UidFrozenStateChangedArgs args =
1848 new UidFrozenStateChangedArgs(uids, frozenStates);
1849
1850 mHandler.sendMessage(
1851 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1852 }
1853 };
1854
1855 final ActivityManager activityManager =
1856 mContext.getSystemService(ActivityManager.class);
1857 activityManager.registerUidFrozenStateChangedCallback(
1858 (Runnable r) -> r.run(), frozenStateChangedCallback);
1859 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001860 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001861
Xiao Ma0a171c02022-01-23 16:14:51 +00001862 /**
1863 * Check whether or not the device supports Ethernet transport.
1864 */
1865 public static boolean deviceSupportsEthernet(final Context context) {
1866 final PackageManager pm = context.getPackageManager();
1867 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1868 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1869 }
1870
Chalard Jean46adcf32018-04-18 20:18:38 +09001871 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001872 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1873 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001874 }
1875
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001876 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1877 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001878 final NetworkCapabilities netCap = new NetworkCapabilities();
1879 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001880 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001881 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001882 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001883 return netCap;
1884 }
1885
James Mattis45d81842021-01-10 14:24:24 -08001886 private NetworkRequest createDefaultRequest() {
1887 return createDefaultInternetRequestForTransport(
1888 TYPE_NONE, NetworkRequest.Type.REQUEST);
1889 }
1890
lucaslin3ba7cc22022-12-19 02:35:33 +00001891 private NetworkRequest createVpnRequest() {
1892 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1893 .withoutDefaultCapabilities()
1894 .addTransportType(TRANSPORT_VPN)
1895 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1896 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1897 .build();
1898 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1899 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1900 }
1901
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001902 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001903 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001904 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001905 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001906 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001907 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001908 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001909 netCap.addTransportType(transportType);
1910 }
James Mattis45d81842021-01-10 14:24:24 -08001911 return createNetworkRequest(type, netCap);
1912 }
1913
1914 private NetworkRequest createNetworkRequest(
1915 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001916 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001917 }
1918
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001919 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1920 NetworkRequest.Type type) {
1921 final NetworkCapabilities netCap = new NetworkCapabilities();
1922 netCap.clearAll();
1923 netCap.addCapability(capability);
1924 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1925 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1926 }
1927
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001928 // Used only for testing.
1929 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001930 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001931 // changing ContentResolver to make registerContentObserver non-final).
1932 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1933 // by subclassing SettingsObserver.
1934 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001935 void updateAlwaysOnNetworks() {
1936 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001937 }
1938
Erik Kline9a62f012018-03-21 07:18:33 -07001939 // See FakeSettingsProvider comment above.
1940 @VisibleForTesting
1941 void updatePrivateDnsSettings() {
1942 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1943 }
1944
paulhu51f77dc2021-06-07 02:34:20 +00001945 @VisibleForTesting
1946 void updateMobileDataPreferredUids() {
1947 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1948 }
1949
Patrick Rohr2857ac42022-01-21 14:58:16 +01001950 @VisibleForTesting
1951 void updateIngressRateLimit() {
1952 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1953 }
1954
Aaron Huang40b52442021-06-08 04:34:24 +08001955 @VisibleForTesting
1956 void simulateUpdateProxyInfo(@Nullable final Network network,
1957 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001958 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08001959 new Pair<>(network, proxyInfo)).sendToTarget();
1960 }
1961
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001962 private void handleAlwaysOnNetworkRequest(
1963 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001964 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001965 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001966 handleAlwaysOnNetworkRequest(networkRequest, enable);
1967 }
1968
1969 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001970 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001971 if (enable == isEnabled) {
1972 return; // Nothing to do.
1973 }
1974
1975 if (enable) {
1976 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001977 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001978 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001979 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001980 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001981 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1982 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001983 }
1984 }
1985
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001986 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001987 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1988 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1989 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1990 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001991 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1992 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001993 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001994 }
1995
paulhu51f77dc2021-06-07 02:34:20 +00001996 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001997 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001998 private void registerSettingsCallbacks() {
1999 // Watch for global HTTP proxy changes.
2000 mSettingsObserver.observe(
2001 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2002 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2003
Chalard Jean46bfbf02022-02-02 00:56:25 +09002004 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002005 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002006 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002007 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2008
Chalard Jean46bfbf02022-02-02 00:56:25 +09002009 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002010 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002011 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002012 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002013
2014 // Watch for mobile data preferred uids changes.
2015 mSettingsObserver.observe(
2016 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2017 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002018
2019 // Watch for ingress rate limit changes.
2020 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002021 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002022 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2023 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002024 }
2025
Erik Kline31b4a9e2018-01-11 21:07:29 +09002026 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002027 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2028 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002029 }
2030 }
2031
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002032 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002033 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2034 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002035 return mNextNetworkRequestId++;
2036 }
2037
junyulai74f9a8b2018-06-13 15:00:37 +08002038 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002039 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002040 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002041 if (network == null) {
2042 return null;
2043 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002044 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002045 }
2046
2047 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002048 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002049 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002050 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002051 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002052
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002053 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002054 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002055 private NetworkAgentInfo getVpnForUid(int uid) {
2056 synchronized (mNetworkForNetId) {
2057 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2058 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002059 if (nai.isVPN() && nai.everConnected()
2060 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002061 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002062 }
2063 }
2064 }
2065 return null;
2066 }
2067
Chalard Jean46bfbf02022-02-02 00:56:25 +09002068 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002069 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002070 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002071 final NetworkAgentInfo nai = getVpnForUid(uid);
2072 if (nai != null) return nai.declaredUnderlyingNetworks;
2073 return null;
2074 }
2075
Lorenzo Colittia7574052021-01-19 01:33:05 +09002076 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002077 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002078
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002079 final Network[] networks = getVpnUnderlyingNetworks(uid);
2080 if (networks != null) {
2081 // getUnderlyingNetworks() returns:
2082 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2083 // empty array => the VPN explicitly said "no default network".
2084 // non-empty array => the VPN specified one or more default networks; we use the
2085 // first one.
2086 if (networks.length > 0) {
2087 nai = getNetworkAgentInfoForNetwork(networks[0]);
2088 } else {
2089 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002090 }
2091 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002092 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002093 }
2094
2095 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002096 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002097 */
paulhu7aeba372020-12-30 00:42:19 +08002098 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2099 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002100 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002101 if (ignoreBlocked) {
2102 return false;
2103 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002104 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002105 final long ident = Binder.clearCallingIdentity();
2106 try {
2107 final boolean metered = nc == null ? true : nc.isMetered();
2108 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2109 } finally {
2110 Binder.restoreCallingIdentity(ident);
2111 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002112 }
2113
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002114 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002115 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2116 return;
2117 }
Hugo Benichi47011212017-03-30 10:46:05 +09002118 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002119 synchronized (mBlockedAppUids) {
2120 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002121 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002122 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002123 blocked = false;
2124 } else {
2125 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002126 }
2127 }
Hugo Benichi47011212017-03-30 10:46:05 +09002128 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2129 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2130 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002131 }
2132
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002133 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002134 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2135 return;
2136 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002137 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002138 final int requestId = nri.getActiveRequest() != null
2139 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002140 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002141 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002142 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002143 }
2144
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002145 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002146 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002147 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002148 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002149 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002150 @NonNull
2151 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2152 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002153 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2154 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2155 // but only exists if an app asks about them or requests them. Ensure the requesting app
2156 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002157 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002158 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2159 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2160 null /* extraInfo */);
2161 }
2162 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002163 return filtered;
2164 }
2165
2166 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2167 boolean ignoreBlocked) {
2168 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2169 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002170 }
2171
2172 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002173 * Return NetworkInfo for the active (i.e., connected) network interface.
2174 * It is assumed that at most one network is active at a time. If more
2175 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002176 * @return the info for the active network, or {@code null} if none is
2177 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002178 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002179 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002180 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002181 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002182 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002183 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002184 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2185 if (nai == null) return null;
2186 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2187 maybeLogBlockedNetworkInfo(networkInfo, uid);
2188 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002189 }
2190
Paul Jensen1f567382015-02-13 14:18:39 -05002191 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002192 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002193 public Network getActiveNetwork() {
2194 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002195 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002196 }
2197
2198 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002199 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002200 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002201 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002202 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002203 }
2204
Chalard Jean46bfbf02022-02-02 00:56:25 +09002205 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002206 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002207 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2208 if (vpnNai != null) {
2209 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2210 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2211 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002212 }
Paul Jensen1f567382015-02-13 14:18:39 -05002213 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002214
James Mattis2516da32021-01-31 17:06:19 -08002215 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002216 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2217 ignoreBlocked)) {
2218 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002219 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002220 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002221 }
2222
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002223 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002224 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002225 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002226 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002227 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2228 if (nai == null) return null;
2229 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002230 }
2231
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002232 /** Returns a NetworkInfo object for a network that doesn't exist. */
2233 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2234 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2235 getNetworkTypeName(networkType), "" /* subtypeName */);
2236 info.setIsAvailable(true);
2237 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2238 // background data is restricted.
2239 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2240 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2241 ? DetailedState.BLOCKED
2242 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002243 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2244 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002245 return info;
2246 }
2247
Lorenzo Colittia7574052021-01-19 01:33:05 +09002248 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002249 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2250 return null;
2251 }
2252 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002253 if (nai == null) {
2254 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002255 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002256 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2257 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002258 }
2259
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002260 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002261 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002262 public NetworkInfo getNetworkInfo(int networkType) {
2263 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002264 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002265 if (getVpnUnderlyingNetworks(uid) != null) {
2266 // A VPN is active, so we may need to return one of its underlying networks. This
2267 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002268 // getNetworkAgentInfoForUid.
2269 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2270 if (nai == null) return null;
2271 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2272 if (networkInfo.getType() == networkType) {
2273 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002274 }
2275 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002276 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002277 }
2278
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002279 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002280 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002281 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002282 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002283 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002284 if (nai == null) return null;
2285 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002286 }
2287
2288 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002289 public NetworkInfo[] getAllNetworkInfo() {
2290 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002291 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002292 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2293 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002294 NetworkInfo info = getNetworkInfo(networkType);
2295 if (info != null) {
2296 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002297 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002298 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002299 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002300 }
2301
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002302 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002303 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002304 public Network getNetworkForType(int networkType) {
2305 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002306 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2307 return null;
2308 }
2309 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2310 if (nai == null) {
2311 return null;
2312 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002313 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002314 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2315 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002316 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002317 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002318 }
2319
2320 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002321 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002322 public Network[] getAllNetworks() {
2323 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002324 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002325 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002326 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002327 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002328 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002329 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002330 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002331 }
2332
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002333 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002334 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002335 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002336 // The basic principle is: if an app's traffic could possibly go over a
2337 // network, without the app doing anything multinetwork-specific,
2338 // (hence, by "default"), then include that network's capabilities in
2339 // the array.
2340 //
2341 // In the normal case, app traffic only goes over the system's default
2342 // network connection, so that's the only network returned.
2343 //
2344 // With a VPN in force, some app traffic may go into the VPN, and thus
2345 // over whatever underlying networks the VPN specifies, while other app
2346 // traffic may go over the system default network (e.g.: a split-tunnel
2347 // VPN, or an app disallowed by the VPN), so the set of networks
2348 // returned includes the VPN's underlying networks and the system
2349 // default.
2350 enforceAccessPermission();
2351
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002352 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002353
James Mattis2516da32021-01-31 17:06:19 -08002354 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2355 if (!nri.isBeingSatisfied()) {
2356 continue;
2357 }
2358 final NetworkAgentInfo nai = nri.getSatisfier();
2359 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2360 if (null != nc
2361 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2362 && !result.containsKey(nai.network)) {
2363 result.put(
2364 nai.network,
2365 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002366 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002367 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2368 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002369 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002370 }
2371
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002372 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002373 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002374 if (null != networks) {
2375 for (final Network network : networks) {
2376 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2377 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002378 result.put(
2379 network,
2380 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002381 nc,
2382 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002383 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002384 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002385 }
2386 }
2387 }
2388
2389 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2390 out = result.values().toArray(out);
2391 return out;
2392 }
2393
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002394 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2395 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2396 // can call sampleConnectivityState and make the checks on it.
2397 @NonNull
2398 private StatsEvent sampleConnectivityStateToStatsEvent() {
2399 final ConnectivityStateSample sample = sampleConnectivityState();
2400 return ConnectivityStatsLog.buildStatsEvent(
2401 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2402 sample.getNetworkCountPerTransports().toByteArray(),
2403 sample.getConnectionDurationPerTransports().toByteArray(),
2404 sample.getNetworkRequestCount().toByteArray(),
2405 sample.getNetworks().toByteArray());
2406 }
2407
2408 /**
2409 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2410 *
2411 * This is used for metrics. These snapshots will be sampled and constitute a base for
2412 * statistics about connectivity state of devices.
2413 */
2414 @VisibleForTesting
2415 @NonNull
2416 public ConnectivityStateSample sampleConnectivityState() {
2417 ensureRunningOnConnectivityServiceThread();
2418 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2419 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2420 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2421 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2422 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2423 return builder.build();
2424 }
2425
2426 private static NetworkCountPerTransports sampleNetworkCount(
2427 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2428 final SparseIntArray countPerTransports = new SparseIntArray();
2429 for (final NetworkAgentInfo nai : nais) {
2430 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2431 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2432 }
2433 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2434 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2435 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2436 c.setTransportTypes(countPerTransports.keyAt(i));
2437 c.setNetworkCount(countPerTransports.valueAt(i));
2438 builder.addNetworkCountForTransports(c);
2439 }
2440 return builder.build();
2441 }
2442
2443 private static ConnectionDurationPerTransports sampleConnectionDuration(
2444 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2445 final ConnectionDurationPerTransports.Builder builder =
2446 ConnectionDurationPerTransports.newBuilder();
2447 for (final NetworkAgentInfo nai : nais) {
2448 final ConnectionDurationForTransports.Builder c =
2449 ConnectionDurationForTransports.newBuilder();
2450 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2451 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2452 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2453 // Add millisPerSecond/2 to round up or down to the nearest value
2454 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2455 builder.addConnectionDurationForTransports(c);
2456 }
2457 return builder.build();
2458 }
2459
2460 private static NetworkRequestCount sampleNetworkRequestCount(
2461 @NonNull final Collection<NetworkRequestInfo> nris) {
2462 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2463 final SparseIntArray countPerType = new SparseIntArray();
2464 for (final NetworkRequestInfo nri : nris) {
2465 final int type;
2466 if (Process.SYSTEM_UID == nri.mAsUid) {
2467 // The request is filed "as" the system, so it's the system on its own behalf.
2468 type = RequestType.RT_SYSTEM.getNumber();
2469 } else if (Process.SYSTEM_UID == nri.mUid) {
2470 // The request is filed by the system as some other app, so it's the system on
2471 // behalf of an app.
2472 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2473 } else {
2474 // Not the system, so it's an app requesting on its own behalf.
2475 type = RequestType.RT_APP.getNumber();
2476 }
2477 countPerType.put(type, countPerType.get(type, 0));
2478 }
2479 for (int i = countPerType.size() - 1; i >= 0; --i) {
2480 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2481 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2482 r.setRequestCount(countPerType.valueAt(i));
2483 builder.addRequestCountForType(r);
2484 }
2485 return builder.build();
2486 }
2487
2488 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2489 final NetworkList.Builder builder = NetworkList.newBuilder();
2490 for (final NetworkAgentInfo nai : nais) {
2491 final NetworkCapabilities nc = nai.networkCapabilities;
2492 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2493 d.setTransportTypes((int) nc.getTransportTypesInternal());
2494 final MeteredState meteredState;
2495 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2496 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2497 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2498 meteredState = MeteredState.METERED_NO;
2499 } else {
2500 meteredState = MeteredState.METERED_YES;
2501 }
2502 d.setMeteredState(meteredState);
2503 final ValidatedState validatedState;
2504 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2505 validatedState = ValidatedState.VS_PORTAL;
2506 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2507 validatedState = ValidatedState.VS_PARTIAL;
2508 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2509 validatedState = ValidatedState.VS_VALID;
2510 } else {
2511 validatedState = ValidatedState.VS_INVALID;
2512 }
2513 d.setValidatedState(validatedState);
2514 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2515 d.setCapabilities(nc.getCapabilitiesInternal());
2516 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2517 builder.addNetworkDescription(d);
2518 }
2519 return builder.build();
2520 }
2521
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002522 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002523 public boolean isNetworkSupported(int networkType) {
2524 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002525 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002526 }
2527
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002528 /**
2529 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002530 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002531 * @return the ip properties for the active network, or {@code null} if
2532 * none is active
2533 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002534 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002535 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002536 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002537 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002538 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2539 if (nai == null) return null;
2540 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002541 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002542 }
2543
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002544 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002545 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002546 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002547 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002548 final LinkProperties lp = getLinkProperties(nai);
2549 if (lp == null) return null;
2550 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002551 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002552 }
2553
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002554 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002555 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002556 public LinkProperties getLinkProperties(Network network) {
2557 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002558 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2559 if (lp == null) return null;
2560 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002561 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002562 }
2563
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002564 @Nullable
2565 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002566 if (nai == null) {
2567 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002568 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002569 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002570 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002571 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002572 }
2573
lucaslinc582d502022-01-27 09:07:00 +08002574 @Override
2575 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002576 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002577 @NonNull String packageName, @Nullable String callingAttributionTag) {
2578 Objects.requireNonNull(packageName);
2579 Objects.requireNonNull(lp);
2580 enforceNetworkStackOrSettingsPermission();
2581 if (!checkAccessPermission(-1 /* pid */, uid)) {
2582 return null;
2583 }
2584 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2585 }
2586
Qingxi Lib2748102020-01-08 12:51:49 -08002587 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2588 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2589 }
2590
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002591 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002592 if (nai == null) return null;
2593 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002594 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002595 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002596 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002597 }
2598
2599 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002600 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2601 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002602 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002603 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002604 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002605 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002606 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002607 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002608 }
2609
lucaslinc582d502022-01-27 09:07:00 +08002610 @Override
lucaslind2b06132022-03-02 10:56:57 +08002611 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2612 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2613 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002614 Objects.requireNonNull(nc);
2615 Objects.requireNonNull(packageName);
2616 enforceNetworkStackOrSettingsPermission();
2617 if (!checkAccessPermission(-1 /* pid */, uid)) {
2618 return null;
2619 }
2620 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2621 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2622 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2623 callingAttributionTag);
2624 }
2625
lucaslin69e1aa92022-03-22 18:15:09 +08002626 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2627 if (nc.getUnderlyingNetworks() != null
2628 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2629 nc.setUnderlyingNetworks(null);
2630 }
2631 }
2632
Qingxi Libb8da982020-01-17 17:54:27 -08002633 @VisibleForTesting
2634 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002635 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002636 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2637 // this would be expensive (one more permission check every time any NC callback is
2638 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2639 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2640 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002641 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002642 if (!checkSettingsPermission(callerPid, callerUid)) {
2643 newNc.setUids(null);
2644 newNc.setSSID(null);
2645 }
Etan Cohen107ae952018-12-30 17:59:59 -08002646 if (newNc.getNetworkSpecifier() != null) {
2647 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2648 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002649 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2650 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002651 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2652 newNc.setAdministratorUids(new int[0]);
2653 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002654 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002655 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002656 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002657 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002658 }
lucaslin69e1aa92022-03-22 18:15:09 +08002659 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002660
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002661 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002662 }
2663
Roshan Pius98f59ec2021-02-23 08:47:39 -08002664 /**
2665 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002666 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002667 * NetworkCapabilities.
2668 * Note: This wrapper does not support any sort of invalidation and thus must not be
2669 * persistent or long-lived. It may only be used for the time necessary to
2670 * compute the redactions required by one particular NetworkCallback or
2671 * synchronous call.
2672 */
2673 private class RedactionPermissionChecker {
2674 private final int mCallingPid;
2675 private final int mCallingUid;
2676 @NonNull private final String mCallingPackageName;
2677 @Nullable private final String mCallingAttributionTag;
2678
2679 private Boolean mHasLocationPermission = null;
2680 private Boolean mHasLocalMacAddressPermission = null;
2681 private Boolean mHasSettingsPermission = null;
2682
2683 RedactionPermissionChecker(int callingPid, int callingUid,
2684 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2685 mCallingPid = callingPid;
2686 mCallingUid = callingUid;
2687 mCallingPackageName = callingPackageName;
2688 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002689 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002690
2691 private boolean hasLocationPermissionInternal() {
2692 final long token = Binder.clearCallingIdentity();
2693 try {
2694 return mLocationPermissionChecker.checkLocationPermission(
2695 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2696 null /* message */);
2697 } finally {
2698 Binder.restoreCallingIdentity(token);
2699 }
2700 }
2701
2702 /**
2703 * Returns whether the app holds location permission or not (might return cached result
2704 * if the permission was already checked before).
2705 */
2706 public boolean hasLocationPermission() {
2707 if (mHasLocationPermission == null) {
2708 // If there is no cached result, perform the check now.
2709 mHasLocationPermission = hasLocationPermissionInternal();
2710 }
2711 return mHasLocationPermission;
2712 }
2713
2714 /**
2715 * Returns whether the app holds local mac address permission or not (might return cached
2716 * result if the permission was already checked before).
2717 */
2718 public boolean hasLocalMacAddressPermission() {
2719 if (mHasLocalMacAddressPermission == null) {
2720 // If there is no cached result, perform the check now.
2721 mHasLocalMacAddressPermission =
2722 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2723 }
2724 return mHasLocalMacAddressPermission;
2725 }
2726
2727 /**
2728 * Returns whether the app holds settings permission or not (might return cached
2729 * result if the permission was already checked before).
2730 */
2731 public boolean hasSettingsPermission() {
2732 if (mHasSettingsPermission == null) {
2733 // If there is no cached result, perform the check now.
2734 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2735 }
2736 return mHasSettingsPermission;
2737 }
2738 }
2739
2740 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2741 @NetworkCapabilities.NetCapability long redaction) {
2742 return (redactions & redaction) != 0;
2743 }
2744
2745 /**
2746 * Use the provided |applicableRedactions| to check the receiving app's
2747 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2748 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2749 * before being sent to the corresponding app.
2750 */
2751 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2752 @NetworkCapabilities.RedactionType long applicableRedactions,
2753 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2754 boolean includeLocationSensitiveInfo) {
2755 long redactions = applicableRedactions;
2756 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2757 if (includeLocationSensitiveInfo
2758 && redactionPermissionChecker.hasLocationPermission()) {
2759 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2760 }
2761 }
2762 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2763 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2764 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2765 }
2766 }
2767 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2768 if (redactionPermissionChecker.hasSettingsPermission()) {
2769 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2770 }
2771 }
2772 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002773 }
2774
Qingxi Lib2748102020-01-08 12:51:49 -08002775 @VisibleForTesting
2776 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002777 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002778 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002779 int callingPid, int callingUid, @NonNull String callingPkgName,
2780 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002781 if (nc == null) {
2782 return null;
2783 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002784 // Avoid doing location permission check if the transport info has no location sensitive
2785 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002786 final RedactionPermissionChecker redactionPermissionChecker =
2787 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2788 callingAttributionTag);
2789 final long redactions = retrieveRequiredRedactions(
2790 nc.getApplicableRedactions(), redactionPermissionChecker,
2791 includeLocationSensitiveInfo);
2792 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002793 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002794 // TODO : calling UID is redacted because apps should generally not know what UID is
2795 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002796 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002797 newNc.setOwnerUid(INVALID_UID);
2798 return newNc;
2799 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002800 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2801 if (nc.hasTransport(TRANSPORT_VPN)) {
2802 // Owner UIDs already checked above. No need to re-check.
2803 return newNc;
2804 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002805 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2806 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002807 // compatibility for older apps.
2808 if (!includeLocationSensitiveInfo
2809 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002810 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002811 newNc.setOwnerUid(INVALID_UID);
2812 return newNc;
2813 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002814 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002815 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002816 newNc.setOwnerUid(INVALID_UID);
2817 }
Qingxi Lib2748102020-01-08 12:51:49 -08002818 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002819 }
2820
lucaslinc582d502022-01-27 09:07:00 +08002821 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002822 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2823 LinkProperties lp, int callerPid, int callerUid) {
2824 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002825 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2826 // this would be expensive (one more permission check every time any LP callback is
2827 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2828 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2829 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002830
2831 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2832 final boolean needsSanitization =
2833 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2834 if (!needsSanitization) {
2835 return new LinkProperties(lp);
2836 }
2837
2838 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002839 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002840 }
2841
2842 final LinkProperties newLp = new LinkProperties(lp);
2843 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2844 // object gets parceled.
2845 newLp.setCaptivePortalApiUrl(null);
2846 newLp.setCaptivePortalData(null);
2847 return newLp;
2848 }
2849
Roshan Pius08c94fb2020-01-16 12:17:17 -08002850 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2851 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002852 // There is no need to track the effective UID of the request here. If the caller
2853 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002854 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002855 // Unprivileged apps can only pass in null or their own UID.
2856 if (nc.getUids() == null) {
2857 // If the caller passes in null, the callback will also match networks that do not
2858 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2859 // In this case, redact everything in the request immediately. This ensures that the
2860 // app is not able to get any redacted information by filing an unredacted request
2861 // and observing whether the request matches something.
2862 if (nc.getNetworkSpecifier() != null) {
2863 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2864 }
2865 } else {
2866 nc.setSingleUid(callerUid);
2867 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002868 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002869 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002870 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002871
2872 // Clear owner UID; this can never come from an app.
2873 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002874 }
2875
Chalard Jean38354d12018-03-20 19:13:57 +09002876 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002877 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002878 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2879 }
2880 }
2881
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002882 @Override
2883 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2884 enforceAccessPermission();
2885 final int callerUid = Binder.getCallingUid();
2886 final long token = Binder.clearCallingIdentity();
2887 try {
2888 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2889 } finally {
2890 Binder.restoreCallingIdentity(token);
2891 }
2892 }
2893
junyulaiebd15162021-03-03 12:09:05 +08002894 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002895 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002896 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002897 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002898 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002899
Serik Beketayev05130302021-01-15 16:47:25 -08002900 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002901 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002902 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2903 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002904 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002905 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002906 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002907 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2908 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002909 }
2910 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002911 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002912 }
2913
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002914 @Override
junyulaiebd15162021-03-03 12:09:05 +08002915 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002916 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002917 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002918 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002919
2920 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2921 for (Network network : getAllNetworks()) {
2922 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002923 final boolean includeNetwork = (nai != null) && nai.isCreated();
2924 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002925 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2926 // NetworkCapabilities, which may contain UIDs of apps to which the
2927 // network applies. Should the UIDs be cleared so as not to leak or
2928 // interfere ?
2929 result.add(nai.getNetworkStateSnapshot());
2930 }
2931 }
2932 return result;
2933 }
2934
2935 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002936 public boolean isActiveNetworkMetered() {
2937 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002938
Qingxi Lib2748102020-01-08 12:51:49 -08002939 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002940 if (caps != null) {
2941 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2942 } else {
2943 // Always return the most conservative value
2944 return true;
2945 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002946 }
2947
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002948 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002949 * Ensures that the system cannot call a particular method.
2950 */
2951 private boolean disallowedBecauseSystemCaller() {
2952 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002953 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2954 // for devices launched with Q and above. However, existing devices upgrading to Q and
2955 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002956 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002957 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002958 log("This method exists only for app backwards compatibility"
2959 + " and must not be called by system services.");
2960 return true;
2961 }
2962 return false;
2963 }
2964
paulhub2c28682021-08-18 18:35:54 +08002965 private int getAppUid(final String app, final UserHandle user) {
2966 final PackageManager pm =
2967 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2968 final long token = Binder.clearCallingIdentity();
2969 try {
2970 return pm.getPackageUid(app, 0 /* flags */);
2971 } catch (PackageManager.NameNotFoundException e) {
2972 return -1;
2973 } finally {
2974 Binder.restoreCallingIdentity(token);
2975 }
2976 }
2977
2978 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2979 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2980 if (getAppUid(packageName, user) != callingUid) {
2981 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2982 }
2983 }
2984
Lorenzo Colitti23862912018-09-28 11:31:55 +09002985 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002986 * Ensure that a network route exists to deliver traffic to the specified
2987 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002988 * @param networkType the type of the network over which traffic to the
2989 * specified host is to be routed
2990 * @param hostAddress the IP address of the host to which the route is
2991 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002992 * @return {@code true} on success, {@code false} on failure
2993 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002994 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002995 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2996 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002997 if (disallowedBecauseSystemCaller()) {
2998 return false;
2999 }
paulhub2c28682021-08-18 18:35:54 +08003000 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003001 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003002 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003003 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003004 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003005
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003006 InetAddress addr;
3007 try {
3008 addr = InetAddress.getByAddress(hostAddress);
3009 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003010 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003011 return false;
3012 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003013
The Android Open Source Project28527d22009-03-03 19:31:44 -08003014 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003015 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003016 return false;
3017 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003018
3019 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3020 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003021 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003022 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3023 } else {
3024 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3025 }
3026 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003027 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003028
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003029 DetailedState netState;
3030 synchronized (nai) {
3031 netState = nai.networkInfo.getDetailedState();
3032 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003033
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003034 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003035 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003036 log("requestRouteToHostAddress on down network "
3037 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003038 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003039 }
3040 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003041 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003042
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003043 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003044 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003045 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003046 LinkProperties lp;
3047 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003048 synchronized (nai) {
3049 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003050 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003051 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003052 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003053 if (DBG) {
3054 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3055 }
Wink Saville32506bc2013-06-29 21:10:57 -07003056 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003057 } finally {
3058 Binder.restoreCallingIdentity(token);
3059 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003060 }
3061
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003062 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003063 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003064 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003065 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003066 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003067 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003068 if (bestRoute.getGateway().equals(addr)) {
3069 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003070 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003071 } else {
3072 // if we will connect to this through another route, add a direct route
3073 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003074 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003075 }
3076 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003077 if (DBG) log("Adding legacy route " + bestRoute +
3078 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003079
3080 final String dst = bestRoute.getDestinationLinkAddress().toString();
3081 final String nextHop = bestRoute.hasGateway()
3082 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003083 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003084 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3085 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003086 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003087 return false;
3088 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003089 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003090 }
3091
paulhu7c0a2e62021-01-08 00:51:49 +08003092 class DnsResolverUnsolicitedEventCallback extends
3093 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003094 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003095 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003096 try {
3097 mHandler.sendMessage(mHandler.obtainMessage(
3098 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003099 new PrivateDnsValidationUpdate(event.netId,
3100 InetAddresses.parseNumericAddress(event.ipAddress),
3101 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003102 } catch (IllegalArgumentException e) {
3103 loge("Error parsing ip address in validation event");
3104 }
3105 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003106
3107 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003108 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3109 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003110 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3111 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3112 // event callback for certain nai. e.g. cellular. Register here to pass to
3113 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003114 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003115 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3116 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003117 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003118 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003119 }
3120 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003121
3122 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003123 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3124 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3125 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003126 }
dalyk1720e542018-03-05 12:42:22 -05003127
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003128 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003129 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003130 return this.VERSION;
3131 }
3132
3133 @Override
3134 public String getInterfaceHash() {
3135 return this.HASH;
3136 }
paulhu7c0a2e62021-01-08 00:51:49 +08003137 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003138
3139 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003140 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3141 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003142
paulhu7c0a2e62021-01-08 00:51:49 +08003143 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003144 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003145 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003146 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003147 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003148 }
3149 }
3150
Sudheer Shanka9967d462021-03-18 19:09:25 +00003151 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003152 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003153 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003154 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3155 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003156 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003157 };
3158
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003159 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003160 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003161 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003162 }
3163
Mark Fasheh7c999d82023-05-04 20:23:11 +00003164 static final class UidFrozenStateChangedArgs {
3165 final int[] mUids;
3166 final int[] mFrozenStates;
3167
3168 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3169 mUids = uids;
3170 mFrozenStates = frozenStates;
3171 }
3172 }
3173
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003174 /**
3175 * Check if the cell network is idle.
3176 * @return true if the cell network state is idle
3177 * false if the cell network state is active or unknown
3178 */
3179 private boolean isCellNetworkIdle() {
3180 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3181 if (defaultNai == null
3182 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3183 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3184 // cell network is not the default network, cell network state is unknown.
3185 // TODO(b/279380356): Track cell network state when the cell is not the default network
3186 return false;
3187 }
3188
3189 return !mNetworkActivityTracker.isDefaultNetworkActive();
3190 }
3191
Mark Fasheh7c999d82023-05-04 20:23:11 +00003192 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003193 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003194
3195 for (int i = 0; i < uids.length; i++) {
3196 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003197 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003198 } else {
3199 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003200 }
3201 }
3202
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003203 if (ownerUids.isEmpty()) {
3204 return;
3205 }
3206
3207 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3208 // Delay closing sockets to avoid waking the cell modem up.
3209 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3210 // than waking cell modem up.
3211 mPendingFrozenUids.addAll(ownerUids);
3212 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003213 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003214 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003215 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003216 loge("Exception in socket destroy: " + e);
3217 }
3218 }
3219 }
3220
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003221 private void closePendingFrozenSockets() {
3222 ensureRunningOnConnectivityServiceThread();
3223
3224 try {
3225 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3226 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3227 loge("Failed to close pending frozen app sockets: " + e);
3228 }
3229 mPendingFrozenUids.clear();
3230 }
3231
3232 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3233 mNetworkActivityTracker.handleReportNetworkActivity(params);
3234
3235 if (mDelayDestroyFrozenSockets
3236 && params.isActive
3237 && params.label == TRANSPORT_CELLULAR
3238 && !mPendingFrozenUids.isEmpty()) {
3239 closePendingFrozenSockets();
3240 }
3241 }
3242
3243 /**
3244 * If the cellular network is no longer the default network, close pending frozen sockets.
3245 *
3246 * @param newNetwork new default network
3247 * @param oldNetwork old default network
3248 */
3249 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3250 NetworkAgentInfo oldNetwork) {
3251 final boolean isOldNetworkCellular = oldNetwork != null
3252 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3253 final boolean isNewNetworkCellular = newNetwork != null
3254 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3255
3256 if (isOldNetworkCellular
3257 && !isNewNetworkCellular
3258 && !mPendingFrozenUids.isEmpty()) {
3259 closePendingFrozenSockets();
3260 }
3261 }
3262
3263 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3264 pw.println("CloseFrozenAppSockets:");
3265 pw.increaseIndent();
3266 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3267 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3268 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3269 pw.decreaseIndent();
3270 }
3271
Junyu Lai155760b2023-10-05 14:51:00 +08003272 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3273 pw.println("Bpf Program Status:");
3274 pw.increaseIndent();
3275 try {
3276 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003277 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003278 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003279 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003280 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003281 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003282 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003283 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003284 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003285 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003286 } catch (IOException e) {
3287 pw.println(" IOException");
3288 }
3289 pw.decreaseIndent();
3290 }
3291
Mark Fasheh7c999d82023-05-04 20:23:11 +00003292 @VisibleForTesting
3293 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003294 @VisibleForTesting
3295 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3296 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003297
Paul Jensen83f5d572014-08-29 09:54:01 -04003298 private void enforceInternetPermission() {
3299 mContext.enforceCallingOrSelfPermission(
3300 android.Manifest.permission.INTERNET,
3301 "ConnectivityService");
3302 }
3303
The Android Open Source Project28527d22009-03-03 19:31:44 -08003304 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003305 mContext.enforceCallingOrSelfPermission(
3306 android.Manifest.permission.ACCESS_NETWORK_STATE,
3307 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003308 }
3309
lucaslinc582d502022-01-27 09:07:00 +08003310 private boolean checkAccessPermission(int pid, int uid) {
3311 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3312 == PERMISSION_GRANTED;
3313 }
3314
paulhua6ee2122021-02-22 15:40:43 +08003315 /**
3316 * Performs a strict and comprehensive check of whether a calling package is allowed to
3317 * change the state of network, as the condition differs for pre-M, M+, and
3318 * privileged/preinstalled apps. The caller is expected to have either the
3319 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3320 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3321 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3322 * permission and cannot be revoked. See http://b/23597341
3323 *
3324 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3325 * of this app will be updated to the current time.
3326 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003327 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003328 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3329 == PackageManager.PERMISSION_GRANTED) {
3330 return;
3331 }
3332
3333 if (callingPkg == null) {
3334 throw new SecurityException("Calling package name is null.");
3335 }
3336
3337 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3338 final int uid = mDeps.getCallingUid();
3339 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3340 callingPkg, callingAttributionTag, null /* message */);
3341
3342 if (mode == AppOpsManager.MODE_ALLOWED) {
3343 return;
3344 }
3345
3346 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3347 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3348 return;
3349 }
3350
3351 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3352 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3353 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003354 }
3355
Charles He9369e612017-05-15 17:07:18 +01003356 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003357 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003358 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003359 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003360 }
3361
Quang Luong98858d62023-02-11 00:25:24 +00003362 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003363 enforceAnyPermissionOf(mContext,
3364 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003365 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003366 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3367 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3368 }
3369
paulhu8e96a752019-08-12 16:25:11 +08003370 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003371 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003372 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003373 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003374 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003375 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003376 }
3377
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003378 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003379 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003380 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003381 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003382 android.Manifest.permission.NETWORK_SETTINGS,
3383 android.Manifest.permission.NETWORK_FACTORY,
3384 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3385 }
3386
3387 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003388 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003389 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003390 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003391 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3392 android.Manifest.permission.NETWORK_FACTORY,
3393 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3394 }
3395
lucaslin69e1aa92022-03-22 18:15:09 +08003396 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3397 return PERMISSION_GRANTED == mContext.checkPermission(
3398 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3399 || PERMISSION_GRANTED == mContext.checkPermission(
3400 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3401 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003402 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003403 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003404 }
3405
Chalard Jean9a396cc2018-02-21 18:43:54 +09003406 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003407 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003408 android.Manifest.permission.NETWORK_SETTINGS,
3409 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003410 }
3411
3412 private boolean checkSettingsPermission(int pid, int uid) {
3413 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003414 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3415 || PERMISSION_GRANTED == mContext.checkPermission(
3416 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003417 }
3418
paulhu8e96a752019-08-12 16:25:11 +08003419 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003420 enforceNetworkStackPermissionOr(mContext,
3421 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003422 }
3423
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003424 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003425 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003426 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003427 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003428 }
3429
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003430 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003431 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003432 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3433 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003434 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003435 }
3436
James Mattis8378aec2021-01-26 14:05:36 -08003437 private void enforceOemNetworkPreferencesPermission() {
3438 mContext.enforceCallingOrSelfPermission(
3439 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3440 "ConnectivityService");
3441 }
3442
James Mattisfa270db2021-05-31 17:11:10 -07003443 private void enforceManageTestNetworksPermission() {
3444 mContext.enforceCallingOrSelfPermission(
3445 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3446 "ConnectivityService");
3447 }
3448
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003449 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003450 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003451 android.Manifest.permission.NETWORK_STACK,
3452 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003453 }
3454
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003455 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003456 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003457 android.Manifest.permission.NETWORK_STACK,
3458 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3459 }
3460
paulhu1a407652019-03-22 16:35:06 +08003461 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003462 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003463 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003464 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3465 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003466 }
3467
Paul Hu8fc2a552022-05-04 18:44:42 +08003468 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3469 boolean checkUidsAllowedList) {
3470 if (PermissionUtils.checkAnyPermissionOf(mContext,
3471 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3472 return true;
3473 }
3474
3475 // fallback to ConnectivityInternalPermission
3476 // TODO: Remove this fallback check after all apps have declared
3477 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3478 if (PermissionUtils.checkAnyPermissionOf(mContext,
3479 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3480 return true;
3481 }
3482
3483 // Check whether uid is in allowed on restricted networks list.
3484 if (checkUidsAllowedList
3485 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3486 return true;
3487 }
3488 return false;
3489 }
3490
3491 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3492 final int callingUid = mDeps.getCallingUid();
3493 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3494 throw new SecurityException("ConnectivityService: user " + callingUid
3495 + " has no permission to access restricted network.");
3496 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003497 }
3498
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003499 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003500 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003501 }
3502
Roshan Pius98f59ec2021-02-23 08:47:39 -08003503 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3504 return PERMISSION_GRANTED == mContext.checkPermission(
3505 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3506 }
3507
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003508 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003509 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003510 }
3511
3512 private void sendInetConditionBroadcast(NetworkInfo info) {
3513 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3514 }
3515
Wink Saville4f0de1e2011-08-04 15:01:58 -07003516 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003517 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003518 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003519 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003520 if (info.isFailover()) {
3521 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3522 info.setFailover(false);
3523 }
3524 if (info.getReason() != null) {
3525 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3526 }
3527 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003528 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3529 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003530 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003531 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003532 return intent;
3533 }
3534
3535 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3536 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3537 }
3538
Michael Groover73f69482023-01-27 11:01:25 -06003539 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3540 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003541 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3542 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003543 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003544 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003545 if (!mSystemReady
3546 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003547 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003548 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003549 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003550 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003551 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003552 }
3553
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003554 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003555 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003556 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003557 final NetworkInfo ni = intent.getParcelableExtra(
3558 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003559 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3560 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003561 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003562 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003563 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003564 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003565 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003566 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003567 } finally {
3568 Binder.restoreCallingIdentity(ident);
3569 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003570 }
3571 }
3572
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003573 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3574 NetworkInfo info) {
3575 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003576 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003577
3578 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3579 try {
3580 // This allows us to discard older broadcasts still waiting to be delivered
3581 // which have the same namespace and key.
3582 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3583 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3584 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003585 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003586 } catch (UnsupportedApiLevelException e) {
3587 Log.wtf(TAG, "Using unsupported API" + e);
3588 }
3589 }
3590
3591 @VisibleForTesting
3592 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3593 final StringBuilder sb = new StringBuilder();
3594 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3595 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3596 sb.append(info.getExtraInfo());
3597 return sb.toString();
3598 }
3599
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003600 /**
Aaron Huang96011892020-06-27 07:18:23 +08003601 * Called by SystemServer through ConnectivityManager when the system is ready.
3602 */
3603 @Override
3604 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003605 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003606 throw new SecurityException("Calling Uid is not system uid.");
3607 }
3608 systemReadyInternal();
3609 }
3610
3611 /**
3612 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003613 */
3614 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003615 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003616 // Load flags after PackageManager is ready to query module version
3617 mFlags.loadFlags(mDeps, mContext);
3618
Aaron Huang9a57acf2020-12-08 10:03:29 +08003619 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3620 // listening network request which is sent by MultipathPolicyTracker won't be added
3621 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3622 // be called after PermissionMonitor#startMonitoring().
3623 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3624 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3625 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003626 final ConditionVariable startMonitoringDone = new ConditionVariable();
3627 mHandler.post(() -> {
3628 mPermissionMonitor.startMonitoring();
3629 startMonitoringDone.open();
3630 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003631 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003632 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003633
Hugo Benichie5220992017-04-26 14:53:28 +09003634 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003635 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003636 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003637 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003638 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003639 }
3640 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003641
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003642 // Create network requests for always-on networks.
3643 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003644
3645 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003646 // Note that updating can be skipped here if the list is empty only because no uid
3647 // rules are applied before system ready. Normally, the empty uid list means to clear
3648 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003649 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3650 updateMobileDataPreferredUids();
3651 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003652
3653 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003654 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003655 mBpfNetMaps.setPullAtomCallback(mContext);
3656 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003657 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3658 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003659 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3660 // have permission problem. While CV#block() is unbounded in time and can in principle block
3661 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3662 // could have blocked forever too.
3663 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003664 }
3665
The Android Open Source Project28527d22009-03-03 19:31:44 -08003666 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003667 * Start listening for default data network activity state changes.
3668 */
3669 @Override
3670 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003671 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003672 }
3673
3674 /**
3675 * Stop listening for default data network activity state changes.
3676 */
3677 @Override
3678 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003679 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003680 }
3681
3682 /**
3683 * Check whether the default network radio is currently active.
3684 */
3685 @Override
3686 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003687 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003688 }
3689
3690 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003691 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003692 * and set it on it's iface.
3693 */
Junyu Lai970963e2022-10-25 15:46:47 +08003694 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003695 final String iface = newLp.getInterfaceName();
3696 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003697 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003698 // Silently ignore unset MTU value.
3699 return;
3700 }
Hansen Kurli04252032022-12-07 11:21:49 +00003701 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3702 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3703 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003704 return;
3705 }
Hansen Kurli04252032022-12-07 11:21:49 +00003706 // Cannot set MTU without interface name
3707 if (TextUtils.isEmpty(iface)) {
3708 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003709 return;
3710 }
sy.yun4aa73922013-09-02 05:24:09 +09003711
Hansen Kurli04252032022-12-07 11:21:49 +00003712 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3713 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003714 return;
3715 }
3716
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003717 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003718 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003719 mNetd.interfaceSetMtu(iface, mtu);
3720 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003721 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003722 }
3723 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003724
Chenbo Feng15416292018-11-08 17:36:21 -08003725 @VisibleForTesting
3726 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003727
Junyu Lai970963e2022-10-25 15:46:47 +08003728 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003729 String[] values = null;
3730 if (tcpBufferSizes != null) {
3731 values = tcpBufferSizes.split(",");
3732 }
3733
3734 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003735 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003736 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3737 values = tcpBufferSizes.split(",");
3738 }
3739
3740 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3741
3742 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003743 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003744
Chenbo Feng15416292018-11-08 17:36:21 -08003745 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3746 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3747 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003748 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003749 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003750 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003751 }
3752 }
3753
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003754 @Override
3755 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003756 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003757 NETWORK_RESTORE_DELAY_PROP_NAME);
3758 if(restoreDefaultNetworkDelayStr != null &&
3759 restoreDefaultNetworkDelayStr.length() != 0) {
3760 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003761 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003762 } catch (NumberFormatException e) {
3763 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003764 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003765 // if the system property isn't set, use the value for the apn type
3766 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3767
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003768 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3769 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003770 }
3771 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003772 }
3773
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003774 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003775 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003776 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003777 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003778 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003779 // Start gathering diagnostic information.
3780 netDiags.add(new NetworkDiagnostics(
3781 nai.network,
3782 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003783 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003784 DIAG_TIME_MS));
3785 }
3786
3787 for (NetworkDiagnostics netDiag : netDiags) {
3788 pw.println();
3789 netDiag.waitForMeasurements();
3790 netDiag.dump(pw);
3791 }
3792 }
3793
The Android Open Source Project28527d22009-03-03 19:31:44 -08003794 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003795 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3796 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003797 if (!checkDumpPermission(mContext, TAG, writer)) return;
3798
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003799 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003800 }
3801
lucaslin99473f62020-12-10 15:10:54 +08003802 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3803 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3804 != PackageManager.PERMISSION_GRANTED) {
3805 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003806 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003807 + " due to missing android.permission.DUMP permission");
3808 return false;
3809 } else {
3810 return true;
3811 }
3812 }
3813
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003814 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003815 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003816
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003817 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003818 dumpNetworkDiagnostics(pw);
3819 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003820 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003821 dumpNetworks(pw);
3822 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003823 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003824 dumpNetworkRequests(pw);
3825 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003826 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3827 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3828 dumpTrafficController(pw, fd, verbose);
3829 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003830 }
Erik Kline9647f382015-06-05 17:47:34 +09003831
Junyu Lai0da479b2022-04-20 15:06:29 +08003832 pw.println("NetworkProviders for:");
3833 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003834 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003835 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003836 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003837 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003838 pw.println();
3839
Chalard Jean5b409c72021-02-04 13:12:59 +09003840 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003841 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003842 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003843 pw.println("none");
3844 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003845 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003846 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003847 pw.println();
3848
James Mattis8b298a02021-06-01 22:34:04 -07003849 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003850 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003851 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003852 pw.decreaseIndent();
3853 pw.println();
3854
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003855 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003856 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003857 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003858 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003859 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003860
junyulaif2c67e42018-08-07 19:50:45 +08003861 pw.println("Status for known UIDs:");
3862 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003863 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003864 for (int i = 0; i < size; i++) {
3865 // Don't crash if the array is modified while dumping in bugreports.
3866 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003867 final int uid = mUidBlockedReasons.keyAt(i);
3868 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3869 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003870 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003871 } catch (ArrayIndexOutOfBoundsException e) {
3872 pw.println(" ArrayIndexOutOfBoundsException");
3873 } catch (ConcurrentModificationException e) {
3874 pw.println(" ConcurrentModificationException");
3875 }
3876 }
3877 pw.println();
3878 pw.decreaseIndent();
3879
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003880 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003881 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003882 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003883 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003884 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003885
Junyu Lai0da479b2022-04-20 15:06:29 +08003886 pw.println("Network Offers:");
3887 pw.increaseIndent();
3888 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3889 pw.println(offerInfo.offer);
3890 }
3891 pw.decreaseIndent();
3892 pw.println();
3893
Robert Greenwalt94e22142014-07-30 16:31:24 -07003894 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003895
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003896 pw.println();
markchien5e866652019-09-30 14:40:57 +08003897 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003898
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003899 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003900 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003901
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003902 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003903 dumpCloseFrozenAppSockets(pw);
3904
3905 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08003906 dumpBpfProgramStatus(pw);
3907
3908 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003909
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003910 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003911 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003912 pw.println("mNetworkRequestInfoLogs (most recent first):");
3913 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003914 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003915 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003916
3917 pw.println();
3918 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3919 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003920 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003921 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003922
3923 pw.println();
3924 pw.println("NetTransition WakeLock activity (most recent first):");
3925 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003926 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3927 pw.println("total releases: " + mTotalWakelockReleases);
3928 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3929 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3930 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3931 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3932 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3933 }
James Mattiscb1e0362021-04-06 17:07:42 -07003934 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003935
3936 pw.println();
3937 pw.println("bandwidth update requests (by uid):");
3938 pw.increaseIndent();
3939 synchronized (mBandwidthRequests) {
3940 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3941 pw.println("[" + mBandwidthRequests.keyAt(i)
3942 + "]: " + mBandwidthRequests.valueAt(i));
3943 }
3944 }
3945 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003946 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003947
James Mattiscb1e0362021-04-06 17:07:42 -07003948 pw.println();
3949 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3950 pw.increaseIndent();
3951 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003952 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003953 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003954
3955 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003956
3957 pw.println();
3958 pw.println("Permission Monitor:");
3959 pw.increaseIndent();
3960 mPermissionMonitor.dump(pw);
3961 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003962
3963 pw.println();
3964 pw.println("Legacy network activity:");
3965 pw.increaseIndent();
3966 mNetworkActivityTracker.dump(pw);
3967 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003968 }
3969
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003970 private void dumpNetworks(IndentingPrintWriter pw) {
3971 for (NetworkAgentInfo nai : networksSortedById()) {
3972 pw.println(nai.toString());
3973 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003974 pw.println("Nat464Xlat:");
3975 pw.increaseIndent();
3976 nai.dumpNat464Xlat(pw);
3977 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003978 pw.println(String.format(
3979 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3980 nai.numForegroundNetworkRequests(),
3981 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3982 nai.numBackgroundNetworkRequests(),
3983 nai.numNetworkRequests()));
3984 pw.increaseIndent();
3985 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3986 pw.println(nai.requestAt(i).toString());
3987 }
3988 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003989 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003990 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003991 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003992 pw.decreaseIndent();
3993 pw.decreaseIndent();
3994 }
3995 }
3996
James Mattis8b298a02021-06-01 22:34:04 -07003997 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3998 if (!mProfileNetworkPreferences.isEmpty()) {
3999 pw.println("Profile preferences:");
4000 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004001 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004002 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004003 }
James Mattis8b298a02021-06-01 22:34:04 -07004004 if (!mOemNetworkPreferences.isEmpty()) {
4005 pw.println("OEM preferences:");
4006 pw.increaseIndent();
4007 pw.println(mOemNetworkPreferences);
4008 pw.decreaseIndent();
4009 }
4010 if (!mMobileDataPreferredUids.isEmpty()) {
4011 pw.println("Mobile data preferred UIDs:");
4012 pw.increaseIndent();
4013 pw.println(mMobileDataPreferredUids);
4014 pw.decreaseIndent();
4015 }
James Mattis45d81842021-01-10 14:24:24 -08004016
James Mattis8b298a02021-06-01 22:34:04 -07004017 pw.println("Default requests:");
4018 pw.increaseIndent();
4019 dumpPerAppDefaultRequests(pw);
4020 pw.decreaseIndent();
4021 }
4022
4023 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004024 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4025 if (mDefaultRequest == defaultRequest) {
4026 continue;
4027 }
4028
James Mattis8b298a02021-06-01 22:34:04 -07004029 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4030 final String networkOutput;
4031 if (null == satisfier) {
4032 networkOutput = "null";
4033 } else if (mNoServiceNetwork.equals(satisfier)) {
4034 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004035 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004036 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004037 }
James Mattis8b298a02021-06-01 22:34:04 -07004038 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4039 ? "" : " asUid: " + defaultRequest.mAsUid;
4040 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4041 + defaultRequest.mPid + asUidString + "]";
4042 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4043 + " Preference order: " + defaultRequest.mPreferenceOrder
4044 + " Tracked UIDs: " + defaultRequest.getUids();
4045 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004046 }
4047 }
4048
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004049 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004050 NetworkRequestInfo[] infos = null;
4051 while (infos == null) {
4052 try {
4053 infos = requestsSortedById();
4054 } catch (ConcurrentModificationException e) {
4055 // mNetworkRequests should only be accessed from handler thread, except dump().
4056 // As dump() is never called in normal usage, it would be needlessly expensive
4057 // to lock the collection only for its benefit. Instead, retry getting the
4058 // requests if ConcurrentModificationException is thrown during dump().
4059 }
4060 }
4061 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004062 pw.println(nri.toString());
4063 }
4064 }
4065
Ken Chene6d511f2022-01-25 11:10:42 +08004066 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4067 boolean verbose) {
4068 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004069 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004070 } catch (ServiceSpecificException e) {
4071 pw.println(e.getMessage());
4072 } catch (IOException e) {
4073 loge("Dump BPF maps failed, " + e);
4074 }
4075 }
4076
Chalard Jean524f0b12021-10-25 21:11:56 +09004077 private void dumpAllRequestInfoLogsToLogcat() {
4078 try (PrintWriter logPw = new PrintWriter(new Writer() {
4079 @Override
4080 public void write(final char[] cbuf, final int off, final int len) {
4081 // This method is called with 0-length and 1-length arrays for empty strings
4082 // or strings containing only the DEL character.
4083 if (len <= 1) return;
4084 Log.e(TAG, new String(cbuf, off, len));
4085 }
4086 @Override public void flush() {}
4087 @Override public void close() {}
4088 })) {
4089 mNetworkRequestInfoLogs.dump(logPw);
4090 }
4091 }
4092
Hugo Benichia480ba52018-09-03 08:19:02 +09004093 /**
4094 * Return an array of all current NetworkAgentInfos sorted by network id.
4095 */
4096 private NetworkAgentInfo[] networksSortedById() {
4097 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004098 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004099 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004100 return networks;
4101 }
4102
4103 /**
4104 * Return an array of all current NetworkRequest sorted by request id.
4105 */
James Mattis258ea3c2020-11-15 15:04:40 -08004106 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004107 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004108 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004109 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004110 // Sort the array based off the NRI containing the min requestId in its requests.
4111 Arrays.sort(requests,
4112 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4113 Comparator.comparingInt(req -> req.requestId)).requestId
4114 )
4115 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004116 return requests;
4117 }
4118
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004119 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004120 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004121 if (officialNai != null && officialNai.equals(nai)) return true;
4122 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004123 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004124 " - " + nai);
4125 }
4126 return false;
4127 }
4128
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004129 private boolean isDisconnectRequest(Message msg) {
4130 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4131 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4132 return info.getState() == NetworkInfo.State.DISCONNECTED;
4133 }
4134
Robert Greenwalt2034b912009-08-12 16:08:25 -07004135 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004136 private class NetworkStateTrackerHandler extends Handler {
4137 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004138 super(looper);
4139 }
4140
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004141 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004142 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4143 final NetworkAgentInfo nai = arg.first;
4144 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004145 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004146 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004147 }
4148 return;
4149 }
4150
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004151 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004152 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004153 return;
4154 }
4155
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004156 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004157 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09004158 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
4159 final NetworkCapabilities sanitized =
4160 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004161 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004162 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004163 break;
4164 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004165 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004166 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004167 processLinkPropertiesFromAgent(nai, newLp);
4168 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004169 break;
4170 }
4171 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004172 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004173 updateNetworkInfo(nai, info);
4174 break;
4175 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004176 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4177 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
4178 updateLocalNetworkConfig(nai, config);
4179 break;
4180 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004181 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004182 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004183 break;
4184 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004185 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004186 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004187 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004188 // Note that if the NAI had been connected, this would affect the
4189 // score, and therefore would require re-mixing the score and performing
4190 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004191 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004192 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4193 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004194 // Mark the network as temporarily accepting partial connectivity so that it
4195 // will be validated (and possibly become default) even if it only provides
4196 // partial internet access. Note that if user connects to partial connectivity
4197 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4198 // out of wifi coverage) and if the same wifi is available again, the device
4199 // will auto connect to this wifi even though the wifi has "no internet".
4200 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004201 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004202 break;
4203 }
junyulai011b1f12019-01-03 18:50:15 +08004204 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004205 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004206 break;
4207 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004208 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004209 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004210 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004211
4212 if (isLegacyLockdownNai(nai)
4213 && (underlying == null || underlying.size() != 1)) {
4214 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4215 + " must have exactly one underlying network: " + underlying);
4216 }
4217
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004218 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4219 nai.declaredUnderlyingNetworks = (underlying != null)
4220 ? underlying.toArray(new Network[0]) : null;
4221
4222 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4223 if (DBG) {
4224 log(nai.toShortString() + " changed underlying networks to "
4225 + Arrays.toString(nai.declaredUnderlyingNetworks));
4226 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004227 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004228 notifyIfacesChangedForNetworkStats();
4229 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004230 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004231 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004232 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4233 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4234 nai.teardownDelayMs = msg.arg1;
4235 } else {
4236 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4237 }
Chalard Jean550b5212021-03-05 23:07:53 +09004238 break;
4239 }
4240 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4241 nai.setLingerDuration((int) arg.second);
4242 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004243 }
Tyler Wear72388212021-09-09 14:49:02 -07004244 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4245 DscpPolicy policy = (DscpPolicy) arg.second;
4246 if (mDscpPolicyTracker != null) {
4247 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4248 }
4249 break;
4250 }
4251 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4252 if (mDscpPolicyTracker != null) {
4253 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4254 }
4255 break;
4256 }
4257 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4258 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004259 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004260 }
4261 break;
4262 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004263 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004264 if (!nai.everConnected()) {
4265 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4266 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004267 teardownUnneededNetwork(nai);
4268 break;
4269 }
4270
4271 if (nai.isDestroyed()) {
4272 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4273 + ", ignoring");
4274 break;
4275 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004276
4277 final int timeoutMs = (int) arg.second;
4278 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4279 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4280 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4281 }
4282
4283 // Marking a network awaiting replacement is used to ensure that any requests
4284 // satisfied by the network do not switch to another network until a
4285 // replacement is available or the wait for a replacement times out.
4286 // If the network is inactive (i.e., nascent or lingering), then there are no
4287 // such requests, and there is no point keeping it. Just tear it down.
4288 // Note that setLingerDuration(0) cannot be used to do this because the network
4289 // could be nascent.
4290 nai.clearInactivityState();
4291 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4292 Log.d(TAG, nai.toShortString()
4293 + " marked awaiting replacement is unneeded, tearing down instead");
4294 teardownUnneededNetwork(nai);
4295 break;
4296 }
4297
4298 Log.d(TAG, "Marking " + nai.toShortString()
4299 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4300 destroyNativeNetwork(nai);
4301
4302 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4303 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4304 // consider the fact that the network could already have disconnected or been
4305 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4306 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4307 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4308 mKeepaliveTracker.handleStopAllKeepalives(nai,
4309 SocketKeepalive.ERROR_INVALID_NETWORK);
4310
4311 nai.updateScoreForNetworkAgentUpdate();
4312 // This rematch is almost certainly not going to result in any changes, because
4313 // the destroyed flag is only just above the "current satisfier wins"
4314 // tie-breaker. But technically anything that affects scoring should rematch.
4315 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004316 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004317 break;
4318 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004319 }
4320 }
4321
4322 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004323 final int netId = msg.arg2;
4324 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004325 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004326 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004327 switch (msg.what) {
4328 default:
4329 return false;
lucasline117e2e2019-10-22 18:27:33 +08004330 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004331 if (nai == null) {
4332 break;
4333 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004334 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4335 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004336 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004337 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004338 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004339 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004340 if (probePrivateDnsCompleted) {
4341 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4342 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004343 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004344 }
4345 // Only show the notification when the private DNS is broken and the
4346 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004347 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004348 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4349 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004350 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004351 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4352 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4353 // private DNS is broken, it means this network is being reevaluated.
4354 // Either probing private DNS is not necessary any more or it hasn't been
4355 // done yet. In either case, the networkCapabilities should be updated to
4356 // reflect the new status.
4357 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004358 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004359 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004360 }
4361 break;
4362 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004363 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004364 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4365
Erik Kline31b4a9e2018-01-11 21:07:29 +09004366 if (nai == null) break;
4367
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004368 handleNetworkTested(nai, results.mTestResult,
4369 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004370 break;
4371 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004372 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004373 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004374 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004375 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004376 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004377 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004378 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4379 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004380 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004381 if (nai == null) {
4382 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4383 break;
4384 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004385 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004386 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004387 (PendingIntent) msg.obj,
4388 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004389 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004390 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004391 break;
4392 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004393 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004394 if (nai == null) break;
4395
Erik Kline9a62f012018-03-21 07:18:33 -07004396 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004397 break;
4398 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004399 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004400 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004401 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004402 break;
4403 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004404 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004405 return true;
4406 }
4407
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004408 private void handleNetworkTested(
4409 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004410 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4411 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004412 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004413
4414 // If there is any kind of working networking, then the NAI has been evaluated
4415 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4416 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004417 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004418 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004419 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4420 // any callback that receives onAvailable for that rematch receives an extra caps
4421 // callback. To prevent that, update the score in the agent so the updates below won't
4422 // see an update to both caps and score at the same time.
4423 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004424 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4425
he_won.hwang881307a2022-03-15 21:23:52 +09004426 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4427 // Assume the validation failure is due to a temporary failure after roaming
4428 // and ignore it. NetworkMonitor will continue to retry validation. If it
4429 // continues to fail after the block timeout expires, the network will be
4430 // marked unvalidated. If it succeeds, then validation state will not change.
4431 return;
4432 }
4433
Chalard Jean254bd162022-08-25 13:04:51 +09004434 final boolean wasValidated = nai.isValidated();
4435 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004436 final boolean wasPortal = nai.captivePortalDetected();
4437 nai.setPartialConnectivity(partial);
4438 nai.setCaptivePortalDetected(portal);
4439 nai.updateScoreForNetworkAgentUpdate();
4440 final boolean partialConnectivityChanged = (wasPartial != partial);
4441 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004442
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004443 if (DBG) {
4444 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4445 ? " with redirect to " + redirectUrl
4446 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004447 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004448 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004449 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004450 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004451 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004452 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004453 if (valid) {
4454 handleFreshlyValidatedNetwork(nai);
4455 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4456 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004457 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004458 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004459 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004460 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004461 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004462 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004463 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004464 NotificationType.PRIVATE_DNS_BROKEN);
4465 // If network becomes valid, the hasShownBroken should be reset for
4466 // that network so that the notification will be fired when the private
4467 // DNS is broken again.
4468 nai.networkAgentConfig.hasShownBroken = false;
4469 }
4470 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004471 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004472 } else if (portalChanged) {
4473 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004474 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004475 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4476 nai.onPreventAutomaticReconnect();
4477 teardownUnneededNetwork(nai);
4478 return;
4479 } else {
4480 updateCapabilitiesForNetwork(nai);
4481 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004482 } else if (becameEvaluated) {
4483 // If valid or partial connectivity changed, updateCapabilities* has
4484 // done the rematch.
4485 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004486 }
4487 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004488
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004489 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004490 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004491 nai.onValidationStatusChanged(
4492 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4493 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004494
4495 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004496 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004497 // immediately. Re-notify partial connectivity silently if no internet
4498 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004499 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004500 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004501 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4502 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004503 }
4504
Chalard Jean254bd162022-08-25 13:04:51 +09004505 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004506 handleNetworkUnvalidated(nai);
4507 }
4508 }
4509
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004510 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4511 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4512 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4513 // Do not avoid captive portal when network is wear proxy.
4514 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4515 }
4516
Calvin Ondada1452016-10-11 15:10:46 -07004517 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004518 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4519 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004520 }
4521
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004522 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4523 switch (msg.what) {
4524 default:
4525 return false;
4526 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4527 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4528 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4529 handleLingerComplete(nai);
4530 }
4531 break;
4532 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004533 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4534 handleNetworkAgentRegistered(msg);
4535 break;
4536 }
4537 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4538 handleNetworkAgentDisconnected(msg);
4539 break;
4540 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004541 }
4542 return true;
4543 }
4544
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004545 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004546 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004547 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004548 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004549 maybeHandleNetworkAgentMessage(msg);
4550 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004551 }
4552 }
4553
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004554 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004555 private final int mNetId;
4556 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004557
4558 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004559 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004560 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004561 }
4562
4563 @Override
4564 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4565 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004566 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004567 }
4568
4569 @Override
4570 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004571 // Legacy version of notifyNetworkTestedWithExtras.
4572 // Would only be called if the system has a NetworkStack module older than the
4573 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004574 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004575 }
4576
4577 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004578 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004579 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4580 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004581 final Message msg = mTrackerHandler.obtainMessage(
4582 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004583 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004584 new NetworkTestedResults(
4585 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004586 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004587
4588 // Invoke ConnectivityReport generation for this Network test event.
4589 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4590 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004591
Cody Kestingf1120be2020-08-03 18:01:40 -07004592 // NetworkMonitor reports the network validation result as a bitmask while
4593 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4594 // logical value for ConnectivityDiagnostics.
4595 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4596 p.result);
4597
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004598 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004599 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004600 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4601 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4602
Aaron Huang959d3642021-01-21 15:47:41 +08004603 ConnectivityReportEvent reportEvent =
4604 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4605 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004606 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004607 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004608 }
4609
4610 @Override
4611 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4612 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4613 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004614 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004615 }
4616
4617 @Override
lucasline117e2e2019-10-22 18:27:33 +08004618 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4619 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4620 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004621 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004622 }
4623
4624 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004625 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4626 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4627 EVENT_CAPPORT_DATA_CHANGED,
4628 0, mNetId, data));
4629 }
4630
4631 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004632 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004633 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004634 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004635
4636 final PendingIntent pendingIntent;
4637 // Only the system server can register notifications with package "android"
4638 final long token = Binder.clearCallingIdentity();
4639 try {
paulhu7746e4e2020-06-09 19:07:03 +08004640 pendingIntent = PendingIntent.getBroadcast(
4641 mContext,
4642 0 /* requestCode */,
4643 intent,
4644 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004645 } finally {
4646 Binder.restoreCallingIdentity(token);
4647 }
4648 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4649 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004650 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004651 }
4652
4653 @Override
4654 public void hideProvisioningNotification() {
4655 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004656 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004657 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004658
4659 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004660 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004661 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004662 }
4663
4664 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004665 public int getInterfaceVersion() {
4666 return this.VERSION;
4667 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004668
4669 @Override
4670 public String getInterfaceHash() {
4671 return this.HASH;
4672 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004673 }
4674
Cody Kestingf1120be2020-08-03 18:01:40 -07004675 /**
4676 * Converts the given NetworkMonitor-specific validation result bitmask to a
4677 * ConnectivityDiagnostics-specific validation result int.
4678 */
4679 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4680 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4681 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4682 }
4683 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4684 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4685 }
4686 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4687 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4688 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4689 }
4690
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004691 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004692 log("Data stall detected with methods: " + p.detectionMethod);
4693
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004694 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004695 int detectionMethod = 0;
4696 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4697 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4698 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4699 }
4700 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4701 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4702 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4703 p.tcpMetricsCollectionPeriodMillis);
4704 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004705 }
4706
Cody Kestingf53a0752020-04-15 12:33:28 -07004707 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004708 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004709 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004710
4711 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4712 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4713 // the cost of going through two handlers.
4714 mConnectivityDiagnosticsHandler.sendMessage(msg);
4715 }
4716
Cody Kestingb37958e2020-05-15 10:36:01 -07004717 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4718 return (p.detectionMethod & detectionMethod) != 0;
4719 }
4720
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004721 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4722 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004723 }
4724
Erik Klinea73af002018-06-26 18:53:43 +09004725 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4726 if (nai == null) return;
4727 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4728 // in order to restart a validation pass from within netd.
4729 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4730 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004731 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004732 }
4733 }
4734
Erik Kline31b4a9e2018-01-11 21:07:29 +09004735 private void handlePrivateDnsSettingsChanged() {
4736 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4737
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004738 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004739 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004740 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004741 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4742 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004743 }
4744 }
4745
Erik Kline9a62f012018-03-21 07:18:33 -07004746 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4747 // Private DNS only ever applies to networks that might provide
4748 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004749 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004750
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004751 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004752 // schedule DNS resolutions. If a DNS resolution is required the
4753 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004754 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004755
4756 // With Private DNS bypass support, we can proceed to update the
4757 // Private DNS config immediately, even if we're in strict mode
4758 // and have not yet resolved the provider name into a set of IPs.
4759 updatePrivateDns(nai, cfg);
4760 }
4761
4762 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4763 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004764 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004765 }
4766
dalyk1720e542018-03-05 12:42:22 -05004767 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4768 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4769 if (nai == null) {
4770 return;
4771 }
4772 mDnsManager.updatePrivateDnsValidation(update);
4773 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4774 }
4775
paulhu7c0a2e62021-01-08 00:51:49 +08004776 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004777 int prefixLength) {
4778 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4779 if (nai == null) return;
4780
paulhu7c0a2e62021-01-08 00:51:49 +08004781 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4782 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004783
4784 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004785 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004786 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004787 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004788 prefixLength);
4789 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004790 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004791 return;
4792 }
4793 }
4794
Lorenzo Colittid523d142020-04-01 20:16:30 +09004795 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004796 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4797 }
4798
Hai Shalome58bdc62021-01-11 18:45:34 -08004799 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004800 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004801 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004802 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4803 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4804 }
4805
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004806 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004807 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004808 * @param nai the agent info to update
4809 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004810 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004811 */
junyulai2b6f0c22021-02-03 20:15:30 +08004812 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4813 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4814 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004815 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004816 // one lingered request, set inactive.
4817 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004818 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004819 if (DBG) log("Unsetting inactive " + nai.toShortString());
4820 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004821 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004822 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004823 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004824 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4825 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004826 }
junyulai2b6f0c22021-02-03 20:15:30 +08004827 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004828 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004829 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004830 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004831 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004832 }
4833
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004834 private void handleNetworkAgentRegistered(Message msg) {
4835 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4836 if (!mNetworkAgentInfos.contains(nai)) {
4837 return;
4838 }
4839
4840 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4841 if (VDBG) log("NetworkAgent registered");
4842 } else {
4843 loge("Error connecting NetworkAgent");
4844 mNetworkAgentInfos.remove(nai);
4845 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004846 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004847 synchronized (mNetworkForNetId) {
4848 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004849 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004850 mNetIdManager.releaseNetId(nai.network.getNetId());
4851 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004852 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004853 }
4854 }
4855 }
Paul Jensend5f53392014-11-25 15:26:53 -05004856
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004857 @VisibleForTesting
4858 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09004859 // The feature of creating the networks immediately was slated for U, but race conditions
4860 // detected late required this was flagged off.
4861 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4862 // in NetworkAgentTest.
4863 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004864 }
4865
4866 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4867 @NonNull NetworkInfo.State state) {
4868 if (nai.isCreated()) return false;
4869 if (state == NetworkInfo.State.CONNECTED) return true;
4870 if (state != NetworkInfo.State.CONNECTING) {
4871 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09004872 if (shouldCreateNetworksImmediately()) {
4873 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4874 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004875 return false;
4876 }
4877 return nai.isVPN() || shouldCreateNetworksImmediately();
4878 }
4879
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004880 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004881 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004882 }
4883
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004884 @VisibleForTesting
4885 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004886 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004887 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004888
4889 // If the network never roamed, return false. The check below is not sufficient if time
4890 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4891 if (nai.lastRoamTime == 0) return false;
4892
he_won.hwang881307a2022-03-15 21:23:52 +09004893 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4894 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004895 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004896 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004897 final long currentTimeMs = SystemClock.elapsedRealtime();
4898 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004899 if (timeSinceLastRoam <= blockTimeOut) {
4900 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4901 return true;
4902 }
4903 }
4904 return false;
4905 }
4906
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004907 private void handleNetworkAgentDisconnected(Message msg) {
4908 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004909 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004910 }
4911
Chalard Jeand9fffc32018-05-11 20:19:20 +09004912 // Destroys a network, remove references to it from the internal state managed by
4913 // ConnectivityService, free its interfaces and clean up.
4914 // Must be called on the Handler thread.
4915 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004916 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004917
4918 if (!mNetworkAgentInfos.contains(nai)) return;
4919
Chalard Jeand9fffc32018-05-11 20:19:20 +09004920 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004921 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004922 }
lucaslinb25c9a62019-02-12 15:30:13 +08004923 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004924 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004925 // A network agent has disconnected.
4926 // TODO - if we move the logic to the network agent (have them disconnect
4927 // because they lost all their requests or because their score isn't good)
4928 // then they would disconnect organically, report their new state and then
4929 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004930 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004931 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4932 null, null);
4933 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004934 final boolean wasDefault = isDefaultNetwork(nai);
4935 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004936 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004937 }
4938 notifyIfacesChangedForNetworkStats();
4939 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4940 // by other networks that are already connected. Perhaps that can be done by
4941 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4942 // of rematchAllNetworksAndRequests
4943 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004944 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004945
4946 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004947 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4948 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004949 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004950 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004951 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004952 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004953 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004954 synchronized (mNetworkForNetId) {
4955 // Remove the NetworkAgent, but don't mark the netId as
4956 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004957 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004958 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004959 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004960 // Update allowed network lists in netd. This should be called after removing nai
4961 // from mNetworkAgentInfos.
4962 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004963 // Remove all previously satisfied requests.
4964 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004965 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004966 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004967 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004968 if (currentNetwork != null
4969 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004970 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004971 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4972 // rematch not to keep disconnected agents instead of setting it here ; this
4973 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004974 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004975 for (final NetworkOfferInfo noi : mNetworkOffers) {
4976 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004977 }
James Mattise3ef1912020-12-20 11:09:58 -08004978
Chalard Jean5b409c72021-02-04 13:12:59 +09004979 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004980 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004981 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004982 // network, because while incorrect this is the closest to the old (also
4983 // incorrect) behavior.
4984 mNetworkActivityTracker.updateDataActivityTracking(
4985 null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004986 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004987 ensureNetworkTransitionWakelock(nai.toShortString());
4988 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004989 }
4990 }
junyulai2b6f0c22021-02-03 20:15:30 +08004991 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004992 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004993 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004994 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004995 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004996 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004997 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004998
Aaron Huang9fe47be2021-06-08 13:11:45 +08004999 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5000 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5001 // not called by the rematch in this case. This is because the code above unset
5002 // this network from the default request's satisfier, and that is what the rematch
5003 // is using as its source data to know what the old satisfier was. So as far as the
5004 // rematch above is concerned, the old default network was null.
5005 // Therefore if there is no new default, the default network was null and is still
5006 // null, thus there was no change so makeDefault() is not called. So if the old
5007 // network had a proxy and there is no new default, the proxy tracker should be told
5008 // that there is no longer a default proxy.
5009 // Strictly speaking this is not essential because having a proxy setting when
5010 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5011 mProxyTracker.setDefaultProxy(null);
5012 }
5013
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005014 // Immediate teardown.
5015 if (nai.teardownDelayMs == 0) {
5016 destroyNetwork(nai);
5017 return;
5018 }
5019
5020 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005021 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305022 try {
5023 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5024 } catch (RemoteException e) {
5025 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5026 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005027 }
5028 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5029 }
5030
5031 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005032 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005033 // Tell netd to clean up the configuration for this network
5034 // (routing rules, DNS, etc).
5035 // This may be slow as it requires a lot of netd shelling out to ip and
5036 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005037 // after we've rematched networks with requests (which might change the default
5038 // network or service a new request from an app), so network traffic isn't interrupted
5039 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005040 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005041 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005042 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005043 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5044 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5045 // false if the network was never created.
5046 // TODO: delete when S is no longer supported.
5047 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005048 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005049 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005050 }
5051
Ken Chen6df7a902021-04-09 15:08:42 +08005052 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005053 try {
5054 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005055 final NativeNetworkConfig config;
5056 if (nai.isVPN()) {
5057 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005058 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005059 return false;
5060 }
5061 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5062 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005063 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005064 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005065 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005066 final boolean hasLocalCap =
5067 nai.networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
5068 config = new NativeNetworkConfig(nai.network.getNetId(),
5069 hasLocalCap ? NativeNetworkType.PHYSICAL_LOCAL : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005070 getNetworkPermission(nai.networkCapabilities),
5071 false /* secure */,
5072 VpnManager.TYPE_VPN_NONE,
5073 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005074 }
Ken Chen6df7a902021-04-09 15:08:42 +08005075 mNetd.networkCreate(config);
5076 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005077 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5078 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005079 return true;
5080 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005081 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005082 return false;
5083 }
5084 }
5085
Ken Chen6df7a902021-04-09 15:08:42 +08005086 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005087 if (mDscpPolicyTracker != null) {
5088 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5089 }
Luke Huangfdd11f82019-04-09 18:41:49 +08005090 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005091 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005092 } catch (RemoteException | ServiceSpecificException e) {
5093 loge("Exception destroying network(networkDestroy): " + e);
5094 }
5095 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005096 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005097 } catch (RemoteException | ServiceSpecificException e) {
5098 loge("Exception destroying network: " + e);
5099 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005100 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5101 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5102 // gets created, could add data to DnsManager data structures that will never get deleted.
5103 mDnsManager.removeNetwork(nai.network);
5104
5105 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005106 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005107 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5108 }
5109
Chalard Jean254bd162022-08-25 13:04:51 +09005110 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005111 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005112 }
5113
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005114 // If this method proves to be too slow then we can maintain a separate
5115 // pendingIntent => NetworkRequestInfo map.
5116 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5117 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005118 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5119 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5120 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005121 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005122 return entry.getValue();
5123 }
5124 }
5125 return null;
5126 }
5127
Chalard Jean524f0b12021-10-25 21:11:56 +09005128 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005129 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005130 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5131 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5132 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5133 // bug is fixed.
5134 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005135 throw new IllegalStateException("This NRI is already registered. New : " + nri
5136 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005137 }
5138 }
5139 }
5140 }
5141
Chalard Jeanac9ace02022-01-26 16:54:05 +09005142 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5143 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005144 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005145 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5146 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005147 }
5148 return false;
5149 }
5150
James Mattisf7027322020-12-13 16:28:14 -08005151 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005152 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005153 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5154 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5155 final NetworkRequestInfo existingRequest =
5156 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005157 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005158 if (DBG) {
5159 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5160 + nri.mRequests.get(0) + " because their intents matched.");
5161 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005162 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005163 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005164 }
Erik Kline05f2b402015-04-30 12:58:40 +09005165 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005166 }
5167
James Mattisf7027322020-12-13 16:28:14 -08005168 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005169 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005170 }
5171
James Mattis3ce3d3c2021-02-09 18:18:28 -08005172 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005173 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005174 for (final NetworkRequestInfo nri : nris) {
5175 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005176 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005177 for (final NetworkRequest req : nri.mRequests) {
5178 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005179 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005180 if (req.isListen()) {
5181 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5182 if (req.networkCapabilities.hasSignalStrength()
5183 && network.satisfiesImmutableCapabilitiesOf(req)) {
5184 updateSignalStrengthThresholds(network, "REGISTER", req);
5185 }
James Mattisf7027322020-12-13 16:28:14 -08005186 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005187 }
5188 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005189
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005190 // If this NRI has a satisfier already, it is replacing an older request that
5191 // has been removed. Track it.
5192 final NetworkRequest activeRequest = nri.getActiveRequest();
5193 if (null != activeRequest) {
5194 // If there is an active request, then for sure there is a satisfier.
5195 nri.getSatisfier().addRequest(activeRequest);
5196 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005197 }
James Mattisf7027322020-12-13 16:28:14 -08005198
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005199 if (mFlags.noRematchAllRequestsOnRegister()) {
5200 rematchNetworksAndRequests(nris);
5201 } else {
5202 rematchAllNetworksAndRequests();
5203 }
James Mattis45d81842021-01-10 14:24:24 -08005204
Chalard Jean0354d8c2021-01-12 10:58:56 +09005205 // Requests that have not been matched to a network will not have been sent to the
5206 // providers, because the old satisfier and the new satisfier are the same (null in this
5207 // case). Send these requests to the providers.
5208 for (final NetworkRequestInfo nri : nris) {
5209 for (final NetworkOfferInfo noi : mNetworkOffers) {
5210 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005211 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005212 }
5213 }
5214
James Mattisf7027322020-12-13 16:28:14 -08005215 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5216 final int callingUid) {
5217 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005218 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005219 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5220 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5221 handleReleaseNetworkRequest(
5222 nri.mRequests.get(0),
5223 callingUid,
5224 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005225 }
5226 }
5227
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005228 // Determines whether the network is the best (or could become the best, if it validated), for
5229 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5230 // on the value of reason:
5231 //
5232 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5233 // then it should be torn down.
5234 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5235 // then it should be lingered.
5236 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005237 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005238
Chalard Jean254bd162022-08-25 13:04:51 +09005239 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005240 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5241 return false;
5242 }
5243
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005244 final int numRequests;
5245 switch (reason) {
5246 case TEARDOWN:
5247 numRequests = nai.numRequestNetworkRequests();
5248 break;
5249 case LINGER:
5250 numRequests = nai.numForegroundNetworkRequests();
5251 break;
5252 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005253 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005254 return true;
5255 }
5256
Chalard Jean947acd42021-03-08 22:29:27 +09005257 if (numRequests > 0) return false;
5258
Paul Jensende49eb12015-06-25 15:30:08 -04005259 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005260 if (reason == UnneededFor.LINGER
5261 && !nri.isMultilayerRequest()
5262 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005263 // Background requests don't affect lingering.
5264 continue;
5265 }
5266
James Mattis3d229892020-11-16 16:46:28 -08005267 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005268 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005269 }
5270 }
Paul Jensende49eb12015-06-25 15:30:08 -04005271 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005272 }
5273
James Mattis3d229892020-11-16 16:46:28 -08005274 private boolean isNetworkPotentialSatisfier(
5275 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
5276 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005277 // request, return immediately. For multilayer requests, check to see if any of the
5278 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005279 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5280 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005281 return false;
5282 }
5283 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005284 // This multilayer listen request is satisfied therefore no further requests need to be
5285 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005286 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005287 return false;
5288 }
James Mattis3d229892020-11-16 16:46:28 -08005289 // As non-multilayer listen requests have already returned, the below would only happen
5290 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005291 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005292 continue;
5293 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09005294 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08005295 // there is hope for it to become one if it validated, then it is needed.
5296 if (candidate.satisfies(req)) {
5297 // As soon as a network is found that satisfies a request, return. Specifically for
5298 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5299 // is important so as to not evaluate lower priority requests further in
5300 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005301 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5302 ? nri.getSatisfier() : null;
5303 // Note that this catches two important cases:
5304 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5305 // is currently satisfying the request. This is desirable when
5306 // cellular ends up validating but WiFi does not.
5307 // 2. Unvalidated WiFi will not be reaped when validated cellular
5308 // is currently satisfying the request. This is desirable when
5309 // WiFi ends up validating and out scoring cellular.
5310 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005311 }
5312 }
5313
5314 return false;
5315 }
5316
Erik Kline0c04b742016-07-07 16:50:58 +09005317 private NetworkRequestInfo getNriForAppRequest(
5318 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005319 // Looking up the app passed param request in mRequests isn't possible since it may return
5320 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5321 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005322 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5323 // to avoid potential race conditions when validating a package->uid mapping when sending
5324 // the callback on the very low-chance that an application shuts down prior to the callback
5325 // being sent.
5326 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5327 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005328
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005329 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005330 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005331 log(String.format("UID %d attempted to %s for unowned request %s",
5332 callingUid, requestedOperation, nri));
5333 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005334 }
Erik Kline0c04b742016-07-07 16:50:58 +09005335 }
5336
5337 return nri;
5338 }
5339
James Mattisf7027322020-12-13 16:28:14 -08005340 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5341 final String callingMethod) {
5342 if (nri.isMultilayerRequest()) {
5343 throw new IllegalStateException(
5344 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005345 }
5346 }
5347
James Mattisf7027322020-12-13 16:28:14 -08005348 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005349 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005350 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5351 // single NetworkRequest and thus does not apply to multilayer requests.
5352 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5353 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005354 return;
5355 }
James Mattis2516da32021-01-31 17:06:19 -08005356 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005357 return;
5358 }
James Mattisf7027322020-12-13 16:28:14 -08005359 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5360 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005361 }
5362 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005363 callCallbackForRequest(
5364 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005365 }
5366
James Mattisf7027322020-12-13 16:28:14 -08005367 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5368 final int callingUid,
5369 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005370 final NetworkRequestInfo nri =
5371 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5372 if (nri == null) {
5373 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005374 }
James Mattisf7027322020-12-13 16:28:14 -08005375 if (VDBG || (DBG && request.isRequest())) {
5376 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005377 }
5378 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005379 if (callOnUnavailable) {
5380 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5381 }
Erik Kline155a59a2015-11-25 12:49:38 +09005382 }
Erik Kline0c04b742016-07-07 16:50:58 +09005383
James Mattisa076c532020-12-02 14:12:41 -08005384 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005385 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005386 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005387 if (null == mNetworkRequests.remove(req)) {
5388 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5389 continue;
5390 }
James Mattisa076c532020-12-02 14:12:41 -08005391 if (req.isListen()) {
5392 removeListenRequestFromNetworks(req);
5393 }
5394 }
James Mattis8f036802021-06-20 16:26:01 -07005395 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005396 if (mDefaultNetworkRequests.remove(nri)) {
5397 // If this request was one of the defaults, then the UID rules need to be updated
5398 // WARNING : if the app(s) for which this network request is the default are doing
5399 // traffic, this will kill their connected sockets, even if an equivalent request
5400 // is going to be reinstated right away ; unconnected traffic will go on the default
5401 // until the new default is set, which will happen very soon.
5402 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5403 // remove ranges for those requests that won't have a replacement
5404 final NetworkAgentInfo satisfier = nri.getSatisfier();
5405 if (null != satisfier) {
5406 try {
paulhu0e79d952021-06-09 16:11:35 +08005407 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5408 satisfier.network.getNetId(),
5409 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005410 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005411 } catch (RemoteException e) {
5412 loge("Exception setting network preference default network", e);
5413 }
5414 }
5415 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005416
Junyu Lai00d92df2022-07-05 11:01:52 +08005417 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005418 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005419 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005420
5421 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005422 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005423 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005424 }
5425 }
5426
Chalard Jean0354d8c2021-01-12 10:58:56 +09005427 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5428 // needed for this offer.
5429 for (final NetworkOfferInfo noi : mNetworkOffers) {
5430 for (final NetworkRequest req : nri.mRequests) {
5431 if (req.isRequest() && noi.offer.neededFor(req)) {
5432 noi.offer.onNetworkUnneeded(req);
5433 }
5434 }
5435 }
James Mattisa076c532020-12-02 14:12:41 -08005436 }
5437
James Mattis3ce3d3c2021-02-09 18:18:28 -08005438 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5439 for (final NetworkRequestInfo nri : nris) {
5440 if (mDefaultRequest == nri) {
5441 // Make sure we never remove the default request.
5442 continue;
5443 }
5444 handleRemoveNetworkRequest(nri);
5445 }
5446 }
5447
James Mattisa076c532020-12-02 14:12:41 -08005448 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5449 // listens don't have a singular affected Network. Check all networks to see
5450 // if this listen request applies and remove it.
5451 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5452 nai.removeRequest(req.requestId);
5453 if (req.networkCapabilities.hasSignalStrength()
5454 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5455 updateSignalStrengthThresholds(nai, "RELEASE", req);
5456 }
5457 }
5458 }
5459
5460 /**
5461 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5462 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5463 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5464 */
5465 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5466 boolean wasKept = false;
5467 final NetworkAgentInfo nai = nri.getSatisfier();
5468 if (nai != null) {
5469 final int requestLegacyType = nri.getActiveRequest().legacyType;
5470 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5471 nai.removeRequest(nri.getActiveRequest().requestId);
5472 if (VDBG || DDBG) {
5473 log(" Removing from current network " + nai.toShortString()
5474 + ", leaving " + nai.numNetworkRequests() + " requests.");
5475 }
5476 // If there are still lingered requests on this network, don't tear it down,
5477 // but resume lingering instead.
5478 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005479 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005480 notifyNetworkLosing(nai, now);
5481 }
5482 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5483 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5484 teardownUnneededNetwork(nai);
5485 } else {
5486 wasKept = true;
5487 }
James Mattisa076c532020-12-02 14:12:41 -08005488 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5489 // Went from foreground to background.
5490 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005491 }
5492
Erik Kline0c04b742016-07-07 16:50:58 +09005493 // Maintain the illusion. When this request arrived, we might have pretended
5494 // that a network connected to serve it, even though the network was already
5495 // connected. Now that this request has gone away, we might have to pretend
5496 // that the network disconnected. LegacyTypeTracker will generate that
5497 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005498 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005499 boolean doRemove = true;
5500 if (wasKept) {
5501 // check if any of the remaining requests for this network are for the
5502 // same legacy type - if so, don't remove the nai
5503 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5504 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005505 if (otherRequest.legacyType == requestLegacyType
5506 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005507 if (DBG) log(" still have other legacy request - leaving");
5508 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005509 }
5510 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005511 }
5512
Erik Kline0c04b742016-07-07 16:50:58 +09005513 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005514 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005515 }
5516 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005517 }
5518 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005519
Junyu Lai00d92df2022-07-05 11:01:52 +08005520 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005521 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005522 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5523 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5524 }
5525
Lorenzo Colittid6459092016-07-04 12:55:44 +09005526 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005527 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005528 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005529 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005530 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005531 }
5532
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005533 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005534 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5535 enforceNetworkStackSettingsOrSetup();
5536 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5537 encodeBool(accept), encodeBool(always), network));
5538 }
5539
5540 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005541 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005542 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005543 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5544 }
5545
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005546 @Override
5547 public void setTestAllowBadWifiUntil(long timeMs) {
5548 enforceSettingsPermission();
5549 if (!Build.isDebuggable()) {
5550 throw new IllegalStateException("Does not support in non-debuggable build");
5551 }
5552
5553 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5554 throw new IllegalArgumentException("It should not exceed "
5555 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5556 }
5557
5558 mHandler.sendMessage(
5559 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5560 }
5561
chiachangwange0192a72023-02-06 13:25:01 +00005562 @Override
5563 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5564 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005565
5566 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5567 throw new IllegalArgumentException("Argument should not exceed "
5568 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5569 }
5570
5571 mHandler.sendMessage(
5572 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5573 }
5574
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005575 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5576 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5577 " accept=" + accept + " always=" + always);
5578
5579 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5580 if (nai == null) {
5581 // Nothing to do.
5582 return;
5583 }
5584
Chalard Jean254bd162022-08-25 13:04:51 +09005585 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005586 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005587 return;
5588 }
5589
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005590 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005591 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005592 }
5593
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005594 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5595 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005596 // If network becomes partial connectivity and user already accepted to use this
5597 // network, we should respect the user's option and don't need to popup the
5598 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005599 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005600 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005601 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005602 }
5603
5604 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005605 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005606 }
5607
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005608 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005609 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005610 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005611 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005612 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005613 }
5614
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005615 }
5616
lucaslin2240ef62019-03-12 13:08:03 +08005617 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5618 boolean always) {
5619 if (DBG) {
5620 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5621 + " always=" + always);
5622 }
5623
5624 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5625 if (nai == null) {
5626 // Nothing to do.
5627 return;
5628 }
5629
Chalard Jean254bd162022-08-25 13:04:51 +09005630 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005631 // The network validated while the dialog box was up. Take no action.
5632 return;
5633 }
5634
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005635 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5636 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005637 }
5638
5639 // TODO: Use the current design or save the user choice into IpMemoryStore.
5640 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005641 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005642 }
5643
5644 if (!accept) {
5645 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005646 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005647 // Tear down the network.
5648 teardownUnneededNetwork(nai);
5649 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005650 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5651 // result in a partial connectivity result which will be processed by
5652 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005653 //
5654 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5655 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005656 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005657 }
5658 }
5659
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005660 private void handleSetAvoidUnvalidated(Network network) {
5661 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005662 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005663 // Nothing to do. The network either disconnected or revalidated.
5664 return;
5665 }
Chalard Jean254bd162022-08-25 13:04:51 +09005666 if (0L == nai.getAvoidUnvalidated()) {
5667 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005668 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005669 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005670 }
5671 }
5672
Chalard Jean5fb43c72022-09-08 19:03:14 +09005673 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005674 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005675 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005676 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005677 }
5678
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005679 @Override
5680 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005681 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005682 mHandler.post(() -> {
5683 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5684 if (nai == null) return;
5685 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005686 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005687 });
5688 }
5689
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005690 /**
5691 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5692 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005693 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005694 * @param appExtras Bundle to use as intent extras for the captive portal application.
5695 * Must be treated as opaque to avoid preventing the captive portal app to
5696 * update its arguments.
5697 */
5698 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005699 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005700 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5701 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005702
5703 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5704 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005705 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5706 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005707 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5708
lucaslin75ff7022020-12-17 04:14:35 +08005709 final long token = Binder.clearCallingIdentity();
5710 try {
5711 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5712 } finally {
5713 Binder.restoreCallingIdentity(token);
5714 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005715 }
5716
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005717 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5718 private final Network mNetwork;
5719
5720 private CaptivePortalImpl(Network network) {
5721 mNetwork = network;
5722 }
5723
5724 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005725 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005726 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5727 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005728 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5729 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5730 // Since the network will be disconnected, skip notifying NetworkMonitor
5731 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005732 }
5733
Chiachang Wang938bfba2020-01-09 13:50:55 +08005734 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005735 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005736 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005737 }
5738
5739 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005740 public void appRequest(final int request) {
5741 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5742 if (nm == null) return;
5743
5744 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005745 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005746 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005747 }
5748 }
5749
5750 @Nullable
5751 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5752 // getNetworkAgentInfoForNetwork is thread-safe
5753 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5754 if (nai == null) return null;
5755
5756 // nai.networkMonitor() is thread-safe
5757 return nai.networkMonitor();
5758 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005759 }
5760
Hugo Benichic9048bc2016-09-14 23:23:08 +00005761 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005762 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005763 }
5764
Chalard Jean020b93a2022-09-01 13:20:14 +09005765 private boolean activelyPreferBadWifi() {
5766 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5767 }
5768
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005769 /**
5770 * Return whether the device should maintain continuous, working connectivity by switching away
5771 * from WiFi networks having no connectivity.
5772 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5773 */
5774 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005775 if (!checkNetworkStackPermission()) {
5776 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5777 }
5778 return avoidBadWifi();
5779 }
5780
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005781 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005782 ensureRunningOnConnectivityServiceThread();
5783 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005784 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005785 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005786 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005787 if (avoidBadWifi) {
5788 // If the device is now avoiding bad wifi, remove notifications that might have
5789 // been put up when the device didn't.
5790 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5791 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005792 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005793 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5794 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5795 for (final NetworkOfferInfo noi : offersToUpdate) {
5796 updateOfferScore(noi.offer);
5797 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005798 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005799 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005800 }
5801
Erik Kline95ecfee2016-10-02 18:02:14 +09005802 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005803 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005804 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005805 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005806 if (!configRestrict) {
5807 pw.println("Bad Wi-Fi avoidance: unrestricted");
5808 return;
5809 }
5810
5811 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5812 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005813 pw.println("Config restrict: " + configRestrict);
5814 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005815
Chalard Jeane0fdea32022-09-14 21:44:22 +09005816 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005817 String description;
5818 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005819 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005820 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005821 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005822 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005823 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005824 description = "avoid";
5825 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005826 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005827 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005828 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005829
5830 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5831 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005832 if (null == configValue) {
5833 description = "unset";
5834 } else if (configValue) {
5835 description = "force true";
5836 } else {
5837 description = "force false";
5838 }
5839 pw.println("Actively prefer bad wifi conf: " + description);
5840 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005841 pw.println("Network overrides:");
5842 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005843 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005844 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005845 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005846 }
5847 }
5848 pw.decreaseIndent();
5849 pw.decreaseIndent();
5850 }
5851
paulhu7746e4e2020-06-09 19:07:03 +08005852 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5853 // unify the method.
5854 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5855 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5856 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5857 return settingsComponent != null
5858 ? settingsComponent.getPackageName() : "com.android.settings";
5859 }
5860
lucaslinb1e8e382019-01-24 15:55:30 +08005861 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005862 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005863 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005864 switch (type) {
5865 case NO_INTERNET:
5866 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005867 // High priority because it is only displayed for explicitly selected networks.
5868 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005869 break;
lucasline117e2e2019-10-22 18:27:33 +08005870 case PRIVATE_DNS_BROKEN:
5871 action = Settings.ACTION_WIRELESS_SETTINGS;
5872 // High priority because we should let user know why there is no internet.
5873 highPriority = true;
5874 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005875 case LOST_INTERNET:
5876 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005877 // High priority because it could help the user avoid unexpected data usage.
5878 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005879 break;
lucaslin2240ef62019-03-12 13:08:03 +08005880 case PARTIAL_CONNECTIVITY:
5881 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005882 // Don't bother the user with a high-priority notification if the network was not
5883 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005884 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005885 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005886 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005887 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005888 return;
5889 }
5890
5891 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005892 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005893 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005894 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005895 // Some OEMs have their own Settings package. Thus, need to get the current using
5896 // Settings package name instead of just use default name "com.android.settings".
5897 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5898 intent.setClassName(settingsPkgName,
5899 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005900 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005901
paulhu2af50222020-10-11 22:52:27 +08005902 PendingIntent pendingIntent = PendingIntent.getActivity(
5903 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005904 0 /* requestCode */,
5905 intent,
paulhu2af50222020-10-11 22:52:27 +08005906 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005907
Serik Beketayevec8ad212020-12-07 22:43:07 -08005908 mNotifier.showNotification(
5909 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005910 }
5911
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005912 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5913 // Don't prompt if the network is validated, and don't prompt on captive portals
5914 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005915 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005916 return false;
5917 }
5918
5919 // If a network has partial connectivity, always prompt unless the user has already accepted
5920 // partial connectivity and selected don't ask again. This ensures that if the device
5921 // automatically connects to a network that has partial Internet access, the user will
5922 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005923 // because we have prompted them.
5924 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005925 return true;
5926 }
5927
5928 // If a network has no Internet access, only prompt if the network was explicitly selected
5929 // and if the user has not already told us to use the network regardless of whether it
5930 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005931 if (nai.networkAgentConfig.explicitlySelected
5932 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005933 return true;
5934 }
5935
5936 return false;
5937 }
5938
Chalard Jean5fb43c72022-09-08 19:03:14 +09005939 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5940 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005941
Chalard Jean5fb43c72022-09-08 19:03:14 +09005942 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5943 if (null == nai) return;
5944
5945 if (nai.setEvaluated()) {
5946 // If setEvaluated() returned true, the network never had any form of connectivity.
5947 // This may have an impact on request matching if bad WiFi avoidance is off and the
5948 // network was found not to have Internet access.
5949 nai.updateScoreForNetworkAgentUpdate();
5950 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005951
5952 // Also, if this is WiFi and it should be preferred actively, now is the time to
5953 // prompt the user that they walked past and connected to a bad WiFi.
5954 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5955 && !avoidBadWifi()
5956 && activelyPreferBadWifi()) {
5957 // The notification will be removed if the network validates or disconnects.
5958 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5959 return;
5960 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005961 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005962
Chalard Jean5fb43c72022-09-08 19:03:14 +09005963 if (!shouldPromptUnvalidated(nai)) return;
5964
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005965 // Stop automatically reconnecting to this network in the future. Automatically connecting
5966 // to a network that provides no or limited connectivity is not useful, because the user
5967 // cannot use that network except through the notification shown by this method, and the
5968 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005969 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005970
Chalard Jean254bd162022-08-25 13:04:51 +09005971 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005972 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005973 } else {
5974 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5975 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005976 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005977
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005978 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5979 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005980 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005981
lucaslin2240ef62019-03-12 13:08:03 +08005982 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5983 return;
5984 }
5985
5986 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005987 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005988 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005989 }
5990
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005991 @Override
5992 public int getMultipathPreference(Network network) {
5993 enforceAccessPermission();
5994
5995 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005996 if (nai != null && nai.networkCapabilities
5997 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005998 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5999 }
6000
Aaron Huang9a57acf2020-12-08 10:03:29 +08006001 final NetworkPolicyManager netPolicyManager =
6002 mContext.getSystemService(NetworkPolicyManager.class);
6003
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006004 final long token = Binder.clearCallingIdentity();
6005 final int networkPreference;
6006 try {
6007 networkPreference = netPolicyManager.getMultipathPreference(network);
6008 } finally {
6009 Binder.restoreCallingIdentity(token);
6010 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006011 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006012 return networkPreference;
6013 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006014 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6015 }
6016
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006017 @Override
6018 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006019 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006020 }
6021
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006022 private class InternalHandler extends Handler {
6023 public InternalHandler(Looper looper) {
6024 super(looper);
6025 }
6026
6027 @Override
6028 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006029 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006030 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006031 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006032 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006033 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006034 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006035 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006036 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006037 break;
6038 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006039 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006040 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006041 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006042 break;
6043 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006044 case EVENT_REGISTER_NETWORK_PROVIDER: {
6045 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006046 break;
6047 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006048 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6049 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006050 break;
6051 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006052 case EVENT_REGISTER_NETWORK_OFFER: {
6053 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6054 break;
6055 }
6056 case EVENT_UNREGISTER_NETWORK_OFFER: {
6057 final NetworkOfferInfo offer =
6058 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6059 if (null != offer) {
6060 handleUnregisterNetworkOffer(offer);
6061 }
6062 break;
6063 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006064 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006065 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6066 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6067 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006068 break;
6069 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006070 case EVENT_REGISTER_NETWORK_REQUEST:
6071 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006072 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006073 break;
6074 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006075 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6076 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006077 handleRegisterNetworkRequestWithIntent(msg);
6078 break;
6079 }
Erik Kline155a59a2015-11-25 12:49:38 +09006080 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6081 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6082 handleTimedOutNetworkRequest(nri);
6083 break;
6084 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006085 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6086 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6087 break;
6088 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006089 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006090 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6091 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006092 break;
6093 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006094 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006095 Network network = (Network) msg.obj;
6096 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006097 break;
6098 }
lucaslin2240ef62019-03-12 13:08:03 +08006099 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6100 Network network = (Network) msg.obj;
6101 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6102 toBool(msg.arg2));
6103 break;
6104 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006105 case EVENT_SET_AVOID_UNVALIDATED: {
6106 handleSetAvoidUnvalidated((Network) msg.obj);
6107 break;
6108 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006109 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6110 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006111 break;
6112 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006113 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6114 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006115 break;
6116 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006117 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6118 // handler thread.
6119 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006120 mKeepaliveTracker.handleStartKeepalive(msg);
6121 break;
6122 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006123 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006124 final AutomaticOnOffKeepalive ki =
6125 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6126 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006127
chiachangwang676c84e2023-02-14 09:22:05 +00006128 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006129 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006130 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006131 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006132 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6133 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006134 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6135 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006136 }
6137 }
6138
6139 // If the network no longer exists, then the keepalive should have been
6140 // cleaned up already. There is no point trying to resume keepalives.
6141 if (!networkFound) return;
6142
chiachangwang676c84e2023-02-14 09:22:05 +00006143 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006144 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00006145 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006146 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006147 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006148 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006149 }
6150 break;
6151 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006152 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006153 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006154 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6155 (IBinder) msg.obj);
6156 if (ki == null) {
6157 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006158 return;
6159 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006160 final int reason = msg.arg2;
6161 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006162 break;
6163 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006164 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6165 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6166 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006167 break;
6168 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006169 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6170 handlePrivateDnsSettingsChanged();
6171 break;
dalyk1720e542018-03-05 12:42:22 -05006172 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6173 handlePrivateDnsValidationUpdate(
6174 (PrivateDnsValidationUpdate) msg.obj);
6175 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006176 case EVENT_UID_BLOCKED_REASON_CHANGED:
6177 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006178 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006179 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6180 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6181 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006182 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006183 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6184 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006185 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006186 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006187 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006188 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006189 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6190 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006191 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006192 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006193 }
lucaslin1193a5d2021-01-21 02:04:15 +08006194 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006195 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006196 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006197 break;
paulhu51f77dc2021-06-07 02:34:20 +00006198 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6199 handleMobileDataPreferredUidsChanged();
6200 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006201 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6202 final long timeMs = ((Long) msg.obj).longValue();
6203 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6204 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006205 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6206 handleIngressRateLimitChanged();
6207 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006208 case EVENT_USER_DOES_NOT_WANT:
6209 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6210 if (nai == null) break;
6211 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006212 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006213 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006214 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6215 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6216 break;
chiachangwange0192a72023-02-06 13:25:01 +00006217 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6218 final long time = ((Long) msg.obj).longValue();
6219 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6220 break;
6221 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006222 case EVENT_UID_FROZEN_STATE_CHANGED:
6223 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6224 handleFrozenUids(args.mUids, args.mFrozenStates);
6225 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006226 }
6227 }
6228 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006229
Lorenzo Colittid6459092016-07-04 12:55:44 +09006230 @Override
markchien5776f962019-12-16 20:15:20 +08006231 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006232 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006233 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006234 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6235 Context.TETHERING_SERVICE);
6236 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006237 }
6238
Lorenzo Colittid6459092016-07-04 12:55:44 +09006239 @Override
markchien5776f962019-12-16 20:15:20 +08006240 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006241 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006242 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006243 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6244 Context.TETHERING_SERVICE);
6245 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006246 }
6247
Lorenzo Colittid6459092016-07-04 12:55:44 +09006248 @Override
markchien5776f962019-12-16 20:15:20 +08006249 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006250 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006251 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006252 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6253 Context.TETHERING_SERVICE);
6254 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006255 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006256
markchien5776f962019-12-16 20:15:20 +08006257
Lorenzo Colittid6459092016-07-04 12:55:44 +09006258 @Override
markchien5776f962019-12-16 20:15:20 +08006259 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006260 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006261 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006262 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6263 Context.TETHERING_SERVICE);
6264
6265 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006266 }
6267
Lorenzo Colittid6459092016-07-04 12:55:44 +09006268 @Override
markchien5776f962019-12-16 20:15:20 +08006269 @Deprecated
6270 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006271 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006272 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6273 Context.TETHERING_SERVICE);
6274
6275 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006276 }
6277
Udam Saini8f7d6a72017-06-07 12:06:28 -07006278 @Override
markchien5776f962019-12-16 20:15:20 +08006279 @Deprecated
6280 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006281 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006282 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6283 Context.TETHERING_SERVICE);
6284 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006285 }
6286
Robert Greenwalte0b00512014-07-02 09:59:16 -07006287 // Called when we lose the default network and have no replacement yet.
6288 // This will automatically be cleared after X seconds or a new default network
6289 // becomes CONNECTED, whichever happens first. The timer is started by the
6290 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006291 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006292 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006293 if (mNetTransitionWakeLock.isHeld()) {
6294 return;
6295 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006296 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006297 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6298 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006299 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006300 mWakelockLogs.log("ACQUIRE for " + forWhom);
6301 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006302 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006303 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006304 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006305 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006306
Hugo Benichi471b62a2017-03-30 23:18:10 +09006307 // Called when we gain a new default network to release the network transition wakelock in a
6308 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6309 // message is cancelled.
6310 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006311 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006312 if (!mNetTransitionWakeLock.isHeld()) {
6313 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006314 }
6315 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006316 // Cancel self timeout on wakelock hold.
6317 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6318 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6319 mHandler.sendMessageDelayed(msg, 1000);
6320 }
6321
6322 // Called when either message of ensureNetworkTransitionWakelock or
6323 // scheduleReleaseNetworkTransitionWakelock is processed.
6324 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6325 String event = eventName(eventId);
6326 synchronized (this) {
6327 if (!mNetTransitionWakeLock.isHeld()) {
6328 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006329 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006330 return;
6331 }
6332 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006333 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6334 mTotalWakelockDurationMs += lockDuration;
6335 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6336 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006337 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006338 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006339 }
6340
Robert Greenwalt986c7412010-09-08 15:24:47 -07006341 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006342 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006343 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006344 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006345 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006346 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006347 }
6348
Lorenzo Colittid6459092016-07-04 12:55:44 +09006349 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006350 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006351 enforceAccessPermission();
6352 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006353 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006354 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006355
6356 final NetworkAgentInfo nai;
6357 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006358 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006359 } else {
6360 nai = getNetworkAgentInfoForNetwork(network);
6361 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006362
6363 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006364 mHandler.obtainMessage(
6365 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006366 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006367
Hugo Benichid6b510a2017-04-06 17:22:18 +09006368 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006369 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006370 if (nai == null
6371 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006372 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006373 return;
6374 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006375 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006376 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006377 mConnectivityDiagnosticsHandler.sendMessage(
6378 mConnectivityDiagnosticsHandler.obtainMessage(
6379 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6380 new ReportedNetworkConnectivityInfo(
6381 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006382 return;
6383 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006384 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006385 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006386 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006387 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006388 // Validating a network that has not yet connected could result in a call to
6389 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006390 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006391 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006392 }
paulhu7aeba372020-12-30 00:42:19 +08006393 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6394 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006395 return;
6396 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006397
6398 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6399 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6400 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6401 // completed.
6402 mConnectivityDiagnosticsHandler.sendMessage(
6403 mConnectivityDiagnosticsHandler.obtainMessage(
6404 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6405 new ReportedNetworkConnectivityInfo(
6406 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006407 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006408 }
6409
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006410 // TODO: call into netd.
6411 private boolean queryUserAccess(int uid, Network network) {
6412 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6413 if (nai == null) return false;
6414
6415 // Any UID can use its default network.
6416 if (nai == getDefaultNetworkForUid(uid)) return true;
6417
6418 // Privileged apps can use any network.
6419 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6420 return true;
6421 }
6422
6423 // An unprivileged UID can use a VPN iff the VPN applies to it.
6424 if (nai.isVPN()) {
6425 return nai.networkCapabilities.appliesToUid(uid);
6426 }
6427
6428 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6429 // sockets, i.e., if it is the owner.
6430 final NetworkAgentInfo vpn = getVpnForUid(uid);
6431 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6432 && uid != vpn.networkCapabilities.getOwnerUid()) {
6433 return false;
6434 }
6435
6436 // The UID's permission must be at least sufficient for the network. Since the restricted
6437 // permission was already checked above, that just leaves background networks.
6438 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6439 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6440 }
6441
6442 // Unrestricted network. Anyone gets to use it.
6443 return true;
6444 }
6445
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006446 /**
6447 * Returns information about the proxy a certain network is using. If given a null network, it
6448 * it will return the proxy for the bound network for the caller app or the default proxy if
6449 * none.
6450 *
6451 * @param network the network we want to get the proxy information for.
6452 * @return Proxy information if a network has a proxy configured, or otherwise null.
6453 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006454 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006455 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006456 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006457 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006458 if (network == null) {
6459 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006460 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006461 true);
6462 if (activeNetwork == null) {
6463 return null;
6464 }
6465 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006466 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006467 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6468 // caller may not have.
6469 return getLinkPropertiesProxyInfo(network);
6470 }
6471 // No proxy info available if the calling UID does not have network access.
6472 return null;
6473 }
6474
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006475
6476 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006477 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6478 if (nai == null) return null;
6479 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006480 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6481 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006482 }
6483 }
6484
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006485 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006486 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006487 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006488 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006489 }
6490
Chalard Jean777e2e52018-06-07 18:02:37 +09006491 @Override
6492 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006493 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006494 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006495 }
6496
Aaron Huang9fe47be2021-06-08 13:11:45 +08006497 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006498 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006499 final NetworkAgentInfo nai = getDefaultNetwork();
6500 // TODO : this method should check that net == nai.network, unfortunately at this point
6501 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6502 // is only ever installed on the default network so in practice this is okay.
6503 if (null == nai) return;
6504 // PAC proxies only work on the default network. Therefore, only the default network
6505 // should have its link properties fixed up for PAC proxies.
6506 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6507 if (nai.everConnected()) {
6508 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6509 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006510 }
6511
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006512 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6513 // when any network changes proxy.
6514 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6515 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006516 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6517 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006518 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6519
Chalard Jean7d97afc2018-06-07 17:41:29 +09006520 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006521 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006522 }
6523 }
6524
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006525 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006526 final private HashMap<Uri, Integer> mUriEventMap;
6527 final private Context mContext;
6528 final private Handler mHandler;
6529
6530 SettingsObserver(Context context, Handler handler) {
6531 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006532 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006533 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006534 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006535 }
6536
Erik Kline05f2b402015-04-30 12:58:40 +09006537 void observe(Uri uri, int what) {
6538 mUriEventMap.put(uri, what);
6539 final ContentResolver resolver = mContext.getContentResolver();
6540 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006541 }
6542
6543 @Override
6544 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006545 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006546 }
6547
6548 @Override
6549 public void onChange(boolean selfChange, Uri uri) {
6550 final Integer what = mUriEventMap.get(uri);
6551 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006552 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006553 } else {
6554 loge("No matching event to send for URI=" + uri);
6555 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006556 }
6557 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006558
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006559 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006560 Log.d(TAG, s);
6561 }
6562
6563 private static void logw(String s) {
6564 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006565 }
6566
Daniel Brightf9e945b2020-06-15 16:10:01 -07006567 private static void logwtf(String s) {
6568 Log.wtf(TAG, s);
6569 }
6570
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006571 private static void logwtf(String s, Throwable t) {
6572 Log.wtf(TAG, s, t);
6573 }
6574
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006575 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006576 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006577 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006578
Hugo Benichi39621362017-02-11 17:04:43 +09006579 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006580 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006581 }
6582
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006583 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006584 * Return the information of all ongoing VPNs.
6585 *
6586 * <p>This method is used to update NetworkStatsService.
6587 *
6588 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006589 */
junyulai2050bed2021-01-23 09:46:34 +08006590 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006591 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006592 if (mLockdownEnabled) {
6593 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006594 }
junyulai2050bed2021-01-23 09:46:34 +08006595 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006596 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006597 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006598 if (info != null) {
6599 infoList.add(info);
6600 }
6601 }
junyulai2050bed2021-01-23 09:46:34 +08006602 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006603 }
6604
6605 /**
6606 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006607 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006608 */
junyulai2050bed2021-01-23 09:46:34 +08006609 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006610 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006611 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6612 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006613 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6614 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6615 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006616 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6617 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006618 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006619 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006620 }
6621 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006622
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006623 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006624
6625 List<String> interfaces = new ArrayList<>();
6626 for (Network network : underlyingNetworks) {
6627 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6628 if (underlyingNai == null) continue;
6629 LinkProperties lp = underlyingNai.linkProperties;
6630 for (String iface : lp.getAllInterfaceNames()) {
6631 if (!TextUtils.isEmpty(iface)) {
6632 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006633 }
6634 }
Benedict Wong34857f82019-06-12 17:46:15 +00006635 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006636
6637 if (interfaces.isEmpty()) return null;
6638
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006639 // Must be non-null or NetworkStatsService will crash.
6640 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6641 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006642 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006643 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006644
junyulai2050bed2021-01-23 09:46:34 +08006645 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6646 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006647 }
6648
James Mattisd31bdfa2020-12-23 16:37:26 -08006649 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006650 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6651 Network[] underlyingNetworks) {
6652 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006653 if (underlyingNetworks == null && defaultNetwork != null) {
6654 // null underlying networks means to track the default.
6655 underlyingNetworks = new Network[] { defaultNetwork };
6656 }
6657 return underlyingNetworks;
6658 }
6659
6660 // Returns true iff |network| is an underlying network of |nai|.
6661 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6662 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6663 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006664 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006665 final Network[] underlying = underlyingNetworksOrDefault(
6666 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006667 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006668 }
6669
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006670 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006671 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006672 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006673 * When underlying networks change, such networks may have to update capabilities to reflect
6674 * things like the metered bit, their transports, and so on. The capabilities are calculated
6675 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006676 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006677 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006678 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006679 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006680 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006681 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006682 }
6683 }
6684 }
6685
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006686 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6687 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6688 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6689 // a VPN is not up.
6690 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6691 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6692 for (UidRange range : blockedUidRanges) {
6693 if (range.contains(uid)) return true;
6694 }
6695 return false;
6696 }
6697
6698 @Override
6699 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006700 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006701 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6702 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6703 }
6704
6705 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6706 if (DBG) {
6707 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6708 + Arrays.toString(ranges));
6709 }
6710 // Cannot use a Set since the list of UID ranges might contain duplicates.
6711 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6712 for (int i = 0; i < ranges.length; i++) {
6713 if (requireVpn) {
6714 newVpnBlockedUidRanges.add(ranges[i]);
6715 } else {
6716 newVpnBlockedUidRanges.remove(ranges[i]);
6717 }
6718 }
6719
6720 try {
6721 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6722 } catch (RemoteException | ServiceSpecificException e) {
6723 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6724 + Arrays.toString(ranges) + "): netd command failed: " + e);
6725 }
6726
Chalard Jeandf29a852023-05-29 17:02:43 +09006727 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006728 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6729 }
6730
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006731 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6732 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006733 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6734 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006735 }
6736
6737 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6738 }
6739
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006740 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006741 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006742 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006743 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006744 }
6745
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006746 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6747 return mLockdownEnabled
6748 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6749 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006750 }
6751
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006752 private NetworkAgentInfo getLegacyLockdownNai() {
6753 if (!mLockdownEnabled) {
6754 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006755 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006756 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006757 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6758 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006759
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006760 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006761 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6762 // a local variable. There is no need to make a copy because its contents cannot change.
6763 final Network[] underlying = nai.declaredUnderlyingNetworks;
6764 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006765 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006766 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006767
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006768 // The legacy lockdown VPN always uses the default network.
6769 // If the VPN's underlying network is no longer the current default network, it means that
6770 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006771 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6772 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006773 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006774 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006775 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006776 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006777
6778 return nai;
6779 };
6780
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006781 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6782 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6783 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006784 private DetailedState getLegacyLockdownState(DetailedState origState) {
6785 if (origState != DetailedState.CONNECTED) {
6786 return origState;
6787 }
6788 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6789 ? DetailedState.CONNECTING
6790 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006791 }
6792
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006793 private void filterForLegacyLockdown(NetworkInfo ni) {
6794 if (!mLockdownEnabled || !ni.isConnected()) return;
6795 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6796 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6797 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6798 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6799 // network, this time with a state of CONNECTED.
6800 //
6801 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6802 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6803 // is not too far off the truth, since an always-on VPN, when not connected, is always
6804 // trying to reconnect.
6805 if (getLegacyLockdownNai() == null) {
6806 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6807 }
6808 }
6809
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006810 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006811 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006812 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006813 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006814 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6815 return;
6816 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006817 final long ident = Binder.clearCallingIdentity();
6818 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006819 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006820 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006821 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006822 } finally {
6823 Binder.restoreCallingIdentity(ident);
6824 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006825 }
Wink Savillecb117d32013-08-29 14:57:08 -07006826
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006827 @Override
6828 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006829 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006830 final long ident = Binder.clearCallingIdentity();
6831 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006832 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006833 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006834 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6835 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006836 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006837 } finally {
6838 Binder.restoreCallingIdentity(ident);
6839 }
6840 }
6841
James Mattis02220e22021-03-13 19:27:21 -08006842 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006843 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6844 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6845 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006846 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006847 }
6848
James Mattis02220e22021-03-13 19:27:21 -08006849 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006850 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006851 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006852 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6853 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006854 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006855 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6856 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6857 }
junyulaid91e7052020-08-28 13:44:33 +08006858 }
6859
James Mattis02220e22021-03-13 19:27:21 -08006860 private void onPackageChanged(@NonNull final String packageName) {
6861 // This is necessary in case a package is added or removed, but also when it's replaced to
6862 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6863 // as one in the preferences, then it should follow the same routing as that other package,
6864 // which means updating the rules is never to be needed in this case (whether it joins or
6865 // leaves a UID with a preference).
6866 if (isMappedInOemNetworkPreference(packageName)) {
6867 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6868 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006869
6870 // Invalidates cache entry when the package is updated.
6871 synchronized (mSelfCertifiedCapabilityCache) {
6872 mSelfCertifiedCapabilityCache.remove(packageName);
6873 }
James Mattis02220e22021-03-13 19:27:21 -08006874 }
6875
6876 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006877 @Override
6878 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006879 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006880 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006881 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006882
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006883 // User should be filled for below intents, check the existence.
6884 if (user == null) {
6885 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6886 return;
6887 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006888
Lorenzo Colitticd675292021-02-04 17:32:07 +09006889 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006890 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006891 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006892 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006893 } else {
junyulaid91e7052020-08-28 13:44:33 +08006894 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006895 }
6896 }
6897 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006898
James Mattis02220e22021-03-13 19:27:21 -08006899 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6900 @Override
6901 public void onReceive(Context context, Intent intent) {
6902 ensureRunningOnConnectivityServiceThread();
6903 switch (intent.getAction()) {
6904 case Intent.ACTION_PACKAGE_ADDED:
6905 case Intent.ACTION_PACKAGE_REMOVED:
6906 case Intent.ACTION_PACKAGE_REPLACED:
6907 onPackageChanged(intent.getData().getSchemeSpecificPart());
6908 break;
6909 default:
6910 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6911 }
6912 }
6913 };
6914
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006915 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006916 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006917
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006918 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006919 public final String name;
6920 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006921 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006922 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006923
lifraf3a3492021-03-10 13:58:14 +08006924 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6925 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006926 this.name = name;
6927 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006928 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006929 mDeathRecipient = deathRecipient;
6930
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006931 if (mDeathRecipient == null) {
6932 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006933 }
6934 }
6935
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006936 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006937 try {
6938 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6939 } catch (RemoteException e) {
6940 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006941 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006942 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006943 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006944
James Mattis4fce5d12020-11-12 15:53:42 -08006945 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6946 for (int i = 0; i < requests.size(); i++) {
6947 ensureNetworkRequestHasType(requests.get(i));
6948 }
6949 }
6950
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006951 private void ensureNetworkRequestHasType(NetworkRequest request) {
6952 if (request.type == NetworkRequest.Type.NONE) {
6953 throw new IllegalArgumentException(
6954 "All NetworkRequests in ConnectivityService must have a type");
6955 }
6956 }
6957
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006958 /**
6959 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006960 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006961 */
James Mattis258ea3c2020-11-15 15:04:40 -08006962 @VisibleForTesting
6963 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006964 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6965 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006966 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006967
James Mattisa076c532020-12-02 14:12:41 -08006968 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6969 void setSatisfier(
6970 @Nullable final NetworkAgentInfo satisfier,
6971 @Nullable final NetworkRequest activeRequest) {
6972 mSatisfier = satisfier;
6973 mActiveRequest = activeRequest;
6974 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006975
James Mattisd31bdfa2020-12-23 16:37:26 -08006976 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006977 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006978 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006979 private NetworkAgentInfo mSatisfier;
6980 NetworkAgentInfo getSatisfier() {
6981 return mSatisfier;
6982 }
6983
6984 // The request in mRequests assigned to a network agent. This is null if none of the
6985 // requests in mRequests can be satisfied. This member has the constraint of only being
6986 // accessible on the handler thread.
6987 @Nullable
6988 private NetworkRequest mActiveRequest;
6989 NetworkRequest getActiveRequest() {
6990 return mActiveRequest;
6991 }
6992
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006993 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006994 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006995 @Nullable
6996 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006997
6998 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006999 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007000 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007001 final int mPid;
7002 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007003 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007004 @Nullable
7005 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007006
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007007 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007008 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007009
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007010 // Effective UID of this request. This is different from mUid when a privileged process
7011 // files a request on behalf of another UID. This UID is used to determine blocked status,
7012 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7013 // maximum limit of registered callbacks per UID.
7014 final int mAsUid;
7015
paulhu48291862021-07-14 14:53:57 +08007016 // Preference order of this request.
7017 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007018
James Mattis3ce3d3c2021-02-09 18:18:28 -08007019 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7020 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7021 // maintained for keying off of. This is only a concern when the original nri
7022 // mNetworkRequests changes which happens currently for apps that register callbacks to
7023 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7024 // that match the per-app default nri that currently tracks the calling app's uid so that
7025 // callbacks are fired at the appropriate time. When the callbacks fire,
7026 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7027 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7028 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7029 @NonNull
7030 private final NetworkRequest mNetworkRequestForCallback;
7031 NetworkRequest getNetworkRequestForCallback() {
7032 return mNetworkRequestForCallback;
7033 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007034
James Mattisd31bdfa2020-12-23 16:37:26 -08007035 /**
7036 * Get the list of UIDs this nri applies to.
7037 */
7038 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007039 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007040 // networkCapabilities.getUids() returns a defensive copy.
7041 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007042 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7043 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007044 }
7045
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007046 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7047 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007048 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007049 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007050 }
7051
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007052 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007053 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007054 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007055 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007056 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007057 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007058 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007059 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007060 mBinder = null;
7061 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007062 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007063 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007064 mPerUidCounter = getRequestCounter(this);
7065 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007066 /**
7067 * Location sensitive data not included in pending intent. Only included in
7068 * {@link NetworkCallback}.
7069 */
7070 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007071 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007072 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007073 }
7074
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007075 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007076 @Nullable final IBinder binder,
7077 @NetworkCallback.Flag int callbackFlags,
7078 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007079 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7080 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007081 }
7082
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007083 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007084 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007085 @Nullable final IBinder binder,
7086 @NetworkCallback.Flag int callbackFlags,
7087 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007088 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007089 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007090 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007091 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007092 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007093 mBinder = binder;
7094 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007095 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007096 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007097 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007098 mPerUidCounter = getRequestCounter(this);
7099 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007100 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007101 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007102 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007103 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007104 }
7105
James Mattis3ce3d3c2021-02-09 18:18:28 -08007106 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7107 @NonNull final List<NetworkRequest> r) {
7108 super();
7109 ensureAllNetworkRequestsHaveType(r);
7110 mRequests = initializeRequests(r);
7111 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007112 final NetworkAgentInfo satisfier = nri.getSatisfier();
7113 if (null != satisfier) {
7114 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7115 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007116 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007117 // As this code creates a new NRI with a new set of requests, figure out which of
7118 // the list of requests should be the active request. It is always the first
7119 // request of the list that can be satisfied by the satisfier since the order of
7120 // requests is a priority order.
7121 // Note even in the presence of a satisfier there may not be an active request,
7122 // when the satisfier is the no-service network.
7123 NetworkRequest activeRequest = null;
7124 for (final NetworkRequest candidate : r) {
7125 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7126 activeRequest = candidate;
7127 break;
7128 }
7129 }
7130 setSatisfier(satisfier, activeRequest);
7131 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007132 mMessenger = nri.mMessenger;
7133 mBinder = nri.mBinder;
7134 mPid = nri.mPid;
7135 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007136 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007137 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007138 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007139 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007140 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007141 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007142 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007143 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007144 }
7145
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007146 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007147 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007148 }
7149
paulhue9913722021-05-26 15:19:20 +08007150 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007151 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007152 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007153 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007154 }
7155
James Mattis2516da32021-01-31 17:06:19 -08007156 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7157 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7158 // false.
7159 boolean isBeingSatisfied() {
7160 return (null != mSatisfier && null != mActiveRequest);
7161 }
7162
James Mattis3d229892020-11-16 16:46:28 -08007163 boolean isMultilayerRequest() {
7164 return mRequests.size() > 1;
7165 }
7166
James Mattis45d81842021-01-10 14:24:24 -08007167 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7168 // Creating a defensive copy to prevent the sender from modifying the list being
7169 // reflected in the return value of this method.
7170 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007171 return Collections.unmodifiableList(tempRequests);
7172 }
7173
James Mattisb1392002021-03-31 13:57:52 -07007174 void linkDeathRecipient() {
7175 if (null != mBinder) {
7176 try {
7177 mBinder.linkToDeath(this, 0);
7178 } catch (RemoteException e) {
7179 binderDied();
7180 }
7181 }
7182 }
7183
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007184 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007185 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007186 try {
7187 mBinder.unlinkToDeath(this, 0);
7188 } catch (NoSuchElementException e) {
7189 // Temporary workaround for b/194394697 pending analysis of additional logs
7190 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7191 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007192 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007193 }
7194
paulhu48291862021-07-14 14:53:57 +08007195 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7196 // Compare two preference orders.
7197 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007198 }
7199
paulhu48291862021-07-14 14:53:57 +08007200 int getPreferenceOrderForNetd() {
7201 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7202 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7203 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007204 }
paulhu48291862021-07-14 14:53:57 +08007205 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007206 }
7207
James Mattis4fce5d12020-11-12 15:53:42 -08007208 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007209 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007210 // As an immutable collection, mRequests cannot change by the time the
7211 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7212 // is acceptable. Use handleReleaseNetworkRequest and not directly
7213 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7214 // the app already unregistered the request.
7215 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7216 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007217 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007218
James Mattis4fce5d12020-11-12 15:53:42 -08007219 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007220 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007221 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7222 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007223 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007224 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007225 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007226 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007227 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007228 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007229 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007230 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007231 }
7232
Junyu Lai00d92df2022-07-05 11:01:52 +08007233 // Keep backward compatibility since the ServiceSpecificException is used by
7234 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7235 public static class RequestInfoPerUidCounter extends PerUidCounter {
7236 RequestInfoPerUidCounter(int maxCountPerUid) {
7237 super(maxCountPerUid);
7238 }
7239
7240 @Override
7241 public synchronized void incrementCountOrThrow(int uid) {
7242 try {
7243 super.incrementCountOrThrow(uid);
7244 } catch (IllegalStateException e) {
7245 throw new ServiceSpecificException(
7246 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7247 "Uid " + uid + " exceeded its allotted requests limit");
7248 }
7249 }
7250
7251 @Override
7252 public synchronized void decrementCountOrThrow(int uid) {
7253 throw new UnsupportedOperationException("Use decrementCount instead.");
7254 }
7255
7256 public synchronized void decrementCount(int uid) {
7257 try {
7258 super.decrementCountOrThrow(uid);
7259 } catch (IllegalStateException e) {
7260 logwtf("Exception when decrement per uid request count: ", e);
7261 }
7262 }
7263 }
7264
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007265 // This checks that the passed capabilities either do not request a
7266 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007267 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007268 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007269 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007270 throw new SecurityException("Insufficient permissions to request a specific SSID");
7271 }
paulhu1a407652019-03-22 16:35:06 +08007272
7273 if (nc.hasSignalStrength()
7274 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7275 throw new SecurityException(
7276 "Insufficient permissions to request a specific signal strength");
7277 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007278 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007279
junyulai2217bec2021-04-14 23:33:31 +08007280 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007281 enforceNetworkFactoryPermission();
7282 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007283 }
7284
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007285 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007286 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007287 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007288 // mNetworkRequests may contain the same value multiple times in case of
7289 // multilayer requests. It won't matter in this case because the thresholds
7290 // will then be the same and be deduplicated as they enter the `thresholds` set.
7291 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007292 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7293 for (final NetworkRequest req : nri.mRequests) {
7294 if (req.networkCapabilities.hasSignalStrength()
7295 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7296 thresholds.add(req.networkCapabilities.getSignalStrength());
7297 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007298 }
7299 }
7300 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007301 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007302 }
7303
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007304 private void updateSignalStrengthThresholds(
7305 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007306 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007307
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007308 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007309 String detail;
7310 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7311 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7312 } else {
7313 detail = reason;
7314 }
7315 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007316 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007317 }
7318
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007319 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007320 }
7321
Chalard Jeandd421992021-12-16 23:16:02 +09007322 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007323 if (nc == null) {
7324 return;
7325 }
7326 NetworkSpecifier ns = nc.getNetworkSpecifier();
7327 if (ns == null) {
7328 return;
7329 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007330 if (ns instanceof MatchAllNetworkSpecifier) {
7331 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7332 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007333 }
7334
Chalard Jeandd421992021-12-16 23:16:02 +09007335 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007336 ensureValidNetworkSpecifier(nc);
7337 if (nc.isPrivateDnsBroken()) {
7338 throw new IllegalArgumentException("Can't request broken private DNS");
7339 }
Chalard Jeande665262022-02-25 16:12:12 +09007340 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007341 throw new IllegalArgumentException("Can't request access UIDs");
7342 }
lucasline117e2e2019-10-22 18:27:33 +08007343 }
7344
Chalard Jeandd421992021-12-16 23:16:02 +09007345 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7346 ensureListenableCapabilities(nc);
7347 final String badCapability = nc.describeFirstNonRequestableCapability();
7348 if (badCapability != null) {
7349 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7350 }
7351 }
7352
Chiachang Wang3bc52762021-11-25 14:17:57 +08007353 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7354 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007355 private boolean isTargetSdkAtleast(int version, int callingUid,
7356 @NonNull String callingPackageName) {
7357 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007358 final PackageManager pm =
7359 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007360 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007361 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007362 if (callingVersion < version) return false;
7363 } catch (PackageManager.NameNotFoundException e) { }
7364 return true;
7365 }
7366
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007367 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007368 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007369 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007370 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007371 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007372 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007373 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7374 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007375 throw new SecurityException("Insufficient permissions to specify legacy type");
7376 }
markchienfac84a22020-03-18 21:16:15 +08007377 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007378 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007379 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007380 // Privileged callers can track the default network of another UID by passing in a UID.
7381 if (asUid != Process.INVALID_UID) {
7382 enforceSettingsPermission();
7383 } else {
7384 asUid = callingUid;
7385 }
junyulaiad010792021-01-11 16:53:38 +08007386 final NetworkRequest.Type reqType;
7387 try {
7388 reqType = NetworkRequest.Type.values()[reqTypeInt];
7389 } catch (ArrayIndexOutOfBoundsException e) {
7390 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7391 }
7392 switch (reqType) {
7393 case TRACK_DEFAULT:
7394 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007395 // is unused and will be replaced by ones appropriate for the UID (usually, the
7396 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007397 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007398 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007399 enforceAccessPermission();
7400 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007401 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007402 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007403 networkCapabilities = new NetworkCapabilities(defaultNc);
7404 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007405 case BACKGROUND_REQUEST:
7406 enforceNetworkStackOrSettingsPermission();
7407 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007408 case REQUEST:
7409 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7410 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007411 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007412 // TODO: this is incorrect. We mark the request as metered or not depending on
7413 // the state of the app when the request is filed, but we never change the
7414 // request if the app changes network state. http://b/29964605
7415 enforceMeteredApnPolicy(networkCapabilities);
7416 break;
junyulai1b1c8742021-03-12 20:05:08 +08007417 case LISTEN_FOR_BEST:
7418 enforceAccessPermission();
7419 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7420 break;
junyulaiad010792021-01-11 16:53:38 +08007421 default:
7422 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007423 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007424 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007425 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007426 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007427
junyulai1b1c8742021-03-12 20:05:08 +08007428 // Enforce FOREGROUND if the caller does not have permission to use background network.
7429 if (reqType == LISTEN_FOR_BEST) {
7430 restrictBackgroundRequestForCaller(networkCapabilities);
7431 }
7432
7433 // Set the UID range for this request to the single UID of the requester, unless the
7434 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007435 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7436 // are no visible methods to set the UIDs, an app could use reflection to try and get
7437 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007438 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007439 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7440 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007441
Etan Cohen85000162017-02-05 10:42:27 -08007442 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007443 throw new IllegalArgumentException("Bad timeout specified");
7444 }
Etan Cohen9786d922015-11-18 10:56:15 -08007445
James Mattis3ce3d3c2021-02-09 18:18:28 -08007446 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007447 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007448 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007449 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007450 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007451 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007452
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007453 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7454 // copied from the default request above. (This is necessary to ensure, for example, that
7455 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7456 // changes don't alter request matching.
7457 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7458 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007459 throw new IllegalStateException(
7460 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007461 + networkCapabilities + " vs. " + defaultNc);
7462 }
7463
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007464 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007465 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007466 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007467 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007468 }
7469 return networkRequest;
7470 }
7471
James Mattis3ce3d3c2021-02-09 18:18:28 -08007472 /**
7473 * Return the nri to be used when registering a network request. Specifically, this is used with
7474 * requests registered to track the default request. If there is currently a per-app default
7475 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7476 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007477 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7478 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007479 * @param nr the network request for the nri.
7480 * @param msgr the messenger for the nri.
7481 * @param binder the binder for the nri.
7482 * @param callingAttributionTag the calling attribution tag for the nri.
7483 * @return the nri to register.
7484 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007485 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007486 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007487 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007488 @Nullable String callingAttributionTag) {
7489 final List<NetworkRequest> requests;
7490 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7491 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007492 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007493 } else {
7494 requests = Collections.singletonList(nr);
7495 }
Roshan Pius951c0032020-12-22 15:10:42 -08007496 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007497 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007498 }
7499
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007500 private boolean shouldCheckCapabilitiesDeclaration(
7501 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7502 @NonNull final String callingPackageName) {
7503 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7504 // Only run the check if the change is enabled.
7505 if (!mDeps.isChangeEnabled(
7506 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7507 callingPackageName, user)) {
7508 return false;
7509 }
7510
7511 return networkCapabilities.hasCapability(
7512 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7513 || networkCapabilities.hasCapability(
7514 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7515 }
7516
7517 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7518 @NonNull final NetworkCapabilities networkCapabilities) {
7519 // This check is added to fix the linter error for "current min is 30", which is not going
7520 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007521 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007522 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7523 return;
7524 }
7525 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007526 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007527 try {
7528 synchronized (mSelfCertifiedCapabilityCache) {
7529 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7530 callerPackageName);
7531 if (applicationNetworkCapabilities == null) {
7532 final PackageManager packageManager = mContext.getPackageManager();
7533 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7534 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7535 callerPackageName
7536 );
7537 final XmlResourceParser parser = packageManager
7538 .getResourcesForApplication(callerPackageName)
7539 .getXml(networkSliceProperty.getResourceId());
7540 applicationNetworkCapabilities =
7541 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7542 mSelfCertifiedCapabilityCache.put(callerPackageName,
7543 applicationNetworkCapabilities);
7544 }
7545
7546 }
7547 } catch (PackageManager.NameNotFoundException ne) {
7548 throw new SecurityException(
7549 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7550 + " property");
7551 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7552 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007553 } finally {
7554 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007555 }
7556
7557 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7558 networkCapabilities);
7559 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007560 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007561 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007562 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7563 callingPackageName)) {
7564 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7565 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007566 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007567 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7568 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7569 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7570 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007571 }
junyulai96bd9fe2022-03-08 17:36:42 +08007572 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007573 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007574 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007575 }
7576 }
7577
fenglu3f357402015-03-20 11:29:56 -07007578 @Override
fenglub00f4882015-04-21 17:12:05 -07007579 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007580 enforceAccessPermission();
7581 NetworkAgentInfo nai = null;
7582 if (network == null) {
7583 return false;
7584 }
7585 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007586 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007587 }
7588 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007589 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007590 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007591 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007592 Integer uidReqs = mBandwidthRequests.get(uid);
7593 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007594 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007595 }
7596 mBandwidthRequests.put(uid, ++uidReqs);
7597 }
fenglu3f357402015-03-20 11:29:56 -07007598 return true;
7599 }
7600 return false;
7601 }
7602
Felipe Leme0a5ae422016-06-20 16:36:29 -07007603 private boolean isSystem(int uid) {
7604 return uid < Process.FIRST_APPLICATION_UID;
7605 }
fenglu3f357402015-03-20 11:29:56 -07007606
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007607 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007608 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007609 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007610 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007611 return;
7612 }
Hugo Benichi39621362017-02-11 17:04:43 +09007613 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7614 // Policy already enforced.
7615 return;
7616 }
paulhuaf50d7d2020-12-24 19:47:34 +08007617 final long ident = Binder.clearCallingIdentity();
7618 try {
7619 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7620 // If UID is restricted, don't allow them to bring up metered APNs.
7621 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7622 }
7623 } finally {
7624 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007625 }
7626 }
7627
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007628 @Override
7629 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007630 PendingIntent operation, @NonNull String callingPackageName,
7631 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007632 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007633 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007634 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007635 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007636 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007637 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007638 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007639 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007640 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007641 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7642 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007643
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007644 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007645 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007646 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7647 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007648 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007649 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7650 nri));
7651 return networkRequest;
7652 }
7653
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007654 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7655 mHandler.sendMessageDelayed(
7656 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007657 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007658 }
7659
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007660 @Override
7661 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007662 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007663 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007664 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007665 }
7666
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007667 // In order to implement the compatibility measure for pre-M apps that call
7668 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7669 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7670 // This ensures it has permission to do so.
7671 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7672 if (nc == null) {
7673 return false;
7674 }
7675 int[] transportTypes = nc.getTransportTypes();
7676 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7677 return false;
7678 }
7679 try {
7680 mContext.enforceCallingOrSelfPermission(
7681 android.Manifest.permission.ACCESS_WIFI_STATE,
7682 "ConnectivityService");
7683 } catch (SecurityException e) {
7684 return false;
7685 }
7686 return true;
7687 }
7688
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007689 @Override
7690 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007691 Messenger messenger, IBinder binder,
7692 @NetworkCallback.Flag int callbackFlags,
7693 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007694 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007695 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7696 enforceAccessPermission();
7697 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007698
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007699 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007700 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007701 Binder.getCallingPid(), callingUid, callingPackageName);
7702 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007703 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7704 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7705 // onLost and onAvailable callbacks when networks move in and out of the background.
7706 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7707 // can't request networks.
7708 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007709 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007710
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007711 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007712 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007713 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007714 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007715 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007716 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007717
7718 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7719 return networkRequest;
7720 }
7721
7722 @Override
7723 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007724 PendingIntent operation, @NonNull String callingPackageName,
7725 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007726 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007727 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007728 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7729 enforceAccessPermission();
7730 }
Chalard Jeandd421992021-12-16 23:16:02 +09007731 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007732 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007733 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007734 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007735 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007736
7737 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007738 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007739 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7740 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007741 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007742
WeiZhang1cc3f172021-06-03 19:02:04 -05007743 mHandler.sendMessage(mHandler.obtainMessage(
7744 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007745 }
7746
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007747 /** Returns the next Network provider ID. */
7748 public final int nextNetworkProviderId() {
7749 return mNextNetworkProviderId.getAndIncrement();
7750 }
7751
Erik Kline0c04b742016-07-07 16:50:58 +09007752 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007753 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007754 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007755 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007756 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007757 }
7758
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007759 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7760 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007761 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7762 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7763 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007764 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007765 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007766 return;
7767 }
7768
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007769 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7770 mNetworkProviderInfos.put(npi.messenger, npi);
7771 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007772 }
7773
7774 @Override
7775 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007776 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007777 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007778 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007779 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007780 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7781 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007782 }
7783
7784 @Override
7785 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007786 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007787 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007788 }
7789
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007790 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007791 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007792 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7793 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007794 Objects.requireNonNull(score);
7795 Objects.requireNonNull(caps);
7796 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007797 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007798 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007799 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7800 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007801 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7802 }
7803
Chalard Jeanbb902a52021-08-18 01:35:19 +09007804 private void updateOfferScore(final NetworkOffer offer) {
7805 final boolean yieldToBadWiFi =
7806 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7807 final NetworkOffer newOffer = new NetworkOffer(
7808 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7809 offer.caps, offer.callback, offer.providerId);
7810 if (offer.equals(newOffer)) return;
7811 handleRegisterNetworkOffer(newOffer);
7812 }
7813
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007814 @Override
7815 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007816 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007817 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7818 }
7819
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007820 private void handleUnregisterNetworkProvider(Messenger messenger) {
7821 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7822 if (npi == null) {
7823 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007824 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007825 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007826 // Unregister all the offers from this provider
7827 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7828 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007829 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007830 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7831 toRemove.add(noi);
7832 }
7833 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007834 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007835 handleUnregisterNetworkOffer(noi);
7836 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007837 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007838 }
7839
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007840 @Override
James Mattisf7027322020-12-13 16:28:14 -08007841 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007842 if (request.hasTransport(TRANSPORT_TEST)) {
7843 enforceNetworkFactoryOrTestNetworksPermission();
7844 } else {
7845 enforceNetworkFactoryPermission();
7846 }
James Mattisf7027322020-12-13 16:28:14 -08007847 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7848 if (nri != null) {
7849 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7850 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7851 mHandler.post(() -> handleReleaseNetworkRequest(
7852 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7853 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007854 }
7855
Paul Jensen1f567382015-02-13 14:18:39 -05007856 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7857 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007858 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007859 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007860 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007861 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007862 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007863
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007864 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007865 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007866 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007867
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007868 // UID ranges for users that are currently blocked by VPNs.
7869 // This array is accessed and iterated on multiple threads without holding locks, so its
7870 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7871 // (on the handler thread).
7872 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7873
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007874 // Must only be accessed on the handler thread
7875 @NonNull
7876 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7877
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007878 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007879 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007880
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007881 // Current OEM network preferences. This object must only be written to on the handler thread.
7882 // Since it is immutable and always non-null, other threads may read it if they only care
7883 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007884 @NonNull
7885 private OemNetworkPreferences mOemNetworkPreferences =
7886 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007887 // Current per-profile network preferences. This object follows the same threading rules as
7888 // the OEM network preferences above.
7889 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007890 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7891 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007892
lucaslin3ba7cc22022-12-19 02:35:33 +00007893 // Current VPN network preferences. This object follows the same threading rules as the OEM
7894 // network preferences above.
7895 @NonNull
7896 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7897 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7898
paulhu51f77dc2021-06-07 02:34:20 +00007899 // A set of UIDs that should use mobile data preferentially if available. This object follows
7900 // the same threading rules as the OEM network preferences above.
7901 @NonNull
7902 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7903
James Mattiscb1e0362021-04-06 17:07:42 -07007904 // OemNetworkPreferences activity String log entries.
7905 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7906 @NonNull
7907 private final LocalLog mOemNetworkPreferencesLogs =
7908 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7909
James Mattis02220e22021-03-13 19:27:21 -08007910 /**
7911 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7912 * @param packageName the package name to check existence of a mapping for.
7913 * @return true if a mapping exists, false otherwise
7914 */
7915 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7916 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7917 }
7918
James Mattise3ef1912020-12-20 11:09:58 -08007919 // The always-on request for an Internet-capable network that apps without a specific default
7920 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007921 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007922 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007923 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007924 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007925 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007926 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007927 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007928
James Mattisd31bdfa2020-12-23 16:37:26 -08007929 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7930 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7931 }
7932
7933 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007934 * Return the default network request currently tracking the given uid.
7935 * @param uid the uid to check.
7936 * @return the NetworkRequestInfo tracking the given uid.
7937 */
7938 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007939 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007940 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007941 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007942 // Checking the first request is sufficient as only multilayer requests will have more
7943 // than one request and for multilayer, all requests will track the same uids.
7944 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007945 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007946 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007947 highestPriorityNri = nri;
7948 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007949 }
7950 }
paulhuaa0743d2021-05-26 21:56:03 +08007951 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007952 }
7953
7954 /**
7955 * Get a copy of the network requests of the default request that is currently tracking the
7956 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007957 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7958 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007959 * @param requestorUid the uid to check the default for.
7960 * @param requestorPackageName the requestor's package name.
7961 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7962 */
7963 @NonNull
7964 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007965 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007966 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007967 getDefaultRequestTrackingUid(asUid).mRequests,
7968 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007969 }
7970
7971 /**
7972 * Copy the given nri's NetworkRequest collection.
7973 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007974 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7975 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007976 * @param requestorUid the uid to set on the copied collection.
7977 * @param requestorPackageName the package name to set on the copied collection.
7978 * @return the copied NetworkRequest collection.
7979 */
7980 @NonNull
7981 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007982 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7983 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007984 final List<NetworkRequest> requests = new ArrayList<>();
7985 for (final NetworkRequest nr : requestsToCopy) {
7986 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007987 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007988 nr.legacyType, nextNetworkRequestId(), nr.type));
7989 }
7990 return requests;
7991 }
7992
7993 @NonNull
7994 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007995 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7996 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007997 // These capabilities are for a TRACK_DEFAULT callback, so:
7998 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7999 // mDefaultRequest and a per-UID default request.
8000 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008001 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008002 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008003 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8004 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008005 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008006 restrictRequestUidsForCallerAndSetRequestorInfo(
8007 netCap, requestorUid, requestorPackageName);
8008 return netCap;
8009 }
8010
8011 /**
8012 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8013 * @param nr the network request to check for equality against.
8014 * @return the nri if one exists, null otherwise.
8015 */
8016 @Nullable
8017 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8018 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8019 if (nri.getNetworkRequestForCallback().equals(nr)) {
8020 return nri;
8021 }
8022 }
8023 return null;
8024 }
8025
8026 /**
8027 * Check if an nri is currently being managed by per-app default networking.
8028 * @param nri the nri to check.
8029 * @return true if this nri is currently being managed by per-app default networking.
8030 */
8031 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8032 // nri.mRequests.get(0) is only different from the original request filed in
8033 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8034 // functionality therefore if these two don't match, it means this particular nri is
8035 // currently being managed by a per-app default.
8036 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8037 }
8038
8039 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008040 * Determine if an nri is a managed default request that disallows default networking.
8041 * @param nri the request to evaluate
8042 * @return true if device-default networking is disallowed
8043 */
8044 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8045 // Check if this nri is a managed default that supports the default network at its
8046 // lowest priority request.
8047 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8048 final NetworkCapabilities lowestPriorityNetCap =
8049 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8050 return isPerAppDefaultRequest(nri)
8051 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8052 lowestPriorityNetCap));
8053 }
8054
Erik Kline05f2b402015-04-30 12:58:40 +09008055 // Request used to optionally keep mobile data active even when higher
8056 // priority networks like Wi-Fi are active.
8057 private final NetworkRequest mDefaultMobileDataRequest;
8058
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008059 // Request used to optionally keep wifi data active even when higher
8060 // priority networks like ethernet are active.
8061 private final NetworkRequest mDefaultWifiRequest;
8062
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008063 // Request used to optionally keep vehicle internal network always active
8064 private final NetworkRequest mDefaultVehicleRequest;
8065
James Mattisd31bdfa2020-12-23 16:37:26 -08008066 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8067 // network with no service. This NAI should never be matched against, nor should any public API
8068 // ever return the associated network. For this reason, this NAI is not in the list of available
8069 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8070 // default requests that don't support using the device default network which will ultimately
8071 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8072 @VisibleForTesting
8073 final NetworkAgentInfo mNoServiceNetwork;
8074
Chalard Jean5b409c72021-02-04 13:12:59 +09008075 // The NetworkAgentInfo currently satisfying the default request, if any.
8076 private NetworkAgentInfo getDefaultNetwork() {
8077 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008078 }
8079
James Mattis2516da32021-01-31 17:06:19 -08008080 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008081 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008082 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8083 // Currently, all network requests will have the same uids therefore checking the first
8084 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008085 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008086 if (null == uids) {
8087 continue;
8088 }
8089 for (final UidRange range : uids) {
8090 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008091 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008092 highestPriorityNri = nri;
8093 }
James Mattis2516da32021-01-31 17:06:19 -08008094 }
8095 }
8096 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008097 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008098 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008099 }
8100
Varun Ananddf569952019-02-06 10:13:38 -08008101 @Nullable
8102 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8103 return nai != null ? nai.network : null;
8104 }
8105
8106 private void ensureRunningOnConnectivityServiceThread() {
8107 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8108 throw new IllegalStateException(
8109 "Not running on ConnectivityService thread: "
8110 + Thread.currentThread().getName());
8111 }
8112 }
8113
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008114 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008115 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8116 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008117 }
8118
Chalard Jean29d06db2018-05-02 21:14:54 +09008119 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008120 * Returns whether local agents are supported on this device.
8121 *
8122 * Local agents are supported from U on TVs, and from V on all devices.
8123 */
8124 @VisibleForTesting
8125 public boolean areLocalAgentsSupported() {
8126 final PackageManager pm = mContext.getPackageManager();
8127 // Local agents are supported starting on U on TVs and on V on everything else.
8128 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8129 }
8130
8131 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008132 * Register a new agent with ConnectivityService to handle a network.
8133 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008134 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008135 * @param networkInfo the initial info associated with this network. It can be updated later :
8136 * see {@link #updateNetworkInfo}.
8137 * @param linkProperties the initial link properties of this network. They can be updated
8138 * later : see {@link #updateLinkProperties}.
8139 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008140 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008141 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008142 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008143 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008144 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008145 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008146 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008147 public Network registerNetworkAgent(INetworkAgent na,
8148 NetworkInfo networkInfo,
8149 LinkProperties linkProperties,
8150 NetworkCapabilities networkCapabilities,
8151 @NonNull NetworkScore initialScore,
8152 @Nullable LocalNetworkConfig localNetworkConfig,
8153 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008154 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008155 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8156 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8157 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008158 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008159 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008160 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008161 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008162 } else {
8163 enforceNetworkFactoryPermission();
8164 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008165 final boolean hasLocalCap =
8166 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8167 if (hasLocalCap && !areLocalAgentsSupported()) {
8168 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8169 throw new IllegalArgumentException("Local agents are not supported in this version");
8170 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008171 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8172 if (hasLocalCap != hasLocalNetworkConfig) {
8173 throw new IllegalArgumentException(null != localNetworkConfig
8174 ? "Only local network agents can have a LocalNetworkConfig"
8175 : "Local network agents must have a LocalNetworkConfig"
8176 );
8177 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008178
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008179 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008180 final long token = Binder.clearCallingIdentity();
8181 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008182 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008183 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8184 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008185 } finally {
8186 Binder.restoreCallingIdentity(token);
8187 }
8188 }
8189
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008190 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008191 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008192 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8193 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008194 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008195
Chalard Jeandbc46952022-02-02 00:14:18 +09008196 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8197 // and mutate them at any time.
8198 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8199 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8200 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008201 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008202
Chalard Jean366c5252022-01-25 18:27:53 +09008203 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008204 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008205 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8206 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008207 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008208 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008209 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8210 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8211 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008212
Chalard Jeandbc46952022-02-02 00:14:18 +09008213 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008214 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008215 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008216 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008217 mDeps.getNetworkStack().makeNetworkMonitor(
8218 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008219 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8220 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008221 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008222 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008223 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008224 }
8225
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008226 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008227 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008228 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008229 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008230 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008231 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8232 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8233 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008234
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008235 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008236
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008237 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008238 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008239 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008240 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008241
8242 try {
8243 networkMonitor.start();
8244 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008245 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008246 }
Chalard Jean366c5252022-01-25 18:27:53 +09008247
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008248 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008249 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008250 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008251 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008252 }
8253
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008254 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8255 @NonNull public final NetworkOffer offer;
8256
8257 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8258 this.offer = offer;
8259 }
8260
8261 @Override
8262 public void binderDied() {
8263 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8264 }
8265 }
8266
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008267 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8268 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8269 if (npi.providerId == providerId) return true;
8270 }
8271 return false;
8272 }
8273
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008274 /**
8275 * Register or update a network offer.
8276 * @param newOffer The new offer. If the callback member is the same as an existing
8277 * offer, it is an update of that offer.
8278 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008279 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008280 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8281 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008282 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008283 // This may actually happen if a provider updates its score or registers and then
8284 // immediately unregisters. The offer would still be in the handler queue, but the
8285 // provider would have been removed.
8286 if (DBG) log("Received offer from an unregistered provider");
8287 return;
8288 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008289 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8290 if (null != existingOffer) {
8291 handleUnregisterNetworkOffer(existingOffer);
8292 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008293 if (DBG) {
8294 // handleUnregisterNetworkOffer has already logged the old offer
8295 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8296 }
8297 } else {
8298 if (DBG) {
8299 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8300 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008301 }
8302 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8303 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008304 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008305 } catch (RemoteException e) {
8306 noi.binderDied();
8307 return;
8308 }
8309 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008310 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008311 }
8312
8313 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8314 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008315 if (DBG) {
8316 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8317 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008318
8319 // If the provider removes the offer and dies immediately afterwards this
8320 // function may be called twice in a row, but the array will no longer contain
8321 // the offer.
8322 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008323 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008324 }
8325
8326 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8327 @NonNull final INetworkOfferCallback callback) {
8328 ensureRunningOnConnectivityServiceThread();
8329 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008330 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008331 }
8332 return null;
8333 }
8334
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008335 /**
8336 * Called when receiving LinkProperties directly from a NetworkAgent.
8337 * Stores into |nai| any data coming from the agent that might also be written to the network's
8338 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8339 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008340 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008341 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008342 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8343 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008344 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008345 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008346 }
8347
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008348 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008349 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008350 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008351
Lorenzo Colittid523d142020-04-01 20:16:30 +09008352 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8353 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8354 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008355 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008356
Suprabh Shukla1e312032023-01-24 03:36:37 -08008357 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008358
8359 // update filtering rules, need to happen after the interface update so netd knows about the
8360 // new interface (the interface name -> index map becomes initialized)
8361 updateVpnFiltering(newLp, oldLp, networkAgent);
8362
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008363 updateMtu(newLp, oldLp);
8364 // TODO - figure out what to do for clat
8365// for (LinkProperties lp : newLp.getStackedLinks()) {
8366// updateMtu(lp, null);
8367// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008368 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008369 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008370 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8371 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008372
Erik Klineb9888902016-04-05 13:30:49 +09008373 updateRoutes(newLp, oldLp, netId);
8374 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008375 // Make sure LinkProperties represents the latest private DNS status.
8376 // This does not need to be done before updateDnses because the
8377 // LinkProperties are not the source of the private DNS configuration.
8378 // updateDnses will fetch the private DNS configuration from DnsManager.
8379 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008380
Chalard Jean5b409c72021-02-04 13:12:59 +09008381 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008382 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008383 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008384 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008385 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008386
8387 updateWakeOnLan(newLp);
8388
Hai Shalome58bdc62021-01-11 18:45:34 -08008389 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8390 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8391 // does, it needs to be merged here.
8392 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8393 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008394
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008395 // TODO - move this check to cover the whole function
8396 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008397 synchronized (networkAgent) {
8398 networkAgent.linkProperties = newLp;
8399 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008400 // Start or stop DNS64 detection and 464xlat according to network state.
8401 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008402 // Notify NSS when relevant events happened. Currently, NSS only cares about
8403 // interface changed to update clat interfaces accounting.
8404 final boolean interfacesChanged = oldLp == null
8405 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8406 if (interfacesChanged) {
8407 notifyIfacesChangedForNetworkStats();
8408 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008409 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8410 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008411 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008412 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008413
8414 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008415 }
8416
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008417 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8418 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8419 }
8420
Hai Shalome58bdc62021-01-11 18:45:34 -08008421 /**
8422 * @param naData captive portal data from NetworkAgent
8423 * @param apiData captive portal data from capport API
8424 */
8425 @Nullable
8426 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8427 CaptivePortalData apiData) {
8428 if (naData == null || apiData == null) {
8429 return naData == null ? apiData : naData;
8430 }
8431 final CaptivePortalData.Builder captivePortalBuilder =
8432 new CaptivePortalData.Builder(naData);
8433
8434 if (apiData.isCaptive()) {
8435 captivePortalBuilder.setCaptive(true);
8436 }
8437 if (apiData.isSessionExtendable()) {
8438 captivePortalBuilder.setSessionExtendable(true);
8439 }
8440 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8441 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8442 // otherwise data would be inconsistent. Prefer the capport API info if present,
8443 // as it can generally be refreshed more often.
8444 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8445 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8446 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8447 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8448 // No source has time / bytes remaining information: surface the newest refresh time
8449 // for other fields
8450 captivePortalBuilder.setRefreshTime(
8451 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8452 }
8453
Hai Shalom7c6ab402021-02-04 19:34:06 -08008454 // Prioritize the user portal URL from the network agent if the source is authenticated.
8455 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8456 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8457 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8458 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008459 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008460 // Prioritize the venue information URL from the network agent if the source is
8461 // authenticated.
8462 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8463 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8464 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8465 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008466 }
8467 return captivePortalBuilder.build();
8468 }
8469
Suprabh Shukla53e16392023-04-26 18:47:36 -07008470 @VisibleForTesting
8471 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008472 // This needs to be kept in sync and backwards compatible with the decoding logic in
8473 // NetdEventListenerService, which is non-mainline code.
8474 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8475 }
8476
Suprabh Shukla75642282023-04-25 23:15:43 -07008477 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8478 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8479 return true;
8480 }
8481 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8482 return true;
8483 }
8484 return false;
8485 }
8486
Suprabh Shukla1e312032023-01-24 03:36:37 -08008487 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008488 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008489 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008490 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008491 return;
8492 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008493
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008494 // Mask/mark of zero will not detect anything interesting.
8495 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008496 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008497 return;
8498 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008499
Suprabh Shukla1e312032023-01-24 03:36:37 -08008500 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008501 try {
8502 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008503 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008504 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008505 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008506 }
8507 } catch (Exception e) {
8508 loge("Exception modifying wakeup packet monitoring: " + e);
8509 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008510 }
8511
Junyu Lai970963e2022-10-25 15:46:47 +08008512 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008513 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008514 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008515 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008516 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008517 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008518 for (final String iface : interfaceDiff.added) {
8519 try {
8520 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008521 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008522 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008523 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008524 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008525 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008526 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008527 }
Paul Jensenbff73492014-04-28 10:33:11 -04008528 }
8529 }
Chalard Jean9589e722019-11-19 19:03:53 +09008530 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008531 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008532 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008533 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008534 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008535 } catch (Exception e) {
8536 loge("Exception removing interface: " + e);
8537 }
8538 }
8539 }
8540
Paul Jensene0fd4a82014-08-06 15:51:33 -04008541 /**
8542 * Have netd update routes from oldLp to newLp.
8543 * @return true if routes changed between oldLp and newLp
8544 */
Junyu Lai970963e2022-10-25 15:46:47 +08008545 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8546 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008547 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008548 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8549 new CompareOrUpdateResult<>(
8550 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008551 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008552 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008553
8554 // add routes before removing old in case it helps with continuous connectivity
8555
Chalard Jean9dd11612018-06-04 16:52:49 +09008556 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008557 for (RouteInfo route : routeDiff.added) {
8558 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008559 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008560 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008561 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008562 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008563 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008564 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008565 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008566 }
8567 }
8568 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008569 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008570 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008571 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008572 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008573 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008574 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008575 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008576 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008577 }
8578 }
8579
8580 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008581 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008582 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008583 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008584 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008585 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008586 }
8587 }
Tyler Weare4314862019-12-05 14:55:30 -08008588
8589 for (RouteInfo route : routeDiff.updated) {
8590 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8591 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008592 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008593 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008594 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008595 }
8596 }
8597 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8598 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008599 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008600
Junyu Lai970963e2022-10-25 15:46:47 +08008601 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8602 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008603 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8604 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008605 }
Erik Klineb9888902016-04-05 13:30:49 +09008606
Erik Kline31b4a9e2018-01-11 21:07:29 +09008607 if (DBG) {
8608 final Collection<InetAddress> dnses = newLp.getDnsServers();
8609 log("Setting DNS servers for network " + netId + " to " + dnses);
8610 }
Erik Klineb9888902016-04-05 13:30:49 +09008611 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008612 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008613 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008614 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008615 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008616 }
Erik Kline54e35c02017-04-07 15:29:29 +09008617 }
8618
Junyu Lai970963e2022-10-25 15:46:47 +08008619 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8620 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008621 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8622 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008623 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8624 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008625
8626 if (!wasFiltering && !needsFiltering) {
8627 // Nothing to do.
8628 return;
8629 }
8630
8631 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8632 // Nothing changed.
8633 return;
8634 }
8635
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008636 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008637 if (ranges == null || ranges.isEmpty()) {
8638 return;
8639 }
8640
Qingxi Libb8da982020-01-17 17:54:27 -08008641 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008642 // TODO: this create a window of opportunity for apps to receive traffic between the time
8643 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008644 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008645 // old rules are being removed.
8646 if (wasFiltering) {
8647 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8648 }
8649 if (needsFiltering) {
8650 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8651 }
8652 }
8653
Valentin Iftime9fa35092019-09-24 13:32:13 +02008654 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008655 if (mWolSupportedInterfaces == null) {
8656 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008657 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008658 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008659 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8660 }
8661
Luke Huangb913c812018-08-24 20:33:16 +08008662 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008663 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008664 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008665 }
8666 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008667 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008668 }
Luke Huangb913c812018-08-24 20:33:16 +08008669 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008670 }
8671
Chalard Jean62edfd82019-12-02 18:39:29 +09008672 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8673 @NonNull final NetworkCapabilities newNc) {
8674 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8675 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008676 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008677 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008678 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008679 } catch (RemoteException | ServiceSpecificException e) {
8680 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008681 }
8682 }
8683 }
8684
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008685 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008686 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008687 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008688 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008689 underlyingNetworks = underlyingNetworksOrDefault(
8690 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008691 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008692 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8693 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008694 // metered if any underlying is metered, or originally declared metered by the agent.
8695 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008696 boolean roaming = false; // roaming if any underlying is roaming
8697 boolean congested = false; // congested if any underlying is congested
8698 boolean suspended = true; // suspended if all underlying are suspended
8699
8700 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008701 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008702 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008703 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008704 for (Network underlyingNetwork : underlyingNetworks) {
8705 final NetworkAgentInfo underlying =
8706 getNetworkAgentInfoForNetwork(underlyingNetwork);
8707 if (underlying == null) continue;
8708
8709 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8710 hadUnderlyingNetworks = true;
8711 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008712 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008713 }
8714
8715 // Merge capabilities of this underlying network. For bandwidth, assume the
8716 // worst case.
8717 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8718 underlyingCaps.getLinkDownstreamBandwidthKbps());
8719 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8720 underlyingCaps.getLinkUpstreamBandwidthKbps());
8721 // If this underlying network is metered, the VPN is metered (it may cost money
8722 // to send packets on this network).
8723 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8724 // If this underlying network is roaming, the VPN is roaming (the billing structure
8725 // is different than the usual, local one).
8726 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8727 // If this underlying network is congested, the VPN is congested (the current
8728 // condition of the network affects the performance of this network).
8729 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8730 // If this network is not suspended, the VPN is not suspended (the VPN
8731 // is able to transfer some data).
8732 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008733 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008734 }
8735 }
8736 if (!hadUnderlyingNetworks) {
8737 // No idea what the underlying networks are; assume reasonable defaults
8738 metered = true;
8739 roaming = false;
8740 congested = false;
8741 suspended = false;
8742 }
8743
Chalard Jean1d420b32022-10-12 16:39:37 +09008744 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008745 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8746 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8747 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8748 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8749 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8750 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008751 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008752 }
8753
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008754 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008755 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8756 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8757 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008758 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008759 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008760 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008761 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008762 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8763 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008764 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008765 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008766 if (nai.everConnected()
8767 && !nai.isVPN()
8768 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008769 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008770 // does not cause any request (that is not a listen) currently matching that agent to
8771 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008772 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008773 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008774 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008775 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008776 }
8777
Paul Jensen53f08952015-06-16 14:27:36 -04008778 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008779 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008780 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008781 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008782 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008783 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008784 }
Chalard Jean254bd162022-08-25 13:04:51 +09008785 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008786 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008787 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008788 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008789 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008790 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008791 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008792 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008793 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008794 }
Chalard Jean254bd162022-08-25 13:04:51 +09008795 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008796 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8797 } else {
8798 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8799 }
lucasline117e2e2019-10-22 18:27:33 +08008800 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008801
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008802 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008803 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8804 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008805 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008806 }
8807
Lorenzo Colittibd079452021-07-02 11:47:57 +09008808 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008809 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008810 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008811 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008812 }
8813
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008814 return newNc;
8815 }
8816
Lorenzo Colitti44840702021-01-11 22:27:57 +09008817 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8818 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8819 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8820 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8821 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8822 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8823 if (prevSuspended != suspended) {
8824 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8825 // onResumed have been removed.
8826 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8827 : ConnectivityManager.CALLBACK_RESUMED);
8828 }
8829 if (prevSuspended != suspended || prevRoaming != roaming) {
8830 // updateNetworkInfo will mix in the suspended info from the capabilities and
8831 // take appropriate action for the network having possibly changed state.
8832 updateNetworkInfo(nai, nai.networkInfo);
8833 }
8834 }
8835
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008836 /**
8837 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8838 *
8839 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8840 * capabilities we manage and store in {@code nai}, such as validated status and captive
8841 * portal status)
8842 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8843 * potentially triggers rematches.
8844 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8845 * change.)
8846 *
8847 * @param oldScore score of the network before any of the changes that prompted us
8848 * to call this function.
8849 * @param nai the network having its capabilities updated.
8850 * @param nc the new network capabilities.
8851 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008852 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008853 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008854 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008855 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008856 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8857 if (null != differences) {
8858 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8859 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008860 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008861 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008862
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008863 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008864 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008865 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008866
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008867 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008868 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8869 // the change we're processing can't affect any requests, it can only affect the listens
8870 // on this network. We might have been called by rematchNetworkAndRequests when a
8871 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008872 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008873 } else {
8874 // If the requestable capabilities have changed or the score changed, we can't have been
8875 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008876 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008877 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008878 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008879 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008880
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008881 final boolean oldMetered = prevNc.isMetered();
8882 final boolean newMetered = newNc.isMetered();
8883 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008884
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008885 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008886 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8887 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008888 }
junyulaif2c67e42018-08-07 19:50:45 +08008889
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008890 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8891 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008892
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008893 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008894 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008895 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008896 }
8897
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008898 // This network might have been underlying another network. Propagate its capabilities.
8899 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008900
Ken Chen5a35cf92023-10-07 07:54:22 +08008901 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08008902 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08008903 }
lucaslin53e8a262021-06-08 01:43:59 +08008904
8905 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008906 }
8907
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008908 /** Convenience method to update the capabilities for a given network. */
8909 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008910 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008911 }
8912
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008913 private void updateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
8914 @NonNull final LocalNetworkConfig config) {
8915 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK)) {
8916 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
8917 return;
8918 }
8919 // TODO : actually apply the diff.
8920 nai.localNetworkConfig = config;
8921 }
8922
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008923 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008924 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008925 *
8926 * Ingress interface filtering enforces that all apps under the given network can only receive
8927 * packets from the network's interface (and loopback). This is important for VPNs because
8928 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8929 * non-VPN interfaces.
8930 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008931 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008932 * 1. the network is an app VPN (not legacy VPN)
8933 * 2. the VPN does not allow bypass
8934 * 3. the VPN is fully-routed
8935 * 4. the VPN interface is non-null
8936 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008937 * @see INetd#firewallAddUidInterfaceRules
8938 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008939 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008940 @Nullable
8941 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008942 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008943 if (nc == null || lp == null) return null;
8944 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008945 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008946 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008947 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008948 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008949 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008950 && !lp.hasExcludeRoute()) {
8951 return lp.getInterfaceName();
8952 }
8953 return null;
8954 }
8955
8956 /**
8957 * Returns whether we need to set interface filtering rule or not
8958 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008959 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008960 String isolationIface) {
8961 // Allow rules are always needed if VPN isolation is enabled.
8962 if (isolationIface != null) return true;
8963
8964 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8965 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8966 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09008967 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008968 }
8969
Chiachang Wang28afaff2020-12-10 22:24:47 +08008970 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8971 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8972 int index = 0;
8973 for (UidRange range : ranges) {
8974 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8975 index++;
8976 }
8977 return stableRanges;
8978 }
8979
Chalard Jeane6c95272022-01-25 21:04:21 +09008980 private static UidRangeParcel[] intsToUidRangeStableParcels(
8981 final @NonNull ArraySet<Integer> uids) {
8982 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8983 int index = 0;
8984 for (int uid : uids) {
8985 stableRanges[index] = new UidRangeParcel(uid, uid);
8986 index++;
8987 }
8988 return stableRanges;
8989 }
8990
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008991 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8992 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8993 for (int i = 0; i < ranges.length; i++) {
8994 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8995 }
8996 return stableRanges;
8997 }
8998
Motomu Utsumi93a22182023-03-16 17:04:21 +09008999 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009000 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009001 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9002 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009003 if (mDeps.isAtLeastU()) {
9004 final Set<Integer> exemptUidSet = new ArraySet<>();
9005 for (final int uid: exemptUids) {
9006 exemptUidSet.add(uid);
9007 }
9008 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9009 } else {
9010 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9011 }
Ken Chen5e65a852020-12-24 12:59:10 +08009012 } catch (Exception e) {
9013 loge("Exception in socket destroy: ", e);
9014 }
9015 }
9016 }
9017
paulhuaa0743d2021-05-26 21:56:03 +08009018 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009019 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009020 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9021 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9022 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009023 exemptUids[0] = VPN_UID;
9024 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009025 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9026
Motomu Utsumi6345e462023-03-13 13:24:50 +09009027 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009028 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009029 try {
9030 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009031 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009032 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009033 } else {
paulhu0e79d952021-06-09 16:11:35 +08009034 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009035 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009036 }
9037 } catch (Exception e) {
9038 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9039 " on netId " + nai.network.netId + ". " + e);
9040 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009041 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009042 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009043 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009044
lucaslin53e8a262021-06-08 01:43:59 +08009045 private boolean isProxySetOnAnyDefaultNetwork() {
9046 ensureRunningOnConnectivityServiceThread();
9047 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9048 final NetworkAgentInfo nai = nri.getSatisfier();
9049 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9050 return true;
9051 }
9052 }
9053 return false;
9054 }
9055
9056 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9057 NetworkCapabilities newNc) {
9058 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9059 // the proxy might be changed since the default network satisfied by the apps might also
9060 // changed.
9061 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9062 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009063 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9064 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009065 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009066 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9067 mProxyTracker.sendProxyBroadcast();
9068 }
9069 }
9070
Chalard Jeane6c95272022-01-25 21:04:21 +09009071 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9072 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009073 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9074 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009075 if (null == prevRanges) prevRanges = new ArraySet<>();
9076 if (null == newRanges) newRanges = new ArraySet<>();
9077 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9078
9079 prevRanges.removeAll(newRanges);
9080 newRanges.removeAll(prevRangesCopy);
9081
9082 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009083 // When updating the VPN uid routing rules, add the new range first then remove the old
9084 // range. If old range were removed first, there would be a window between the old
9085 // range being removed and the new range being added, during which UIDs contained
9086 // in both ranges are not subject to any VPN routing rules. Adding new range before
9087 // removing old range works because, unlike the filtering rules below, it's possible to
9088 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009089 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9090 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9091 // [1-5] & [1-2],[4-5] == [3]
9092 // Then we can do:
9093 // maybeCloseSockets([3])
9094 // mNetd.networkAddUidRanges([1-2],[4-5])
9095 // mNetd.networkRemoveUidRanges([1-5])
9096 // maybeCloseSockets([3])
9097 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9098 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009099 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009100 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009101 }
9102 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009103 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009104 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009105 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9106 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009107 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9108 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009109 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009110 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009111 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9112 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9113 // were added first and then newRanges got removed later, there would be only one uid
9114 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9115 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9116 // Note that this is in contrast with the (more robust) update of VPN routing rules
9117 // above, where the addition of new ranges happens before the removal of old ranges.
9118 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9119 // to be removed will never overlap with the new range to be added.
9120 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009121 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9122 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009123 }
9124 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009125 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009126 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009127 } catch (Exception e) {
9128 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009129 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009130 }
9131 }
9132
Chalard Jeande665262022-02-25 16:12:12 +09009133 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009134 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9135 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009136 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9137 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009138 if (prevEmpty && newEmpty) return;
9139
9140 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009141 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009142 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009143 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009144
9145 if (prevUids.equals(newUids)) return;
9146
9147 // This implementation is very simple and vastly faster for sets of Integers than
9148 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9149 // a key computed from the value and has storage for that.
9150 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9151 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9152 toRemove.removeAll(newUids);
9153 toAdd.removeAll(prevUids);
9154
9155 try {
9156 if (!toAdd.isEmpty()) {
9157 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9158 nai.network.netId,
9159 intsToUidRangeStableParcels(toAdd),
9160 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9161 }
9162 if (!toRemove.isEmpty()) {
9163 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9164 nai.network.netId,
9165 intsToUidRangeStableParcels(toRemove),
9166 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9167 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009168 } catch (ServiceSpecificException e) {
9169 // Has the interface disappeared since the network was built ?
9170 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009171 } catch (RemoteException e) {
9172 // Netd died. This usually causes a runtime restart anyway.
9173 }
9174 }
9175
Junyu Lai2ed7d412022-10-07 16:52:21 +08009176 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9177 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009178 ensureRunningOnConnectivityServiceThread();
9179
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009180 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009181 // Ignore updates for disconnected networks
9182 return;
9183 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009184 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009185 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009186 + "; created=" + nai.getCreatedTime()
9187 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009188 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009189 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9190 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009191 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009192 }
9193
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009194 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9195 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009196 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009197 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009198 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009199 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9200 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9201 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009202 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9203 // need to be sent as a separate extra.
9204 final NetworkRequest req = nri.isMultilayerRequest()
9205 ? nri.getActiveRequest()
9206 // Non-multilayer listen requests do not have an active request
9207 : nri.mRequests.get(0);
9208 if (req == null) {
9209 Log.wtf(TAG, "No request in NRI " + nri);
9210 }
9211 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009212 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009213 sendIntent(nri.mPendingIntent, intent);
9214 }
9215 // else not handled
9216 }
9217
Michael Groover73f69482023-01-27 11:01:25 -06009218 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9219 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009220 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9221 mPendingIntentWakeLock.acquire();
9222 try {
9223 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009224 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009225 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009226 // Explicitly disallow the receiver from starting activities, to prevent apps from
9227 // utilizing the PendingIntent as a backdoor to do this.
9228 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9229 }
9230 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9231 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009232 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009233 } catch (PendingIntent.CanceledException e) {
9234 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9235 mPendingIntentWakeLock.release();
9236 releasePendingNetworkRequest(pendingIntent);
9237 }
9238 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9239 }
9240
9241 @Override
9242 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9243 String resultData, Bundle resultExtras) {
9244 if (DBG) log("Finished sending " + pendingIntent);
9245 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009246 // Release with a delay so the receiving client has an opportunity to put in its
9247 // own request.
9248 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009249 }
9250
Chalard Jean46bfbf02022-02-02 00:56:25 +09009251 // networkAgent is only allowed to be null if notificationType is
9252 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9253 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009254 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009255 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009256 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009257 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009258 // Default request has no msgr. Also prevents callbacks from being invoked for
9259 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9260 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9261 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009262 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009263 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009264 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009265 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009266 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009267 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009268 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009269 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9270 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009271 }
Roshan Pius951c0032020-12-22 15:10:42 -08009272 final boolean includeLocationSensitiveInfo =
9273 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009274 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009275 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009276 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009277 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009278 networkCapabilitiesRestrictedForCallerPermissions(
9279 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9280 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009281 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009282 nri.mCallingAttributionTag);
9283 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009284 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9285 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009286 // For this notification, arg1 contains the blocked status.
9287 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009288 break;
9289 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009290 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009291 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009292 break;
9293 }
9294 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009295 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009296 final NetworkCapabilities netCap =
9297 networkCapabilitiesRestrictedForCallerPermissions(
9298 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9299 putParcelable(
9300 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009301 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009302 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009303 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009304 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009305 break;
9306 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009307 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009308 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9309 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009310 break;
9311 }
junyulaif2c67e42018-08-07 19:50:45 +08009312 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009313 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009314 msg.arg1 = arg1;
9315 break;
9316 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009317 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009318 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009319 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009320 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009321 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009322 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009323 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009324 }
James Mattis45d81842021-01-10 14:24:24 -08009325 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009326 } catch (RemoteException e) {
9327 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009328 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009329 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009330 }
9331
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009332 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9333 bundle.putParcelable(t.getClass().getSimpleName(), t);
9334 }
9335
Chalard Jean0702f982021-09-16 21:50:07 +09009336 /**
9337 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9338 *
9339 * When a request should be assigned to a new network, it is normally lingered to give
9340 * time for apps to gracefully migrate their connections. When both networks are on the same
9341 * radio, but that radio can't do time-sharing efficiently, this may end up being
9342 * counter-productive because any traffic on the old network may drastically reduce the
9343 * performance of the new network.
9344 * The stack supports a configuration to let modem vendors state that their radio can't
9345 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9346 * from one cell network to another can't be done gracefully.
9347 *
9348 * @param oldNai the old network serving the request
9349 * @param newNai the new network serving the request
9350 * @return whether the switch can be graceful
9351 */
9352 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9353 @NonNull final NetworkAgentInfo newSatisfier) {
9354 if (mCellularRadioTimesharingCapable) return true;
9355 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9356 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9357 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9358 }
9359
Paul Jensenaf94b982014-09-30 15:37:41 -04009360 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009361 if (nai.numRequestNetworkRequests() != 0) {
9362 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9363 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009364 // Ignore listening and track default requests.
9365 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009366 loge("Dead network still had at least " + nr);
9367 break;
9368 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009369 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009370 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009371 }
9372
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009373 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9374 if (oldNetwork == null) {
9375 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9376 return;
9377 }
Chalard Jean49707572019-12-10 21:07:02 +09009378 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009379
9380 // If we get here it means that the last linger timeout for this network expired. So there
9381 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009382 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009383
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009384 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009385 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009386 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009387 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009388 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009389 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009390 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009391 }
9392
James Mattise3ef1912020-12-20 11:09:58 -08009393 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9394 boolean isDefaultChanged = false;
9395 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9396 final NetworkReassignment.RequestReassignment reassignment =
9397 changes.getReassignment(defaultRequestInfo);
9398 if (null == reassignment) {
9399 continue;
9400 }
9401 // reassignment only contains those instances where the satisfying network changed.
9402 isDefaultChanged = true;
9403 // Notify system services of the new default.
9404 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9405 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009406
James Mattise3ef1912020-12-20 11:09:58 -08009407 if (isDefaultChanged) {
9408 // Hold a wakelock for a short time to help apps in migrating to a new default.
9409 scheduleReleaseNetworkTransitionWakelock();
9410 }
9411 }
9412
Aaron Huang9fe47be2021-06-08 13:11:45 +08009413 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9414 if (null == oldDefaultNetwork) return;
9415 // The network stopped being the default. If it was using a PAC proxy, then the
9416 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9417 // to the local proxy server, which would forward them over the newly default network.
9418 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9419 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9420 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9421 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9422 }
9423
James Mattise3ef1912020-12-20 11:09:58 -08009424 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9425 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9426 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9427 if (DBG) {
9428 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9429 }
Chalard Jean8e382112019-12-03 20:45:30 +09009430
James Mattisd31bdfa2020-12-23 16:37:26 -08009431 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9432 if (newDefaultNetwork != null) {
9433 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009434 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009435
James Mattisd31bdfa2020-12-23 16:37:26 -08009436 // Set an app level managed default and return since further processing only applies to the
9437 // default network.
9438 if (mDefaultRequest != nri) {
9439 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9440 return;
9441 }
9442
9443 makeDefaultNetwork(newDefaultNetwork);
9444
James Mattise3ef1912020-12-20 11:09:58 -08009445 if (oldDefaultNetwork != null) {
9446 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9447 }
9448 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009449 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009450 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009451 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009452 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009453 updateTcpBufferSizes(null != newDefaultNetwork
9454 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009455 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009456 }
9457
James Mattisd31bdfa2020-12-23 16:37:26 -08009458 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9459 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9460 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9461 try {
9462 if (VDBG) {
9463 log("Setting default network for " + nri
9464 + " using UIDs " + nri.getUids()
9465 + " with old network " + (oldDefaultNetwork != null
9466 ? oldDefaultNetwork.network().getNetId() : "null")
9467 + " and new network " + (newDefaultNetwork != null
9468 ? newDefaultNetwork.network().getNetId() : "null"));
9469 }
9470 if (nri.getUids().isEmpty()) {
9471 throw new IllegalStateException("makeDefaultForApps called without specifying"
9472 + " any applications to set as the default." + nri);
9473 }
9474 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009475 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009476 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009477 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009478 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009479 }
9480 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009481 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009482 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009483 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009484 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009485 }
9486 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009487 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009488 }
9489 }
9490
Junyu Lai35665cc2022-12-19 17:37:48 +08009491 /**
9492 * Collect restricted uid ranges for the given network and UserHandle, these uids
9493 * are not restricted for matched enterprise networks but being restricted for non-matched
9494 * enterprise networks and non-enterprise networks.
9495 */
9496 @NonNull
9497 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9498 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9499 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9500 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9501 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9502
9503 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9504 // The NC is built from a `ProfileNetworkPreference` which has only one
9505 // enterprise ID, so it's guaranteed to have exactly one.
9506 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9507 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9508 continue;
9509 }
9510 }
9511
9512 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9513 pref.capabilities.getUidRanges())) {
9514 throw new IllegalArgumentException(
9515 "Overlapping uid range in preference: " + pref);
9516 }
9517 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9518 }
9519 return restrictedUidRanges;
9520 }
9521
9522 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009523 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009524 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009525
Junyu Lai35665cc2022-12-19 17:37:48 +08009526 ensureRunningOnConnectivityServiceThread();
9527 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9528 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9529 .getUserHandles(true /* excludeDying */);
9530 if (users.isEmpty()) {
9531 throw new IllegalStateException("No user is available");
9532 }
9533
9534 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9535 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9536 for (final UserHandle user : users) {
9537 final ArraySet<UidRange> restrictedUidRanges =
9538 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9539 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9540 UidRange.createForUser(user), restrictedUidRanges));
9541 }
9542
9543 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9544 configs.add(new NativeUidRangeConfig(
9545 nai.network.netId, rangesParcel, 0 /* subPriority */));
9546 }
9547
9548 // The netd API replaces the previous configs with the current configs.
9549 // Thus, for network disconnection or preference removal, no need to
9550 // unset previous config. Instead, collecting all currently needed
9551 // configs and issue to netd.
9552 try {
9553 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9554 } catch (ServiceSpecificException e) {
9555 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009556 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009557 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009558 // Netd died. This will cause a runtime restart anyway.
9559 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009560 }
9561 }
9562
James Mattisd31bdfa2020-12-23 16:37:26 -08009563 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9564 try {
9565 if (null != newDefaultNetwork) {
9566 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9567 } else {
9568 mNetd.networkClearDefault();
9569 }
9570 } catch (RemoteException | ServiceSpecificException e) {
9571 loge("Exception setting default network :" + e);
9572 }
9573 }
9574
Chalard Jean05cbe972019-12-09 11:50:38 +09009575 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009576 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009577 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009578 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009579 processNewlySatisfiedListenRequests(nai);
9580 }
9581
9582 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009583 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9584 if (nri.isMultilayerRequest()) {
9585 continue;
9586 }
9587 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009588 if (!nr.isListen()) continue;
9589 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009590 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009591 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9592 }
9593 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009594 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009595
Chalard Jeancd397a22019-11-22 22:33:33 +09009596 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009597 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9598 if (nri.isMultilayerRequest()) {
9599 continue;
9600 }
9601 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009602 if (!nr.isListen()) continue;
9603 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9604 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009605 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009606 }
9607 }
9608 }
9609
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009610 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009611 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009612 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009613 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009614 @Nullable public final NetworkRequest mOldNetworkRequest;
9615 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009616 @Nullable public final NetworkAgentInfo mOldNetwork;
9617 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009618 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009619 @Nullable final NetworkRequest oldNetworkRequest,
9620 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009621 @Nullable final NetworkAgentInfo oldNetwork,
9622 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009623 mNetworkRequestInfo = networkRequestInfo;
9624 mOldNetworkRequest = oldNetworkRequest;
9625 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009626 mOldNetwork = oldNetwork;
9627 mNewNetwork = newNetwork;
9628 }
Chalard Jean49707572019-12-10 21:07:02 +09009629
9630 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009631 final NetworkRequest requestToShow = null != mNewNetworkRequest
9632 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9633 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009634 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9635 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009636 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009637 }
9638
Chalard Jean46a62372019-12-10 21:25:24 +09009639 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009640
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009641 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009642 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009643 }
9644
9645 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009646 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009647 // The code is never supposed to add two reassignments of the same request. Make
9648 // sure this stays true, but without imposing this expensive check on all
9649 // reassignments on all user devices.
9650 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009651 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009652 throw new IllegalStateException("Trying to reassign ["
9653 + reassignment + "] but already have ["
9654 + existing + "]");
9655 }
9656 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009657 }
Chalard Jean46a62372019-12-10 21:25:24 +09009658 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009659 }
9660
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009661 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009662 // the passed request.
9663 @Nullable
9664 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009665 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009666 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009667 }
9668 return null;
9669 }
Chalard Jean49707572019-12-10 21:07:02 +09009670
9671 public String toString() {
9672 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9673 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009674 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009675 for (final RequestReassignment rr : getRequestReassignments()) {
9676 sj.add(rr.toString());
9677 }
9678 return sj.toString();
9679 }
9680
9681 public String debugString() {
9682 final StringBuilder sb = new StringBuilder();
9683 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009684 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009685 for (final RequestReassignment rr : getRequestReassignments()) {
9686 sb.append("\n ").append(rr);
9687 }
9688 return sb.append("\n").toString();
9689 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009690 }
9691
Chalard Jean24344d72019-12-04 13:32:31 +09009692 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009693 @Nullable final NetworkRequest previousRequest,
9694 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009695 @Nullable final NetworkAgentInfo previousSatisfier,
9696 @Nullable final NetworkAgentInfo newSatisfier,
9697 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009698 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009699 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009700 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009701 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009702 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009703 }
James Mattisa076c532020-12-02 14:12:41 -08009704 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009705 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009706 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009707 // If this network switch can't be supported gracefully, the request is not
9708 // lingered. This allows letting go of the network sooner to reclaim some
9709 // performance on the new network, since the radio can't do both at the same
9710 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009711 //
9712 // Also don't linger the request if the old network has been destroyed.
9713 // A destroyed network does not provide actual network connectivity, so
9714 // lingering it is not useful. In particular this ensures that a destroyed
9715 // network is outscored by its replacement,
9716 // then it is torn down immediately instead of being lingered, and any apps that
9717 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009718 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9719 }
Chalard Jean24344d72019-12-04 13:32:31 +09009720 } else {
9721 if (VDBG || DDBG) log(" accepting network in place of null");
9722 }
junyulai0ac374f2020-12-14 18:41:52 +08009723
9724 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9725 // and immediately satisfies a request then remove the timer. This will happen for
9726 // all networks except in the case of an underlying network for a VCN.
9727 if (newSatisfier.isNascent()) {
9728 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009729 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009730 }
9731
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009732 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009733 newSatisfier.unlingerRequest(newRequest.requestId);
9734 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009735 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009736 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009737 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009738 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009739 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009740 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009741 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009742 }
James Mattisa076c532020-12-02 14:12:41 -08009743 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009744 }
James Mattisa076c532020-12-02 14:12:41 -08009745 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009746 }
9747
James Mattisa076c532020-12-02 14:12:41 -08009748 /**
9749 * This function is triggered when something can affect what network should satisfy what
9750 * request, and it computes the network reassignment from the passed collection of requests to
9751 * network match to the one that the system should now have. That data is encoded in an
9752 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9753 * satisfier.
9754 *
9755 * After the reassignment is computed, it is applied to the state objects.
9756 *
9757 * @param networkRequests the nri objects to evaluate for possible network reassignment
9758 * @return NetworkReassignment listing of proposed network assignment changes
9759 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009760 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009761 private NetworkReassignment computeNetworkReassignment(
9762 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009763 final NetworkReassignment changes = new NetworkReassignment();
9764
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009765 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009766 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009767 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009768 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009769 }
Chalard Jean857a1712019-12-10 21:08:07 +09009770
James Mattisa076c532020-12-02 14:12:41 -08009771 for (final NetworkRequestInfo nri : networkRequests) {
9772 // Non-multilayer listen requests can be ignored.
9773 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9774 continue;
9775 }
9776 NetworkAgentInfo bestNetwork = null;
9777 NetworkRequest bestRequest = null;
9778 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009779 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009780 // Stop evaluating as the highest possible priority request is satisfied.
9781 if (null != bestNetwork) {
9782 bestRequest = req;
9783 break;
9784 }
9785 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009786 if (null == bestNetwork && isDefaultBlocked(nri)) {
9787 // Remove default networking if disallowed for managed default requests.
9788 bestNetwork = mNoServiceNetwork;
9789 }
9790 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009791 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009792 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009793 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009794 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009795 }
9796 return changes;
9797 }
9798
James Mattisa076c532020-12-02 14:12:41 -08009799 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9800 return new HashSet<>(mNetworkRequests.values());
9801 }
9802
Paul Jensenc88b39b2015-06-16 14:27:36 -04009803 /**
James Mattisa076c532020-12-02 14:12:41 -08009804 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009805 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009806 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009807 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009808 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9809 }
9810
9811 /**
9812 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9813 * being disconnected.
9814 */
9815 private void rematchNetworksAndRequests(
9816 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9817 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009818 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009819 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009820 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009821 final long computed = SystemClock.elapsedRealtime();
9822 applyNetworkReassignment(changes, start);
9823 final long applied = SystemClock.elapsedRealtime();
9824 issueNetworkNeeds();
9825 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009826 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009827 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9828 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009829 log(changes.debugString());
9830 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009831 // Shorter form, only one line of log
9832 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9833 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009834 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009835 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009836
Chalard Jeand7f762d2019-12-10 19:01:29 +09009837 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009838 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009839 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009840
9841 // Since most of the time there are only 0 or 1 background networks, it would probably
9842 // be more efficient to just use an ArrayList here. TODO : measure performance
9843 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9844 for (final NetworkAgentInfo nai : nais) {
9845 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9846 }
9847
Chalard Jeand7f762d2019-12-10 19:01:29 +09009848 // First, update the lists of satisfied requests in the network agents. This is necessary
9849 // because some code later depends on this state to be correct, most prominently computing
9850 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009851 for (final NetworkReassignment.RequestReassignment event :
9852 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009853 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9854 event.mOldNetworkRequest, event.mNewNetworkRequest,
9855 event.mOldNetwork, event.mNewNetwork,
9856 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009857 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009858
James Mattise3ef1912020-12-20 11:09:58 -08009859 // Process default network changes if applicable.
9860 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009861
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009862 // Notify requested networks are available after the default net is switched, but
9863 // before LegacyTypeTracker sends legacy broadcasts
9864 for (final NetworkReassignment.RequestReassignment event :
9865 changes.getRequestReassignments()) {
9866 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009867 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009868 } else {
James Mattisa076c532020-12-02 14:12:41 -08009869 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009870 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009871 }
9872 }
9873
junyulai0ac374f2020-12-14 18:41:52 +08009874 // Update the inactivity state before processing listen callbacks, because the background
9875 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009876 // just yet though, because they have to be sent after the listens are processed to keep
9877 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009878 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009879 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009880 // Rematching may have altered the inactivity state of some networks, so update all
9881 // inactivity timers. updateInactivityState reads the state from the network agent
9882 // and does nothing if the state has not changed : the source of truth is controlled
9883 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9884 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009885 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009886 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009887 }
9888 }
9889
Chalard Jeanb10ab412019-12-11 14:12:30 +09009890 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009891 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009892 // Process listen requests and update capabilities if the background state has
9893 // changed for this network. For consistency with previous behavior, send onLost
9894 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009895 processNewlyLostListenRequests(nai);
9896 if (oldBackground != nai.isBackgroundNetwork()) {
9897 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009898 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009899 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009900 }
9901
junyulai0ac374f2020-12-14 18:41:52 +08009902 for (final NetworkAgentInfo nai : inactiveNetworks) {
9903 // For nascent networks, if connecting with no foreground request, skip broadcasting
9904 // LOSING for backward compatibility. This is typical when mobile data connected while
9905 // wifi connected with mobile data always-on enabled.
9906 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009907 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009908 }
9909
James Mattise3ef1912020-12-20 11:09:58 -08009910 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009911
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009912 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +00009913 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009914 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009915 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009916 // This network has active linger timers and no requests, but is not
9917 // lingering. Linger it.
9918 //
9919 // One way (the only way?) this can happen if this network is unvalidated
9920 // and became unneeded due to another network improving its score to the
9921 // point where this network will no longer be able to satisfy any requests
9922 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009923 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009924 notifyNetworkLosing(nai, now);
9925 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009926 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009927 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009928 teardownUnneededNetwork(nai);
9929 }
9930 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009931 }
9932 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009933
Chalard Jean62edfd82019-12-02 18:39:29 +09009934 /**
9935 * Apply a change in background state resulting from rematching networks with requests.
9936 *
9937 * During rematch, a network may change background states by starting to satisfy or stopping
9938 * to satisfy a foreground request. Listens don't count for this. When a network changes
9939 * background states, its capabilities need to be updated and callbacks fired for the
9940 * capability change.
9941 *
9942 * @param nai The network that changed background states
9943 */
9944 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9945 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9946 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9947 updateNetworkPermissions(nai, newNc);
9948 nai.getAndSetNetworkCapabilities(newNc);
9949 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9950 }
9951
Chalard Jeanf0344532019-11-19 19:23:38 +09009952 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009953 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009954 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009955 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9956 changes.getReassignment(mDefaultRequest);
9957 final NetworkAgentInfo oldDefaultNetwork =
9958 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9959 final NetworkAgentInfo newDefaultNetwork =
9960 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009961
Chalard Jean5b409c72021-02-04 13:12:59 +09009962 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009963 // Maintain the illusion : since the legacy API only understands one network at a time,
9964 // if the default network changed, apps should see a disconnected broadcast for the
9965 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009966 if (oldDefaultNetwork != null) {
9967 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9968 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009969 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009970 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009971 // The new default network can be newly null if and only if the old default
9972 // network doesn't satisfy the default request any more because it lost a
9973 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009974 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009975 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009976 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009977 }
9978 }
9979
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009980 // Now that all the callbacks have been sent, send the legacy network broadcasts
9981 // as needed. This is necessary so that legacy requests correctly bind dns
9982 // requests to this network. The legacy users are listening for this broadcast
9983 // and will generally do a dns request so they can ensureRouteToHost and if
9984 // they do that before the callbacks happen they'll use the default network.
9985 //
9986 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9987 // callbacks, but if apps can receive the broadcast before the callback, they still might
9988 // have an inconsistent view of networking.
9989 //
9990 // This *does* introduce a race where if the user uses the new api
9991 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9992 // they may get old info. Reverse this after the old startUsing api is removed.
9993 // This is on top of the multiple intent sequencing referenced in the todo above.
9994 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009995 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009996 addNetworkToLegacyTypeTracker(nai);
9997 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009998 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009999 }
10000
Chalard Jean0354d8c2021-01-12 10:58:56 +090010001 private void issueNetworkNeeds() {
10002 ensureRunningOnConnectivityServiceThread();
10003 for (final NetworkOfferInfo noi : mNetworkOffers) {
10004 issueNetworkNeeds(noi);
10005 }
10006 }
10007
10008 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10009 ensureRunningOnConnectivityServiceThread();
10010 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10011 informOffer(nri, noi.offer, mNetworkRanker);
10012 }
10013 }
10014
10015 /**
10016 * Inform a NetworkOffer about any new situation of a request.
10017 *
10018 * This function handles updates to offers. A number of events may happen that require
10019 * updating the registrant for this offer about the situation :
10020 * • The offer itself was updated. This may lead the offer to no longer being able
10021 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10022 * or conversely being strengthened enough to beat the satisfier (and therefore
10023 * start being needed)
10024 * • The network satisfying a request changed (including cases where the request
10025 * starts or stops being satisfied). The new network may be a stronger or weaker
10026 * match than the old one, possibly affecting whether the offer is needed.
10027 * • The network satisfying a request updated their score. This may lead the offer
10028 * to no longer be able to beat it if the current satisfier got better, or
10029 * conversely start being a good choice if the current satisfier got weaker.
10030 *
10031 * @param nri The request
10032 * @param offer The offer. This may be an updated offer.
10033 */
10034 private static void informOffer(@NonNull NetworkRequestInfo nri,
10035 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10036 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10037 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010038
10039 // Multi-layer requests have a currently active request, the one being satisfied.
10040 // Since the system will try to bring up a better network than is currently satisfying
10041 // the request, NetworkProviders need to be told the offers matching the requests *above*
10042 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10043 // not needed, and the offer is needed for the active request iff the offer can beat
10044 // the satisfier.
10045 // For non-multilayer requests, the logic above gracefully degenerates to only the
10046 // last case.
10047 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10048 // providers that the offer is needed for this request, until the active request is found.
10049 // In a second phase, deal with the currently active request. In a third phase, inform
10050 // the providers that offer is unneeded for the remaining requests.
10051
10052 // First phase : inform providers of all requests above the active request.
10053 int i;
10054 for (i = 0; nri.mRequests.size() > i; ++i) {
10055 final NetworkRequest request = nri.mRequests.get(i);
10056 if (activeRequest == request) break; // Found the active request : go to phase 2
10057 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10058 // Since this request is higher-priority than the one currently satisfied, if the
10059 // offer can satisfy it, the provider should try and bring up the network for sure ;
10060 // no need to even ask the ranker – an offer that can satisfy is always better than
10061 // no network. Hence tell the provider so unless it already knew.
10062 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10063 offer.onNetworkNeeded(request);
10064 }
10065 }
10066
10067 // Second phase : deal with the active request (if any)
10068 if (null != activeRequest && activeRequest.isRequest()) {
10069 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010070 // If an offer can satisfy the request, it is considered needed if it is currently
10071 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010072 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010073 && satisfier.factorySerialNumber == offer.providerId
10074 && activeRequest.canBeSatisfiedBy(offer.caps);
10075 final boolean newNeeded = currentlyServing
10076 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010077 if (newNeeded != oldNeeded) {
10078 if (newNeeded) {
10079 offer.onNetworkNeeded(activeRequest);
10080 } else {
10081 // The offer used to be able to beat the satisfier. Now it can't.
10082 offer.onNetworkUnneeded(activeRequest);
10083 }
10084 }
10085 }
10086
10087 // Third phase : inform the providers that the offer isn't needed for any request
10088 // below the active one.
10089 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10090 final NetworkRequest request = nri.mRequests.get(i);
10091 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10092 // Since this request is lower-priority than the one currently satisfied, if the
10093 // offer can satisfy it, the provider should not try and bring up the network.
10094 // Hence tell the provider so unless it already knew.
10095 if (offer.neededFor(request)) {
10096 offer.onNetworkUnneeded(request);
10097 }
10098 }
10099 }
10100
Chalard Jean61c79252019-11-07 23:07:32 +090010101 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10102 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10103 NetworkRequest nr = nai.requestAt(i);
10104 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10105 // legacy type tracker filters out repeat adds
10106 mLegacyTypeTracker.add(nr.legacyType, nai);
10107 }
10108 }
10109
10110 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010111 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010112 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10113 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10114 if (nai.isVPN()) {
10115 mLegacyTypeTracker.add(TYPE_VPN, nai);
10116 }
10117 }
10118
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010119 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010120 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010121 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010122 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010123 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010124 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010125
Chalard Jean254bd162022-08-25 13:04:51 +090010126 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010127 // Don't repeat publish.
10128 if (newInetCondition == mDefaultInetConditionPublished) return;
10129
10130 mDefaultInetConditionPublished = newInetCondition;
10131 sendInetConditionBroadcast(nai.networkInfo);
10132 }
10133
Chalard Jeand61375d2020-01-14 22:46:36 +090010134 @NonNull
10135 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10136 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010137 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010138 final boolean suspended =
10139 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10140 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10141 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10142 // state. This is because the network could have been suspended before connecting,
10143 // or it could be disconnecting while being suspended, and in both these cases
10144 // the state should not be overridden. Note that the only detailed state that
10145 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10146 // worry about multiple different substates of CONNECTED.
10147 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10148 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010149 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10150 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10151 // network agent is created, then goes to suspended, then goes out of suspended without
10152 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010153 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010154 ? NetworkInfo.DetailedState.CONNECTED
10155 : NetworkInfo.DetailedState.CONNECTING,
10156 info.getReason(),
10157 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010158 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010159 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010160 return newInfo;
10161 }
10162
10163 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10164 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10165
Erik Kline99f301b2017-02-15 19:59:17 +090010166 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010167 NetworkInfo oldInfo = null;
10168 synchronized (networkAgent) {
10169 oldInfo = networkAgent.networkInfo;
10170 networkAgent.networkInfo = newInfo;
10171 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010172
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010173 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010174 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10175 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010176 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010177
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010178 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010179 // A network that has just connected has zero requests and is thus a foreground network.
10180 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10181
Luke Huangfdd11f82019-04-09 18:41:49 +080010182 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010183
10184 networkAgent.setCreated();
10185
10186 // If the network is created immediately on register, then apply the LinkProperties now.
10187 // Otherwise, this is done further down when the network goes into connected state.
10188 // Applying the LinkProperties means that the network is ready to carry traffic -
10189 // interfaces and routing rules have been added, DNS servers programmed, etc.
10190 // For VPNs, this must be done before the capabilities are updated, because as soon as
10191 // that happens, UIDs are routed to the network.
10192 if (shouldCreateNetworksImmediately()) {
10193 applyInitialLinkProperties(networkAgent);
10194 }
10195
10196 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10197 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010198 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010199 // Initialize the network's capabilities to their starting values according to the
10200 // underlying networks. This ensures that the capabilities are correct before
10201 // anything happens to the network.
10202 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010203 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010204 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010205 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010206 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010207 }
10208
Chalard Jean254bd162022-08-25 13:04:51 +090010209 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10210 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010211
lucaslin45e639b2019-04-03 17:09:28 +080010212 // NetworkCapabilities need to be set before sending the private DNS config to
10213 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010214 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10215
Erik Kline9a62f012018-03-21 07:18:33 -070010216 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010217 if (!shouldCreateNetworksImmediately()) {
10218 applyInitialLinkProperties(networkAgent);
10219 } else {
10220 // The network was created when the agent registered, and the LinkProperties are
10221 // already up-to-date. However, updateLinkProperties also makes some changes only
10222 // when the network connects. Apply those changes here. On T and below these are
10223 // handled by the applyInitialLinkProperties call just above.
10224 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10225 // If something depends on both LinkProperties and connected state, it should be in
10226 // this method as well.
10227 networkAgent.clatd.update();
10228 updateProxy(networkAgent.linkProperties, null);
10229 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010230
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010231 // If a rate limit has been configured and is applicable to this network (network
10232 // provides internet connectivity), apply it. The tc police filter cannot be attached
10233 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010234 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010235 // Note: in case of a system server crash, the NetworkController constructor in netd
10236 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10237 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10238 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10239 mIngressRateLimit);
10240 }
10241
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010242 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10243 // command must be sent after updating LinkProperties to maximize chances of
10244 // NetworkMonitor seeing the correct LinkProperties when starting.
10245 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010246 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010247 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010248 }
Chalard Jeand4900722022-02-06 12:25:38 +090010249 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10250 params.networkAgentConfig = networkAgent.networkAgentConfig;
10251 params.networkCapabilities = networkAgent.networkCapabilities;
10252 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10253 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010254 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10255 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10256 // call that would cause a Log.wtf to be emitted from the system_server process, and
10257 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10258 // process to check the interface version, just use an SDK check. NetworkStack will
10259 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010260 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010261 networkAgent.networkMonitor().notifyNetworkConnected(params);
10262 } else {
10263 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10264 params.networkCapabilities);
10265 }
Chalard Jean0f141332023-06-05 19:26:17 +090010266 final long evaluationDelay;
10267 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10268 // If the network is anything other than pure wifi, use the default timeout.
10269 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10270 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10271 // If the network is explicitly selected, use the default timeout because it's
10272 // shorter and the user is likely staring at the screen expecting it to validate
10273 // right away.
10274 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10275 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10276 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10277 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10278 } else {
10279 // It's wifi, automatically connected, and bad wifi is preferred : use the
10280 // longer timeout to avoid the device switching to captive portals with bad
10281 // signal or very slow response.
10282 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10283 }
10284 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010285
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010286 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10287 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10288 // capabilities, so it only needs to be done once on initial connect, not every time the
10289 // network's capabilities change. Note that we do this before rematching the network,
10290 // so we could decide to tear it down immediately afterwards. That's fine though - on
10291 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10292 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010293 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010294
junyulai0ac374f2020-12-14 18:41:52 +080010295 // Before first rematching networks, put an inactivity timer without any request, this
10296 // allows {@code updateInactivityState} to update the state accordingly and prevent
10297 // tearing down for any {@code unneeded} evaluation in this period.
10298 // Note that the timer will not be rescheduled since the expiry time is
10299 // fixed after connection regardless of the network satisfying other requests or not.
10300 // But it will be removed as soon as the network satisfies a request for the first time.
10301 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10302 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010303 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010304
Paul Jensen05e85ee2014-09-11 11:00:39 -040010305 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010306 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010307
10308 // This has to happen after matching the requests, because callbacks are just requests.
10309 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010310 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010311 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010312 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010313 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010314 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010315 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010316 if (networkAgent.isVPN()) {
10317 // As the active or bound network changes for apps, broadcast the default proxy, as
10318 // apps may need to update their proxy data. This is called after disconnecting from
10319 // VPN to make sure we do not broadcast the old proxy data.
10320 // TODO(b/122649188): send the broadcast only to VPN users.
10321 mProxyTracker.sendProxyBroadcast();
10322 }
Chalard Jean254bd162022-08-25 13:04:51 +090010323 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10324 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010325 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010326 }
10327 }
10328
Chalard Jean28018572020-12-21 18:36:52 +090010329 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010330 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10331 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010332 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010333 }
10334
Erik Kline99f301b2017-02-15 19:59:17 +090010335 // Notify only this one new request of the current state. Transfer all the
10336 // current state by calling NetworkCapabilities and LinkProperties callbacks
10337 // so that callers can be guaranteed to have as close to atomicity in state
10338 // transfer as can be supported by this current API.
10339 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010340 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010341 if (nri.mPendingIntent != null) {
10342 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10343 // Attempt no subsequent state pushes where intents are involved.
10344 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010345 }
Erik Kline99f301b2017-02-15 19:59:17 +090010346
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010347 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010348 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010349 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10350 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10351 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010352 }
10353
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010354 // Notify the requests on this NAI that the network is now lingered.
10355 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010356 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010357 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10358 }
10359
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010360 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10361 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10362 return vpnBlocked
10363 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10364 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10365 }
10366
10367 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10368 if (blockedReasons == BLOCKED_REASON_NONE) {
10369 mUidBlockedReasons.delete(uid);
10370 } else {
10371 mUidBlockedReasons.put(uid, blockedReasons);
10372 }
10373 }
10374
junyulaif2c67e42018-08-07 19:50:45 +080010375 /**
10376 * Notify of the blocked state apps with a registered callback matching a given NAI.
10377 *
10378 * Unlike other callbacks, blocked status is different between each individual uid. So for
10379 * any given nai, all requests need to be considered according to the uid who filed it.
10380 *
10381 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010382 * @param oldMetered True if the previous network capabilities were metered.
10383 * @param newMetered True if the current network capabilities are metered.
10384 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10385 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010386 */
10387 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010388 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10389 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010390
10391 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10392 NetworkRequest nr = nai.requestAt(i);
10393 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010394
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010395 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10396 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10397 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010398 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010399 : oldVpnBlocked;
10400
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010401 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10402 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10403 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010404 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010405 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010406 }
10407 }
10408 }
10409
10410 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010411 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010412 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010413 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010414 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010415 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010416 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010417 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010418 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010419
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010420 final int oldBlockedState = getBlockedState(
10421 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10422 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10423 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010424 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010425 }
junyulaif2c67e42018-08-07 19:50:45 +080010426 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10427 NetworkRequest nr = nai.requestAt(i);
10428 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010429 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010430 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10431 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010432 }
10433 }
10434 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010435 }
10436
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010437 @VisibleForTesting
10438 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010439 // The NetworkInfo we actually send out has no bearing on the real
10440 // state of affairs. For example, if the default connection is mobile,
10441 // and a request for HIPRI has just gone away, we need to pretend that
10442 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10443 // the state to DISCONNECTED, even though the network is of type MOBILE
10444 // and is still connected.
10445 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10446 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010447 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010448 if (state != DetailedState.DISCONNECTED) {
10449 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010450 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010451 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010452 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010453 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10454 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10455 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10456 if (info.isFailover()) {
10457 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10458 nai.networkInfo.setFailover(false);
10459 }
10460 if (info.getReason() != null) {
10461 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10462 }
10463 if (info.getExtraInfo() != null) {
10464 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10465 }
10466 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010467 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010468 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010469 if (newDefaultAgent != null) {
10470 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10471 newDefaultAgent.networkInfo);
10472 } else {
10473 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10474 }
10475 }
10476 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10477 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010478 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010479 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010480 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010481 }
10482 }
10483 }
10484
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010485 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010486 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010487 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010488 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010489 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010490 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10491 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010492 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10493 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010494 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010495 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010496 } else {
10497 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10498 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010499 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010500 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010501
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010502 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10503 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10504 }
10505
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010506 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010507 * Returns the list of all interfaces that could be used by network traffic that does not
10508 * explicitly specify a network. This includes the default network, but also all VPNs that are
10509 * currently connected.
10510 *
10511 * Must be called on the handler thread.
10512 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010513 @NonNull
10514 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010515 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010516 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010517 final Set<Integer> activeNetIds = new ArraySet<>();
10518 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10519 if (nri.isBeingSatisfied()) {
10520 activeNetIds.add(nri.getSatisfier().network().netId);
10521 }
10522 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010523 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010524 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010525 defaultNetworks.add(nai.network);
10526 }
10527 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010528 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010529 }
10530
10531 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010532 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10533 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010534 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010535 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010536 ensureRunningOnConnectivityServiceThread();
10537 String activeIface = null;
10538 LinkProperties activeLinkProperties = getActiveLinkProperties();
10539 if (activeLinkProperties != null) {
10540 activeIface = activeLinkProperties.getInterfaceName();
10541 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010542
junyulai2050bed2021-01-23 09:46:34 +080010543 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010544 try {
junyulaide41fc22021-01-22 22:46:01 +080010545 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010546 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010547 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10548 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010549 } catch (Exception ignored) {
10550 }
10551 }
10552
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010553 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010554 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010555 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010556 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010557 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010558
10559 if (!TextUtils.isEmpty(settingUrl)) {
10560 return settingUrl;
10561 }
10562
10563 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010564 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010565 if (!TextUtils.isEmpty(settingUrl)) {
10566 return settingUrl;
10567 }
10568
10569 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010570 }
10571
10572 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010573 public void startNattKeepalive(Network network, int intervalSeconds,
10574 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010575 enforceKeepalivePermission();
10576 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010577 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010578 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10579 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010580 // false and set the underpinned network to null because there is no way and no
10581 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10582 // deprecated method.
10583 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010584 }
10585
10586 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010587 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010588 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010589 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010590 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010591 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010592 mKeepaliveTracker.startNattKeepalive(
10593 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010594 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10595 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010596 } finally {
10597 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10598 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010599 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10600 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010601 }
10602 }
junyulaid05a1922019-01-15 11:32:44 +080010603 }
10604
10605 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010606 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010607 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010608 try {
10609 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010610 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010611 mKeepaliveTracker.startTcpKeepalive(
10612 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10613 } finally {
10614 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10615 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010616 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10617 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010618 }
10619 }
junyulai0835a1e2019-01-08 20:04:33 +080010620 }
10621
10622 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010623 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010624 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010625 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10626 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010627 }
10628
10629 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010630 public int[] getSupportedKeepalives() {
10631 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10632 // Backwards compatibility with CTS 13
10633 android.Manifest.permission.QUERY_ALL_PACKAGES);
10634
10635 return BinderUtils.withCleanCallingIdentity(() ->
10636 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10637 }
10638
10639 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010640 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010641 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010642
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010643 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010644 final long token = Binder.clearCallingIdentity();
10645 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010646 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10647 UserHandle.getUserHandleForUid(uid))) {
10648 return;
10649 }
10650
Heemin Seogdb8489d2019-06-12 09:21:44 -070010651 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10652 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010653
10654 // Turn airplane mode off
10655 setAirplaneMode(false);
10656
10657 // restore private DNS settings to default mode (opportunistic)
10658 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10659 UserHandle.getUserHandleForUid(uid))) {
10660 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10661 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10662 }
10663
10664 Settings.Global.putString(mContext.getContentResolver(),
10665 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010666 } finally {
10667 Binder.restoreCallingIdentity(token);
10668 }
Stuart Scottd5463642015-04-02 18:00:02 -070010669 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010670
Ricky Wai7097cc92018-01-23 04:09:45 +000010671 @Override
10672 public byte[] getNetworkWatchlistConfigHash() {
10673 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10674 if (nwm == null) {
10675 loge("Unable to get NetworkWatchlistManager");
10676 return null;
10677 }
10678 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10679 return nwm.getWatchlistConfigHash();
10680 }
10681
Hugo Benichibe0c7652016-05-31 16:28:06 +090010682 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010683 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010684 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010685 }
Hugo Benichif4210292017-04-21 15:07:12 +090010686
10687 private static boolean toBool(int encodedBoolean) {
10688 return encodedBoolean != 0; // Only 0 means false.
10689 }
10690
10691 private static int encodeBool(boolean b) {
10692 return b ? 1 : 0;
10693 }
mswest4632928412018-03-12 10:34:34 -070010694
10695 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010696 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10697 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10698 @NonNull String[] args) {
10699 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10700 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010701 }
10702
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010703 private Boolean parseBooleanArgument(final String arg) {
10704 if ("true".equals(arg)) {
10705 return true;
10706 } else if ("false".equals(arg)) {
10707 return false;
10708 } else {
10709 return null;
10710 }
10711 }
10712
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010713 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010714 @Override
10715 public int onCommand(String cmd) {
10716 if (cmd == null) {
10717 return handleDefaultCommands(cmd);
10718 }
10719 final PrintWriter pw = getOutPrintWriter();
10720 try {
10721 switch (cmd) {
10722 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010723 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10724 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010725 final String action = getNextArg();
10726 if ("enable".equals(action)) {
10727 setAirplaneMode(true);
10728 return 0;
10729 } else if ("disable".equals(action)) {
10730 setAirplaneMode(false);
10731 return 0;
10732 } else if (action == null) {
10733 final ContentResolver cr = mContext.getContentResolver();
10734 final int enabled = Settings.Global.getInt(cr,
10735 Settings.Global.AIRPLANE_MODE_ON);
10736 pw.println(enabled == 0 ? "disabled" : "enabled");
10737 return 0;
10738 } else {
10739 onHelp();
10740 return -1;
10741 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010742 case "set-chain3-enabled": {
10743 final Boolean enabled = parseBooleanArgument(getNextArg());
10744 if (null == enabled) {
10745 onHelp();
10746 return -1;
10747 }
10748 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
10749 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10750 enabled);
10751 return 0;
10752 }
10753 case "get-chain3-enabled": {
10754 final boolean chainEnabled = getFirewallChainEnabled(
10755 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
10756 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
10757 return 0;
10758 }
10759 case "set-package-networking-enabled": {
10760 final Boolean enabled = parseBooleanArgument(getNextArg());
10761 final String packageName = getNextArg();
10762 if (null == enabled || null == packageName) {
10763 onHelp();
10764 return -1;
10765 }
10766 // Throws NameNotFound if the package doesn't exist.
10767 final int appId = setPackageFirewallRule(
10768 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
10769 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
10770 final String msg = (enabled ? "Enabled" : "Disabled")
10771 + " networking for " + packageName + ", appId " + appId;
10772 Log.i(TAG, msg);
10773 pw.println(msg);
10774 return 0;
10775 }
10776 case "get-package-networking-enabled": {
10777 final String packageName = getNextArg();
10778 final int rule = getPackageFirewallRule(
10779 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
10780 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
10781 pw.println(packageName + ":" + "allow");
10782 } else if (FIREWALL_RULE_DENY == rule) {
10783 pw.println(packageName + ":" + "deny");
10784 } else {
10785 throw new IllegalStateException("Unknown rule " + rule + " for package "
10786 + packageName);
10787 }
10788 return 0;
10789 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010790 case "reevaluate":
10791 // Usage : adb shell cmd connectivity reevaluate <netId>
10792 // If netId is omitted, then reevaluate the default network
10793 final String netId = getNextArg();
10794 final NetworkAgentInfo nai;
10795 if (null == netId) {
10796 // Note that the command is running on the wrong thread to call this,
10797 // so this could in principle return stale data. But it can't crash.
10798 nai = getDefaultNetwork();
10799 } else {
10800 // If netId can't be parsed, this throws NumberFormatException, which
10801 // is passed back to adb who prints it.
10802 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10803 }
10804 if (null == nai) {
10805 pw.println("Unknown network (net ID not found or no default network)");
10806 return 0;
10807 }
10808 Log.d(TAG, "Reevaluating network " + nai.network);
10809 reportNetworkConnectivity(nai.network, !nai.isValidated());
10810 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080010811 case "bpf-get-cgroup-program-id": {
10812 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
10813 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
10814 // for more detail.
10815 // If type can't be parsed, this throws NumberFormatException, which
10816 // is passed back to adb who prints it.
10817 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000010818 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080010819 pw.println(ret);
10820 return 0;
10821 }
mswest4632928412018-03-12 10:34:34 -070010822 default:
10823 return handleDefaultCommands(cmd);
10824 }
10825 } catch (Exception e) {
10826 pw.println(e);
10827 }
10828 return -1;
10829 }
10830
10831 @Override
10832 public void onHelp() {
10833 PrintWriter pw = getOutPrintWriter();
10834 pw.println("Connectivity service commands:");
10835 pw.println(" help");
10836 pw.println(" Print this help text.");
10837 pw.println(" airplane-mode [enable|disable]");
10838 pw.println(" Turn airplane mode on or off.");
10839 pw.println(" airplane-mode");
10840 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090010841 pw.println(" set-chain3-enabled [true|false]");
10842 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
10843 pw.println(" get-chain3-enabled");
10844 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
10845 pw.println(" set-package-networking-enabled [true|false] [package name]");
10846 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
10847 + " no effect if the chain is disabled.");
10848 pw.println(" get-package-networking-enabled [package name]");
10849 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070010850 }
10851 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010852
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010853 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010854 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10855 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10856 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010857 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010858 }
10859
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010860 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10861 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010862 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10863 final TransportInfo newInfo = nc.getTransportInfo();
10864 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10865 return;
10866 }
10867 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010868 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010869 }
10870 }
10871
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010872 /**
10873 * @param connectionInfo the connection to resolve.
10874 * @return {@code uid} if the connection is found and the app has permission to observe it
10875 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10876 * connection is not found.
10877 */
10878 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010879 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10880 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10881 }
10882
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010883 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010884 connectionInfo.local, connectionInfo.remote);
10885
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010886 if (uid == INVALID_UID) return uid; // Not found.
10887
10888 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10889 // VPN, if any, that applies to the UID that owns the connection.
10890 if (checkNetworkStackPermission()) return uid;
10891
10892 final NetworkAgentInfo vpn = getVpnForUid(uid);
10893 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010894 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010895 return INVALID_UID;
10896 }
10897
10898 return uid;
10899 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010900
Benedict Wong493e04b2018-11-09 14:45:34 -080010901 /**
10902 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10903 *
10904 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10905 */
10906 @Override
10907 public IBinder startOrGetTestNetworkService() {
10908 synchronized (mTNSLock) {
10909 TestNetworkService.enforceTestNetworkPermissions(mContext);
10910
10911 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010912 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010913 }
10914
10915 return mTNS;
10916 }
10917 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010918
Cody Kesting73708bf2019-12-18 10:57:50 -080010919 /**
10920 * Handler used for managing all Connectivity Diagnostics related functions.
10921 *
10922 * @see android.net.ConnectivityDiagnosticsManager
10923 *
10924 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10925 */
10926 @VisibleForTesting
10927 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010928 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10929
Cody Kesting73708bf2019-12-18 10:57:50 -080010930 /**
10931 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10932 * android.net.ConnectivityDiagnosticsManager}.
10933 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10934 * NetworkRequestInfo to be registered
10935 */
10936 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10937
10938 /**
10939 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10940 * android.net.ConnectivityDiagnosticsManager}.
10941 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10942 * arg1 = the uid of the caller
10943 */
10944 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10945
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010946 /**
10947 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010948 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010949 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10950 * NetworkMonitor.
10951 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010952 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010953 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010954
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010955 /**
10956 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10957 * been detected on the network.
10958 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10959 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10960 * arg2 = NetID.
10961 * data = PersistableBundle of extras passed from NetworkMonitor.
10962 */
10963 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10964
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010965 /**
10966 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10967 * the platform. This event will invoke {@link
10968 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10969 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010970 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010971 */
10972 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10973
Cody Kesting73708bf2019-12-18 10:57:50 -080010974 private ConnectivityDiagnosticsHandler(Looper looper) {
10975 super(looper);
10976 }
10977
10978 @Override
10979 public void handleMessage(Message msg) {
10980 switch (msg.what) {
10981 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10982 handleRegisterConnectivityDiagnosticsCallback(
10983 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10984 break;
10985 }
10986 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10987 handleUnregisterConnectivityDiagnosticsCallback(
10988 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10989 break;
10990 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010991 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010992 final ConnectivityReportEvent reportEvent =
10993 (ConnectivityReportEvent) msg.obj;
10994
Aaron Huang959d3642021-01-21 15:47:41 +080010995 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010996 break;
10997 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010998 case EVENT_DATA_STALL_SUSPECTED: {
10999 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011000 final Pair<Long, PersistableBundle> arg =
11001 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011002 if (nai == null) break;
11003
Aaron Huang959d3642021-01-21 15:47:41 +080011004 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011005 break;
11006 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011007 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011008 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011009 break;
11010 }
11011 default: {
11012 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11013 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011014 }
11015 }
11016 }
11017
11018 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11019 @VisibleForTesting
11020 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11021 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11022 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011023 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011024
11025 @VisibleForTesting
11026 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011027 @NonNull IConnectivityDiagnosticsCallback cb,
11028 @NonNull NetworkRequestInfo nri,
11029 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011030 mCb = cb;
11031 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011032 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011033 }
11034
11035 @Override
11036 public void binderDied() {
11037 log("ConnectivityDiagnosticsCallback IBinder died.");
11038 unregisterConnectivityDiagnosticsCallback(mCb);
11039 }
11040 }
11041
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011042 /**
11043 * Class used for sending information from {@link
11044 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11045 */
11046 private static class NetworkTestedResults {
11047 private final int mNetId;
11048 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011049 @Nullable private final String mRedirectUrl;
11050
11051 private NetworkTestedResults(
11052 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11053 mNetId = netId;
11054 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011055 mRedirectUrl = redirectUrl;
11056 }
11057 }
11058
11059 /**
11060 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11061 * ConnectivityDiagnosticsHandler}.
11062 */
11063 private static class ConnectivityReportEvent {
11064 private final long mTimestampMillis;
11065 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011066 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011067
Aaron Huang959d3642021-01-21 15:47:41 +080011068 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11069 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011070 mTimestampMillis = timestampMillis;
11071 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011072 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011073 }
11074 }
11075
Cody Kestingf1120be2020-08-03 18:01:40 -070011076 /**
11077 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11078 * ConnectivityDiagnosticsHandler}.
11079 */
11080 private static class ReportedNetworkConnectivityInfo {
11081 public final boolean hasConnectivity;
11082 public final boolean isNetworkRevalidating;
11083 public final int reporterUid;
11084 @NonNull public final NetworkAgentInfo nai;
11085
11086 private ReportedNetworkConnectivityInfo(
11087 boolean hasConnectivity,
11088 boolean isNetworkRevalidating,
11089 int reporterUid,
11090 @NonNull NetworkAgentInfo nai) {
11091 this.hasConnectivity = hasConnectivity;
11092 this.isNetworkRevalidating = isNetworkRevalidating;
11093 this.reporterUid = reporterUid;
11094 this.nai = nai;
11095 }
11096 }
11097
Cody Kesting73708bf2019-12-18 10:57:50 -080011098 private void handleRegisterConnectivityDiagnosticsCallback(
11099 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11100 ensureRunningOnConnectivityServiceThread();
11101
11102 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011103 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011104 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11105
James Mattis64b8b0f2020-11-24 17:40:49 -080011106 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11107 // confusing for these networks to change when an NRI is satisfied in another layer.
11108 if (nri.isMultilayerRequest()) {
11109 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11110 + "network requests.");
11111 }
11112
Cody Kesting73708bf2019-12-18 10:57:50 -080011113 // This means that the client registered the same callback multiple times. Do
11114 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011115 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011116 if (VDBG) log("Diagnostics callback is already registered");
11117
11118 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11119 // incremented when the NetworkRequestInfo is created as part of
11120 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011121 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011122 return;
11123 }
11124
Cody Kesting31f1ff62020-03-05 10:46:02 -080011125 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011126
11127 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011128 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011129 } catch (RemoteException e) {
11130 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011131 return;
11132 }
11133
11134 // Once registered, provide ConnectivityReports for matching Networks
11135 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11136 synchronized (mNetworkForNetId) {
11137 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11138 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011139 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11140 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011141 matchingNetworks.add(nai);
11142 }
11143 }
11144 }
11145 for (final NetworkAgentInfo nai : matchingNetworks) {
11146 final ConnectivityReport report = nai.getConnectivityReport();
11147 if (report == null) {
11148 continue;
11149 }
11150 if (!checkConnectivityDiagnosticsPermissions(
11151 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11152 continue;
11153 }
11154
11155 try {
11156 cb.onConnectivityReportAvailable(report);
11157 } catch (RemoteException e) {
11158 // Exception while sending the ConnectivityReport. Move on to the next network.
11159 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011160 }
11161 }
11162
11163 private void handleUnregisterConnectivityDiagnosticsCallback(
11164 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11165 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011166 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011167
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011168 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11169 mConnectivityDiagnosticsCallbacks.remove(iCb);
11170 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011171 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11172 return;
11173 }
11174
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011175 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011176
Cody Kesting70fa2b22020-12-02 12:16:56 -080011177 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11178 // (if the Binder died)
11179 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11180 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011181 return;
11182 }
11183
Cody Kesting46cb1672020-03-04 13:35:20 -080011184 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11185 // incremented when the NetworkRequestInfo is created as part of
11186 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011187 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011188
Cody Kesting31f1ff62020-03-05 10:46:02 -080011189 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011190 }
11191
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011192 private void handleNetworkTestedWithExtras(
11193 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11194 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011195 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011196 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011197 final ConnectivityReport report =
11198 new ConnectivityReport(
11199 reportEvent.mNai.network,
11200 reportEvent.mTimestampMillis,
11201 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011202 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011203 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011204 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011205
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011206 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011207 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011208 for (final IConnectivityDiagnosticsCallback cb : results) {
11209 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011210 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011211 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011212 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011213 }
11214 }
11215 }
11216
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011217 private void handleDataStallSuspected(
11218 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11219 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011220 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011221 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011222 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011223 new DataStallReport(
11224 nai.network,
11225 timestampMillis,
11226 detectionMethod,
11227 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011228 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011229 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011230 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011231 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011232 for (final IConnectivityDiagnosticsCallback cb : results) {
11233 try {
11234 cb.onDataStallSuspected(report);
11235 } catch (RemoteException ex) {
11236 loge("Error invoking onDataStallSuspected", ex);
11237 }
11238 }
11239 }
11240
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011241 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011242 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11243 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11244 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11245
11246 // If the Network is being re-validated as a result of this call to
11247 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11248 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011249 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011250 getMatchingPermissionedCallbacks(
11251 nai,
11252 reportedNetworkConnectivityInfo.isNetworkRevalidating
11253 ? Process.INVALID_UID
11254 : reportedNetworkConnectivityInfo.reporterUid);
11255
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011256 for (final IConnectivityDiagnosticsCallback cb : results) {
11257 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011258 cb.onNetworkConnectivityReported(
11259 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011260 } catch (RemoteException ex) {
11261 loge("Error invoking onNetworkConnectivityReported", ex);
11262 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011263
11264 // If the Network isn't re-validating, also provide the cached report. If there is no
11265 // cached report, the Network is still being validated and a report will be sent once
11266 // validation is complete. Note that networks which never undergo validation will still
11267 // have a cached ConnectivityReport with RESULT_SKIPPED.
11268 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11269 try {
11270 cb.onConnectivityReportAvailable(cachedReport);
11271 } catch (RemoteException ex) {
11272 loge("Error invoking onConnectivityReportAvailable", ex);
11273 }
11274 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011275 }
11276 }
11277
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011278 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011279 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11280 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011281 sanitized.setUids(null);
11282 sanitized.setAdministratorUids(new int[0]);
11283 sanitized.setOwnerUid(Process.INVALID_UID);
11284 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011285 }
11286
Cody Kestingf1120be2020-08-03 18:01:40 -070011287 /**
11288 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11289 *
11290 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11291 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011292 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011293 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011294 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011295 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011296 mConnectivityDiagnosticsCallbacks.entrySet()) {
11297 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11298 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011299
James Mattis64b8b0f2020-11-24 17:40:49 -080011300 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011301 if (!nai.satisfies(nri.mRequests.get(0))) {
11302 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011303 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011304
11305 // UID for this callback must either be:
11306 // - INVALID_UID (which sends callbacks to all UIDs), or
11307 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11308 // notified as a result)
11309 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11310 continue;
11311 }
11312
11313 if (!checkConnectivityDiagnosticsPermissions(
11314 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11315 continue;
11316 }
11317
11318 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011319 }
11320 return results;
11321 }
11322
Cody Kesting7474f672021-05-11 14:22:40 -070011323 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11324 @NonNull NetworkAgentInfo nai) {
11325 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11326 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11327 }
11328
Cody Kesting160ef392021-05-05 13:17:22 -070011329 private boolean hasLocationPermission(String packageName, int uid) {
11330 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11331 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11332 // call in a try-catch.
11333 try {
11334 if (!mLocationPermissionChecker.checkLocationPermission(
11335 packageName, null /* featureId */, uid, null /* message */)) {
11336 return false;
11337 }
11338 } catch (SecurityException e) {
11339 return false;
11340 }
11341
11342 return true;
11343 }
11344
11345 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11346 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011347 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011348 && virtual.networkCapabilities.getOwnerUid() == uid
11349 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11350 return true;
11351 }
11352 }
11353
11354 return false;
11355 }
11356
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011357 @VisibleForTesting
11358 boolean checkConnectivityDiagnosticsPermissions(
11359 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11360 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11361 return true;
11362 }
11363
Cody Kesting160ef392021-05-05 13:17:22 -070011364 // Administrator UIDs also contains the Owner UID
11365 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11366 if (!CollectionUtils.contains(administratorUids, callbackUid)
11367 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011368 return false;
11369 }
11370
Cody Kesting7474f672021-05-11 14:22:40 -070011371 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11372 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011373 }
11374
Cody Kestingd199a9d2019-12-17 12:55:28 -080011375 @Override
11376 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011377 @NonNull IConnectivityDiagnosticsCallback callback,
11378 @NonNull NetworkRequest request,
11379 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011380 Objects.requireNonNull(callback, "callback must not be null");
11381 Objects.requireNonNull(request, "request must not be null");
11382 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11383
Cody Kesting73708bf2019-12-18 10:57:50 -080011384 if (request.legacyType != TYPE_NONE) {
11385 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11386 + " Please use NetworkCapabilities instead.");
11387 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011388 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011389 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011390
11391 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11392 // and administrator uids to be safe.
11393 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011394 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011395
11396 final NetworkRequest requestWithId =
11397 new NetworkRequest(
11398 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11399
11400 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11401 //
11402 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11403 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11404 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011405 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011406 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011407 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011408
11409 mConnectivityDiagnosticsHandler.sendMessage(
11410 mConnectivityDiagnosticsHandler.obtainMessage(
11411 ConnectivityDiagnosticsHandler
11412 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11413 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011414 }
11415
11416 @Override
11417 public void unregisterConnectivityDiagnosticsCallback(
11418 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011419 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011420 mConnectivityDiagnosticsHandler.sendMessage(
11421 mConnectivityDiagnosticsHandler.obtainMessage(
11422 ConnectivityDiagnosticsHandler
11423 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011424 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011425 0,
11426 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011427 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011428
Yan Yanfe96dde2022-12-05 23:00:01 +000011429 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11430 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11431 if (underlyingNetworks == null) return false;
11432
11433 for (Network network : underlyingNetworks) {
11434 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11435 return true;
11436 }
11437 }
11438 return false;
11439 }
11440
Cody Kestingf53a0752020-04-15 12:33:28 -070011441 @Override
11442 public void simulateDataStall(int detectionMethod, long timestampMillis,
11443 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011444 Objects.requireNonNull(network, "network must not be null");
11445 Objects.requireNonNull(extras, "extras must not be null");
11446
paulhu3ffffe72021-09-16 10:15:22 +080011447 enforceAnyPermissionOf(mContext,
11448 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011449 android.Manifest.permission.NETWORK_STACK);
11450 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011451 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11452 throw new SecurityException(
11453 "Data Stall simulation is only possible for test networks or networks built on"
11454 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011455 }
11456
11457 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011458 if (nai == null
11459 || (nai.creatorUid != mDeps.getCallingUid()
11460 && nai.creatorUid != Process.SYSTEM_UID)) {
11461 throw new SecurityException(
11462 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011463 }
11464
Cody Kesting652e3ec2020-05-21 12:08:21 -070011465 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11466 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11467 // Data Stall information as a DataStallReportParcelable and passing to
11468 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11469 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011470 final DataStallReportParcelable p = new DataStallReportParcelable();
11471 p.timestampMillis = timestampMillis;
11472 p.detectionMethod = detectionMethod;
11473
11474 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11475 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11476 }
11477 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11478 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11479 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11480 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11481 }
11482
Serik Beketayevec8ad212020-12-07 22:43:07 -080011483 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011484 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011485
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011486 /**
11487 * Class to hold the information for network activity change event from idle timers
11488 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
11489 */
11490 private static final class NetworkActivityParams {
11491 public final boolean isActive;
11492 // Label used for idle timer. Transport type is used as label.
11493 // label is int since NMS was using the identifier as int, and it has not been changed
11494 public final int label;
11495 public final long timestampNs;
11496 // Uid represents the uid that was responsible for waking the radio.
11497 // -1 for no uid and uid is -1 if isActive is false.
11498 public final int uid;
11499
11500 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
11501 this.isActive = isActive;
11502 this.label = label;
11503 this.timestampNs = timestampNs;
11504 this.uid = uid;
11505 }
11506 }
11507
lucaslin66f44212021-02-23 01:12:55 +080011508 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11509 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011510 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080011511 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011512 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
11513 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080011514 }
lucaslin37a16d92021-01-21 19:48:09 +080011515
11516 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011517 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011518 mHandler.post(() -> {
11519 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011520 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011521 }
11522 });
lucaslin37a16d92021-01-21 19:48:09 +080011523 }
11524
11525 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011526 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011527 mHandler.post(() -> {
11528 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090011529 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090011530 }
11531 });
lucaslin66f44212021-02-23 01:12:55 +080011532 }
11533 }
11534
lucaslin1a8b4c62021-01-21 02:02:55 +080011535 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11536
11537 /**
11538 * Class used for updating network activity tracking with netd and notify network activity
11539 * changes.
11540 */
11541 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011542 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011543 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011544 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011545 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080011546 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11547 new RemoteCallbackList<>();
11548 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090011549 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011550 // If there is no default network, default network is considered active to keep the existing
11551 // behavior. Initial value is used until first connect to the default network.
11552 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011553 // Key is netId. Value is configured idle timer information.
11554 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080011555
Chalard Jean46bfbf02022-02-02 00:56:25 +090011556 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011557 public final int timeout;
11558 public final int transportType;
11559
11560 IdleTimerParams(int timeout, int transport) {
11561 this.timeout = timeout;
11562 this.transportType = transport;
11563 }
11564 }
11565
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011566 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011567 @NonNull Handler handler) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011568 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011569 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011570 mHandler = handler;
11571 }
11572
11573 private void ensureRunningOnConnectivityServiceThread() {
11574 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
11575 throw new IllegalStateException("Not running on ConnectivityService thread: "
11576 + Thread.currentThread().getName());
11577 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011578 }
11579
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011580 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011581 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011582 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011583 // This activity change is not for the current default network.
11584 // This can happen if netd callback post activity change event message but
11585 // the default network is lost before processing this message.
11586 return;
11587 }
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090011588 sendDataActivityBroadcast(transportTypeToLegacyType(activityParams.label),
11589 activityParams.isActive, activityParams.timestampNs);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011590 mIsDefaultNetworkActive = activityParams.isActive;
11591 if (mIsDefaultNetworkActive) {
11592 reportNetworkActive();
lucaslin66f44212021-02-23 01:12:55 +080011593 }
11594 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011595
lucaslin1193a5d2021-01-21 02:04:15 +080011596 private void reportNetworkActive() {
11597 final int length = mNetworkActivityListeners.beginBroadcast();
11598 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11599 try {
11600 for (int i = 0; i < length; i++) {
11601 try {
11602 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11603 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011604 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011605 }
11606 }
11607 } finally {
11608 mNetworkActivityListeners.finishBroadcast();
11609 }
11610 }
11611
lucaslin1a8b4c62021-01-21 02:02:55 +080011612 // This is deprecated and only to support legacy use cases.
11613 private int transportTypeToLegacyType(int type) {
11614 switch (type) {
11615 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011616 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011617 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011618 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011619 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011620 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011621 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011622 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011623 default:
11624 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11625 }
11626 return ConnectivityManager.TYPE_NONE;
11627 }
11628
11629 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11630 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11631 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11632 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11633 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11634 final long ident = Binder.clearCallingIdentity();
11635 try {
11636 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11637 RECEIVE_DATA_ACTIVITY_CHANGE,
11638 null /* resultReceiver */,
11639 null /* scheduler */,
11640 0 /* initialCode */,
11641 null /* initialData */,
11642 null /* initialExtra */);
11643 } finally {
11644 Binder.restoreCallingIdentity(ident);
11645 }
11646 }
11647
11648 /**
11649 * Setup data activity tracking for the given network.
11650 *
11651 * Every {@code setupDataActivityTracking} should be paired with a
11652 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090011653 *
11654 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080011655 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090011656 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011657 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011658 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011659
11660 final int timeout;
11661 final int type;
11662
11663 if (networkAgent.networkCapabilities.hasTransport(
11664 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11665 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011666 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011667 10);
11668 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11669 } else if (networkAgent.networkCapabilities.hasTransport(
11670 NetworkCapabilities.TRANSPORT_WIFI)) {
11671 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011672 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011673 15);
11674 type = NetworkCapabilities.TRANSPORT_WIFI;
11675 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011676 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080011677 }
11678
lucaslinb961efc2021-01-21 02:03:17 +080011679 updateRadioPowerState(true /* isActive */, type);
11680
lucaslin1a8b4c62021-01-21 02:02:55 +080011681 if (timeout > 0 && iface != null) {
11682 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011683 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, type));
Motomu Utsumic298cf02023-05-31 12:06:12 +090011684 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
Motomu Utsumi6225d572023-05-29 15:08:57 +090011685 return true;
lucaslin1a8b4c62021-01-21 02:02:55 +080011686 } catch (Exception e) {
11687 // You shall not crash!
11688 loge("Exception in setupDataActivityTracking " + e);
11689 }
11690 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011691 return false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011692 }
11693
11694 /**
11695 * Remove data activity tracking when network disconnects.
11696 */
11697 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11698 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011699 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080011700 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11701
lucaslinb961efc2021-01-21 02:03:17 +080011702 if (iface == null) return;
11703
11704 final int type;
11705 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11706 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11707 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11708 type = NetworkCapabilities.TRANSPORT_WIFI;
11709 } else {
11710 return; // do not track any other networks
11711 }
11712
11713 try {
11714 updateRadioPowerState(false /* isActive */, type);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011715 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011716 if (params == null) {
11717 // IdleTimer is not added if the configured timeout is 0 or negative value
11718 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080011719 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011720 mActiveIdleTimers.remove(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090011721 // The call fails silently if no idle timer setup for this interface
11722 mNetd.idletimerRemoveInterface(iface, params.timeout,
11723 Integer.toString(params.transportType));
lucaslinb961efc2021-01-21 02:03:17 +080011724 } catch (Exception e) {
11725 // You shall not crash!
11726 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011727 }
11728 }
11729
Motomu Utsumi6225d572023-05-29 15:08:57 +090011730 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
11731 boolean hasIdleTimer) {
11732 if (defaultNetwork != null) {
11733 mIsDefaultNetworkActive = true;
Motomu Utsumi1e51a642023-07-18 15:11:41 +090011734 // Callbacks are called only when the network has the idle timer.
11735 if (hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011736 reportNetworkActive();
11737 }
11738 } else {
Motomu Utsumi51e7a602023-07-31 19:26:18 +090011739 // If there is no default network, default network is considered active to keep the
11740 // existing behavior.
11741 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090011742 }
11743 }
11744
lucaslin1a8b4c62021-01-21 02:02:55 +080011745 /**
11746 * Update data activity tracking when network state is updated.
11747 */
11748 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11749 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090011750 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi6225d572023-05-29 15:08:57 +090011751 boolean hasIdleTimer = false;
lucaslin1a8b4c62021-01-21 02:02:55 +080011752 if (newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090011753 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080011754 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090011755 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
lucaslin1a8b4c62021-01-21 02:02:55 +080011756 if (oldNetwork != null) {
11757 removeDataActivityTracking(oldNetwork);
11758 }
11759 }
lucaslinb961efc2021-01-21 02:03:17 +080011760
11761 private void updateRadioPowerState(boolean isActive, int transportType) {
11762 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11763 switch (transportType) {
11764 case NetworkCapabilities.TRANSPORT_CELLULAR:
11765 bs.reportMobileRadioPowerState(isActive, NO_UID);
11766 break;
11767 case NetworkCapabilities.TRANSPORT_WIFI:
11768 bs.reportWifiRadioPowerState(isActive, NO_UID);
11769 break;
11770 default:
11771 logw("Untracked transport type:" + transportType);
11772 }
11773 }
lucaslin1193a5d2021-01-21 02:04:15 +080011774
11775 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011776 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080011777 }
11778
11779 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11780 mNetworkActivityListeners.register(l);
11781 }
11782
11783 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11784 mNetworkActivityListeners.unregister(l);
11785 }
lucaslin012f7a12021-01-21 02:04:35 +080011786
11787 public void dump(IndentingPrintWriter pw) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090011788 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
11789 pw.println("Idle timers:");
11790 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090011791 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
11792 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
11793 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080011794 pw.print(" timeout="); pw.print(params.timeout);
11795 pw.print(" type="); pw.println(params.transportType);
11796 }
Motomu Utsumic298cf02023-05-31 12:06:12 +090011797 } catch (Exception e) {
11798 // mActiveIdleTimers should only be accessed from handler thread, except dump().
11799 // As dump() is never called in normal usage, it would be needlessly expensive
11800 // to lock the collection only for its benefit.
11801 // Also, mActiveIdleTimers is not expected to be updated frequently.
11802 // So catching the exception and logging.
11803 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080011804 }
11805 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011806 }
James Mattis47db0582021-01-01 14:13:35 -080011807
Daniel Brightf9e945b2020-06-15 16:10:01 -070011808 /**
11809 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11810 *
11811 * @param socketInfo the socket information
11812 * @param callback the callback to register
11813 */
11814 @Override
11815 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11816 @NonNull final IQosCallback callback) {
11817 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11818 if (nai == null || nai.networkCapabilities == null) {
11819 try {
11820 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11821 } catch (final RemoteException ex) {
11822 loge("registerQosCallbackInternal: RemoteException", ex);
11823 }
11824 return;
11825 }
11826 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11827 }
11828
11829 /**
11830 * Register a {@link IQosCallback} with base {@link QosFilter}.
11831 *
11832 * @param filter the filter to register
11833 * @param callback the callback to register
11834 * @param nai the agent information related to the filter's network
11835 */
11836 @VisibleForTesting
11837 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11838 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011839 Objects.requireNonNull(filter, "filter must be non-null");
11840 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011841
11842 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011843 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11844 // on this network is unregistered when the app loses permission or b) no QoS
11845 // callbacks are sent for restricted networks unless the app currently has permission
11846 // to access restricted networks.
11847 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011848 }
11849 mQosCallbackTracker.registerCallback(callback, filter, nai);
11850 }
11851
11852 /**
11853 * Unregisters the given callback.
11854 *
11855 * @param callback the callback to unregister
11856 */
11857 @Override
11858 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011859 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011860 mQosCallbackTracker.unregisterCallback(callback);
11861 }
James Mattis47db0582021-01-01 14:13:35 -080011862
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011863 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11864 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11865 // Enterprise device can be fully managed like device owner and such use case
11866 // also should be supported. Calling app check for work profile and fully managed device
11867 // is already done in DevicePolicyManager.
11868 // This check is an extra caution to be sure device is fully managed or not.
11869 final UserManager um = mContext.getSystemService(UserManager.class);
11870 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11871 if (um.isManagedProfile(profile.getIdentifier())) {
11872 return true;
11873 }
Chalard Jeandf29a852023-05-29 17:02:43 +090011874 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011875 return false;
11876 }
11877
James Mattis45d81842021-01-10 14:24:24 -080011878 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011879 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011880 *
11881 * See the documentation for the individual preferences for a description of the supported
11882 * behaviors.
11883 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011884 * @param profile If the device owner is set, any profile is allowed.
11885 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011886 * @param preferences the list of profile network preferences for the
11887 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011888 * @param listener an optional listener to listen for completion of the operation.
11889 */
11890 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011891 public void setProfileNetworkPreferences(
11892 @NonNull final UserHandle profile,
11893 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011894 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011895 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011896 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011897
11898 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011899 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11900 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11901 .build();
11902 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011903 }
11904
paulhu3ffffe72021-09-16 10:15:22 +080011905 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011906 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011907 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011908 }
11909 if (profile.getIdentifier() < 0) {
11910 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11911 + "UserHandle.CURRENT not supported)");
11912 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011913 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11914 throw new IllegalArgumentException("Profile must be a managed profile "
11915 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011916 }
paulhuaa0743d2021-05-26 21:56:03 +080011917
Chalard Jean0606fc82022-12-14 20:34:43 +090011918 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011919 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011920 for (final ProfileNetworkPreference preference : preferences) {
11921 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011922 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011923 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011924 switch (preference.getPreference()) {
11925 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11926 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011927 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011928 if (preference.getPreferenceEnterpriseId() != 0) {
11929 throw new IllegalArgumentException(
11930 "Invalid enterprise identifier in setProfileNetworkPreferences");
11931 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011932 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011933 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11934 blockingNonEnterprise = true;
11935 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011936 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11937 allowFallback = false;
11938 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011939 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011940 // This code is needed even though there is a check later on,
11941 // because isRangeAlreadyInPreferenceList assumes that every preference
11942 // has a UID list.
11943 if (hasDefaultPreference) {
11944 throw new IllegalArgumentException(
11945 "Default profile preference should not be set along with other "
11946 + "preference");
11947 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011948 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11949 throw new IllegalArgumentException(
11950 "Invalid enterprise identifier in setProfileNetworkPreferences");
11951 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011952 final Set<UidRange> uidRangeSet =
11953 getUidListToBeAppliedForNetworkPreference(profile, preference);
11954 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11955 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11956 } else {
11957 throw new IllegalArgumentException(
11958 "Overlapping uid range in setProfileNetworkPreferences");
11959 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011960 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011961 nc.addEnterpriseId(
11962 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011963 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11964 break;
11965 default:
11966 throw new IllegalArgumentException(
11967 "Invalid preference in setProfileNetworkPreferences");
11968 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011969 preferenceList.add(new ProfileNetworkPreferenceInfo(
11970 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011971 if (hasDefaultPreference && preferenceList.size() > 1) {
11972 throw new IllegalArgumentException(
11973 "Default profile preference should not be set along with other preference");
11974 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011975 }
11976 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011977 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011978 }
11979
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011980 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11981 @NonNull final UserHandle profile,
11982 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11983 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011984 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11985 profileNetworkPreference.getIncludedUids());
11986
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011987 if (uidRangeSet.size() > 0) {
11988 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11989 throw new IllegalArgumentException(
11990 "Allow uid range is outside the uid range of profile.");
11991 }
11992 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011993 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011994 profileNetworkPreference.getExcludedUids());
11995 if (disallowUidRangeSet.size() > 0) {
11996 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11997 throw new IllegalArgumentException(
11998 "disallow uid range is outside the uid range of profile.");
11999 }
12000 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12001 disallowUidRangeSet);
12002 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012003 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012004 uidRangeSet.add(profileUids);
12005 }
12006 }
12007 return uidRangeSet;
12008 }
12009
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012010 private boolean isEnterpriseIdentifierValid(
12011 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012012 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012013 return true;
12014 }
12015 return false;
12016 }
12017
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012018 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012019 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012020 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012021 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012022 // The NRI for a user should contain the request for capabilities.
12023 // If fallback to default network is needed then NRI should include
12024 // the request for the default network. Create an image of it to
12025 // have the correct UIDs in it (also a request can only be part of one NRI, because
12026 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012027 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12028 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012029 if (pref.allowFallback) {
12030 nrs.add(createDefaultInternetRequestForTransport(
12031 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12032 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012033 if (VDBG) {
12034 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12035 pref.capabilities.getUids()));
12036 }
12037
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012038 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012039 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012040 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012041 result.add(nri);
12042 }
12043 return result;
12044 }
12045
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012046 /**
12047 * Compare if the given UID range sets have the same UIDs.
12048 *
12049 */
12050 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012051 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012052 @NonNull Set<UidRange> uidRangeSet) {
12053 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12054 return false;
12055 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012056 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012057 if (UidRangeUtils.doesRangeSetOverlap(
12058 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12059 return true;
12060 }
12061 }
12062 return false;
12063 }
12064
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012065 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012066 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012067 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012068 /*
12069 * handleSetProfileNetworkPreference is always called for single user.
12070 * preferenceList only contains preferences for different uids within the same user
12071 * (enforced by getUidListToBeAppliedForNetworkPreference).
12072 * Clear all the existing preferences for the user before applying new preferences.
12073 *
12074 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012075 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12076 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012077 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12078 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012079
paulhu74128522021-09-28 02:29:03 +000012080 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12081 addPerAppDefaultNetworkRequests(
12082 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012083 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012084
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012085 // Finally, rematch.
12086 rematchAllNetworksAndRequests();
12087
12088 if (null != listener) {
12089 try {
12090 listener.onComplete();
12091 } catch (RemoteException e) {
12092 loge("Listener for setProfileNetworkPreference has died");
12093 }
12094 }
12095 }
12096
paulhu51f77dc2021-06-07 02:34:20 +000012097 @VisibleForTesting
12098 @NonNull
12099 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12100 @NonNull final Set<Integer> uids) {
12101 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12102 if (uids.size() == 0) {
12103 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12104 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12105 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12106 return nris;
12107 }
12108
12109 final List<NetworkRequest> requests = new ArrayList<>();
12110 // The NRI should be comprised of two layers:
12111 // - The request for the mobile network preferred.
12112 // - The request for the default network, for fallback.
12113 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012114 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012115 requests.add(createDefaultInternetRequestForTransport(
12116 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12117 final Set<UidRange> ranges = new ArraySet<>();
12118 for (final int uid : uids) {
12119 ranges.add(new UidRange(uid, uid));
12120 }
12121 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012122 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012123 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012124 return nris;
12125 }
12126
12127 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012128 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012129 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12130 addPerAppDefaultNetworkRequests(
12131 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012132 // Finally, rematch.
12133 rematchAllNetworksAndRequests();
12134 }
12135
Patrick Rohr2857ac42022-01-21 14:58:16 +010012136 private void handleIngressRateLimitChanged() {
12137 final long oldIngressRateLimit = mIngressRateLimit;
12138 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12139 mContext);
12140 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12141 if (canNetworkBeRateLimited(networkAgent)) {
12142 // If rate limit has previously been enabled, remove the old limit first.
12143 if (oldIngressRateLimit >= 0) {
12144 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12145 }
12146 if (mIngressRateLimit >= 0) {
12147 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12148 mIngressRateLimit);
12149 }
12150 }
12151 }
12152 }
12153
12154 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012155 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012156 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012157
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012158 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12159 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12160 // internet connectivity can be rate limited.
12161 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12162 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012163 return false;
12164 }
12165
12166 final String iface = networkAgent.linkProperties.getInterfaceName();
12167 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012168 // This may happen in tests, but if there is no interface then there is nothing that
12169 // can be rate limited.
12170 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012171 return false;
12172 }
12173 return true;
12174 }
12175
James Mattis45d81842021-01-10 14:24:24 -080012176 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012177 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12178 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012179 }
12180
12181 /**
12182 * Used by automotive devices to set the network preferences used to direct traffic at an
12183 * application level as per the given OemNetworkPreferences. An example use-case would be an
12184 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12185 * vehicle via a particular network.
12186 *
12187 * Calling this will overwrite the existing preference.
12188 *
James Mattisda32cfe2021-01-26 16:23:52 -080012189 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012190 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012191 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012192 */
James Mattis47db0582021-01-01 14:13:35 -080012193 @Override
James Mattis45d81842021-01-10 14:24:24 -080012194 public void setOemNetworkPreference(
12195 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012196 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012197
James Mattisfa270db2021-05-31 17:11:10 -070012198 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12199 // Only bypass the permission/device checks if this is a valid test request.
12200 if (isValidTestOemNetworkPreference(preference)) {
12201 enforceManageTestNetworksPermission();
12202 } else {
12203 enforceAutomotiveDevice();
12204 enforceOemNetworkPreferencesPermission();
12205 validateOemNetworkPreferences(preference);
12206 }
James Mattis45d81842021-01-10 14:24:24 -080012207
James Mattis45d81842021-01-10 14:24:24 -080012208 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12209 new Pair<>(preference, listener)));
12210 }
12211
James Mattisfa270db2021-05-31 17:11:10 -070012212 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012213 * Sets the specified UIDs to get/receive the VPN as the only default network.
12214 *
12215 * Calling this will overwrite the existing network preference for this session, and the
12216 * specified UIDs won't get any default network when no VPN is connected.
12217 *
12218 * @param session The VPN session which manages the passed UIDs.
12219 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12220 * setting for this session if the array is empty. Null is not allowed, the
12221 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12222 * @hide
12223 */
12224 @Override
12225 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12226 Objects.requireNonNull(ranges);
12227 enforceNetworkStackOrSettingsPermission();
12228 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12229 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12230 throw new IllegalArgumentException(
12231 "setVpnNetworkPreference: Passed UID ranges overlap");
12232 }
12233
12234 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12235 new VpnNetworkPreferenceInfo(session,
12236 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12237 }
12238
12239 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12240 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12241
12242 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12243 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12244
12245 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12246 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12247 // Finally, rematch.
12248 rematchAllNetworksAndRequests();
12249 }
12250
12251 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12252 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12253 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12254 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12255 final List<NetworkRequest> requests = new ArrayList<>();
12256 // Request VPN only, so other networks won't be the fallback options when VPN is not
12257 // connected temporarily.
12258 requests.add(createVpnRequest());
12259 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12260 setNetworkRequestUids(requests, uidRanges);
12261 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12262 }
12263 return nris;
12264 }
12265
12266 /**
James Mattisfa270db2021-05-31 17:11:10 -070012267 * Check the validity of an OEM network preference to be used for testing purposes.
12268 * @param preference the preference to validate
12269 * @return true if this is a valid OEM network preference test request.
12270 */
12271 private boolean isValidTestOemNetworkPreference(
12272 @NonNull final OemNetworkPreferences preference) {
12273 // Allow for clearing of an existing OemNetworkPreference used for testing.
12274 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12275 // changes after this check is complete. This is an unlikely scenario as calling of this API
12276 // is controlled by the OEM therefore the added complexity is not worth adding given those
12277 // circumstances. That said, it is an edge case to be aware of hence this comment.
12278 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12279 && isTestOemNetworkPreference(mOemNetworkPreferences);
12280 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12281 }
12282
12283 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12284 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12285 return prefMap.size() == 1
12286 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12287 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12288 }
12289
James Mattis45d81842021-01-10 14:24:24 -080012290 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12291 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12292 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012293 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12294 throw new IllegalArgumentException(
12295 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12296 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012297 }
12298 }
12299 }
12300
12301 private void handleSetOemNetworkPreference(
12302 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012303 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012304 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12305 if (DBG) {
12306 log("set OEM network preferences :" + preference.toString());
12307 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012308
James Mattiscb1e0362021-04-06 17:07:42 -070012309 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012310 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12311 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12312 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012313 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012314
12315 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012316 try {
12317 listener.onComplete();
12318 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012319 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012320 }
James Mattis45d81842021-01-10 14:24:24 -080012321 }
12322 }
12323
paulhu74128522021-09-28 02:29:03 +000012324 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012325 // Skip the requests which are set by other network preference. Because the uid range rules
12326 // should stay in netd.
12327 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012328 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012329 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012330 }
12331
James Mattis3ce3d3c2021-02-09 18:18:28 -080012332 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12333 ensureRunningOnConnectivityServiceThread();
12334 mDefaultNetworkRequests.addAll(nris);
12335 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12336 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012337 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012338 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12339 nrisToRegister.addAll(
12340 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12341 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012342 }
12343
12344 /**
12345 * All current requests that are tracking the default network need to be assessed as to whether
12346 * or not the current set of per-application default requests will be changing their default
12347 * network. If so, those requests will need to be updated so that they will send callbacks for
12348 * default network changes at the appropriate time. Additionally, those requests tracking the
12349 * default that were previously updated by this flow will need to be reassessed.
12350 * @return the nris which will need to be updated.
12351 */
12352 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12353 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12354 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12355 // same nri in the map's values for each of its NetworkRequest objects.
12356 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012357 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012358 // Include this nri if it is currently being tracked.
12359 if (isPerAppTrackedNri(nri)) {
12360 defaultCallbackRequests.add(nri);
12361 continue;
12362 }
12363 // We only track callbacks for requests tracking the default.
12364 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12365 continue;
12366 }
12367 // Include this nri if it will be tracked by the new per-app default requests.
12368 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012369 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012370 if (isNriGoingToBeTracked) {
12371 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012372 }
12373 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012374 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012375 }
12376
James Mattis3ce3d3c2021-02-09 18:18:28 -080012377 /**
12378 * Create nris for those network requests that are currently tracking the default network that
12379 * are being controlled by a per-application default.
12380 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12381 * foundation when creating the nri. Important items include the calling uid's original
12382 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12383 * requests are assumed to have already been validated as needing to be updated.
12384 * @return the Set of nris to use when registering network requests.
12385 */
12386 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12387 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12388 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12389 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12390 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012391 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012392
Chalard Jean9473c982021-07-29 20:03:04 +090012393 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012394 if (trackingNri == mDefaultRequest) {
12395 callbackRequestsToRegister.add(new NetworkRequestInfo(
12396 callbackRequest,
12397 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12398 continue;
12399 }
12400
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012401 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012402 callbackRequestsToRegister.add(new NetworkRequestInfo(
12403 callbackRequest,
12404 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012405 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012406 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012407 }
12408 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012409 }
12410
Chalard Jean17215832021-03-01 14:06:28 +090012411 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12412 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012413 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012414 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012415 }
12416 }
12417
James Mattis45d81842021-01-10 14:24:24 -080012418 /**
12419 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12420 */
12421 @VisibleForTesting
12422 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012423 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012424 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012425 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012426 final SparseArray<Set<Integer>> uids =
12427 createUidsFromOemNetworkPreferences(preference);
12428 for (int i = 0; i < uids.size(); i++) {
12429 final int key = uids.keyAt(i);
12430 final Set<Integer> value = uids.valueAt(i);
12431 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12432 // No need to add an nri without any requests.
12433 if (0 == nri.mRequests.size()) {
12434 continue;
12435 }
12436 nris.add(nri);
12437 }
12438
12439 return nris;
12440 }
12441
12442 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12443 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012444 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012445 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012446 final List<UserHandle> users =
12447 mContext.getSystemService(UserManager.class).getUserHandles(true);
12448 if (null == users || users.size() == 0) {
12449 if (VDBG || DDBG) {
12450 log("No users currently available for setting the OEM network preference.");
12451 }
James Mattisb6b6a432021-06-01 22:30:36 -070012452 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012453 }
James Mattis45d81842021-01-10 14:24:24 -080012454 for (final Map.Entry<String, Integer> entry :
12455 preference.getNetworkPreferences().entrySet()) {
12456 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012457 // Add the rules for all users as this policy is device wide.
12458 for (final UserHandle user : users) {
12459 try {
12460 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12461 if (!prefToUids.contains(pref)) {
12462 prefToUids.put(pref, new ArraySet<>());
12463 }
12464 prefToUids.get(pref).add(uid);
12465 } catch (PackageManager.NameNotFoundException e) {
12466 // Although this may seem like an error scenario, it is ok that uninstalled
12467 // packages are sent on a network preference as the system will watch for
12468 // package installations associated with this network preference and update
12469 // accordingly. This is done to minimize race conditions on app install.
12470 continue;
James Mattis45d81842021-01-10 14:24:24 -080012471 }
James Mattis45d81842021-01-10 14:24:24 -080012472 }
12473 }
James Mattisb6b6a432021-06-01 22:30:36 -070012474 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012475 }
12476
12477 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12478 @OemNetworkPreferences.OemNetworkPreference final int preference,
12479 @NonNull final Set<Integer> uids) {
12480 final List<NetworkRequest> requests = new ArrayList<>();
12481 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12482 switch (preference) {
12483 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12484 requests.add(createUnmeteredNetworkRequest());
12485 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012486 requests.add(createDefaultInternetRequestForTransport(
12487 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012488 break;
12489 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12490 requests.add(createUnmeteredNetworkRequest());
12491 requests.add(createOemPaidNetworkRequest());
12492 break;
12493 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12494 requests.add(createOemPaidNetworkRequest());
12495 break;
12496 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12497 requests.add(createOemPrivateNetworkRequest());
12498 break;
James Mattisfa270db2021-05-31 17:11:10 -070012499 case OEM_NETWORK_PREFERENCE_TEST:
12500 requests.add(createUnmeteredNetworkRequest());
12501 requests.add(createTestNetworkRequest());
12502 requests.add(createDefaultRequest());
12503 break;
12504 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12505 requests.add(createTestNetworkRequest());
12506 break;
James Mattis45d81842021-01-10 14:24:24 -080012507 default:
12508 // This should never happen.
12509 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12510 + " called with invalid preference of " + preference);
12511 }
12512
James Mattisfa270db2021-05-31 17:11:10 -070012513 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012514 for (final int uid : uids) {
12515 ranges.add(new UidRange(uid, uid));
12516 }
12517 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012518 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012519 }
12520
12521 private NetworkRequest createUnmeteredNetworkRequest() {
12522 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12523 .addCapability(NET_CAPABILITY_NOT_METERED)
12524 .addCapability(NET_CAPABILITY_VALIDATED);
12525 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12526 }
12527
12528 private NetworkRequest createOemPaidNetworkRequest() {
12529 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12530 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12531 .addCapability(NET_CAPABILITY_OEM_PAID)
12532 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12533 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12534 }
12535
12536 private NetworkRequest createOemPrivateNetworkRequest() {
12537 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12538 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12539 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12540 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12541 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12542 }
12543
12544 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012545 final NetworkCapabilities netcap = new NetworkCapabilities();
12546 netcap.addCapability(NET_CAPABILITY_INTERNET);
12547 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12548 return netcap;
12549 }
12550
12551 private NetworkRequest createTestNetworkRequest() {
12552 final NetworkCapabilities netcap = new NetworkCapabilities();
12553 netcap.clearAll();
12554 netcap.addTransportType(TRANSPORT_TEST);
12555 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012556 }
James Mattis47db0582021-01-01 14:13:35 -080012557 }
markchien738ad912021-12-09 18:15:45 +080012558
Ken Chen24330172023-10-20 13:02:14 +080012559 @TargetApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080012560 @Override
Junyu Laidf210362023-10-24 02:47:50 +000012561 public void setDataSaverEnabled(final boolean enable) {
12562 enforceNetworkStackOrSettingsPermission();
12563 try {
12564 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
12565 if (!ret) {
12566 throw new IllegalStateException("Error when changing iptables: " + enable);
12567 }
12568 } catch (RemoteException e) {
12569 // Lack of permission or binder errors.
12570 throw new IllegalStateException(e);
12571 }
Ken Chen24330172023-10-20 13:02:14 +080012572
12573 try {
12574 mBpfNetMaps.setDataSaverEnabled(enable);
12575 } catch (ServiceSpecificException | UnsupportedOperationException e) {
12576 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
12577 }
Junyu Laidf210362023-10-24 02:47:50 +000012578 }
12579
12580 @Override
markchien738ad912021-12-09 18:15:45 +080012581 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12582 enforceNetworkStackOrSettingsPermission();
12583
12584 try {
12585 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012586 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012587 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012588 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012589 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012590 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012591 throw new IllegalStateException(e);
12592 }
12593 }
12594
12595 @Override
12596 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12597 enforceNetworkStackOrSettingsPermission();
12598
12599 try {
12600 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012601 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012602 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012603 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012604 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012605 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012606 throw new IllegalStateException(e);
12607 }
12608 }
markchiene1561fa2021-12-09 22:00:56 +080012609
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012610 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
12611 throws PackageManager.NameNotFoundException {
12612 final PackageManager pm = mContext.getPackageManager();
12613 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12614 if (appId < Process.FIRST_APPLICATION_UID) {
12615 throw new RuntimeException("Can't set package firewall rule for system app "
12616 + packageName + " with appId " + appId);
12617 }
12618 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
12619 final int uid = uh.getUid(appId);
12620 setUidFirewallRule(chain, uid, rule);
12621 }
12622 return appId;
12623 }
12624
markchiene1561fa2021-12-09 22:00:56 +080012625 @Override
markchien3c04e662022-03-22 16:29:56 +080012626 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012627 enforceNetworkStackOrSettingsPermission();
12628
markchien3c04e662022-03-22 16:29:56 +080012629 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12630 int firewallRule = getFirewallRuleType(chain, rule);
12631
12632 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12633 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12634 }
12635
markchiene1561fa2021-12-09 22:00:56 +080012636 try {
markchien3c04e662022-03-22 16:29:56 +080012637 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012638 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012639 throw new IllegalStateException(e);
12640 }
12641 }
markchien98a6f952022-01-13 23:43:53 +080012642
Chalard Jeanc8fefb32023-09-05 21:41:13 +090012643 private int getPackageFirewallRule(final int chain, final String packageName)
12644 throws PackageManager.NameNotFoundException {
12645 final PackageManager pm = mContext.getPackageManager();
12646 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
12647 return getUidFirewallRule(chain, appId);
12648 }
12649
Motomu Utsumi900b8062023-01-19 16:16:49 +090012650 @Override
12651 public int getUidFirewallRule(final int chain, final int uid) {
12652 enforceNetworkStackOrSettingsPermission();
12653 return mBpfNetMaps.getUidRule(chain, uid);
12654 }
12655
markchien3c04e662022-03-22 16:29:56 +080012656 private int getFirewallRuleType(int chain, int rule) {
12657 final int defaultRule;
12658 switch (chain) {
12659 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012660 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12661 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012662 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012663 defaultRule = FIREWALL_RULE_ALLOW;
12664 break;
12665 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12666 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12667 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12668 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12669 defaultRule = FIREWALL_RULE_DENY;
12670 break;
12671 default:
12672 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12673 }
12674 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12675
12676 return rule;
12677 }
12678
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012679 private void closeSocketsForFirewallChainLocked(final int chain)
12680 throws ErrnoException, SocketException, InterruptedIOException {
12681 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12682 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12683 // So, close all non-system socket owned by uids that are not explicitly allowed
12684 Set<Range<Integer>> ranges = new ArraySet<>();
12685 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12686 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12687 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12688 } else {
12689 // Denylist means the firewall allows all by default, uids must be explicitly denied
12690 // So, close socket owned by uids that are explicitly denied
12691 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12692 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12693 }
12694 }
12695
markchien98a6f952022-01-13 23:43:53 +080012696 @Override
12697 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12698 enforceNetworkStackOrSettingsPermission();
12699
12700 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012701 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012702 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012703 throw new IllegalStateException(e);
12704 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012705
Chalard Jeandf29a852023-05-29 17:02:43 +090012706 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012707 try {
12708 closeSocketsForFirewallChainLocked(chain);
12709 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12710 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12711 }
12712 }
markchien98a6f952022-01-13 23:43:53 +080012713 }
12714
markchien00a0bed2022-01-13 23:46:13 +080012715 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012716 public boolean getFirewallChainEnabled(final int chain) {
12717 enforceNetworkStackOrSettingsPermission();
12718
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012719 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012720 }
12721
12722 @Override
markchien00a0bed2022-01-13 23:46:13 +080012723 public void replaceFirewallChain(final int chain, final int[] uids) {
12724 enforceNetworkStackOrSettingsPermission();
12725
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012726 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012727 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012728
12729 @Override
12730 public IBinder getCompanionDeviceManagerProxyService() {
12731 enforceNetworkStackPermission(mContext);
12732 return mCdmps;
12733 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090012734
12735 @Override
12736 public IBinder getRoutingCoordinatorService() {
12737 enforceNetworkStackPermission(mContext);
12738 return mRoutingCoordinatorService;
12739 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012740}