blob: 8ec979a2411d9db4aee7b3854cf158c34df4e13d [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;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090020import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
21import static android.content.pm.PackageManager.FEATURE_WATCH;
22import static android.content.pm.PackageManager.FEATURE_WIFI;
23import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090024import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090025import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
26import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
28import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090033import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
34import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000035import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070036import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080037import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
38import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
39import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090040import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090041import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090042import static android.net.ConnectivityManager.TYPE_MOBILE;
43import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
44import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
45import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
46import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
47import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
48import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
49import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
50import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
51import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070052import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090053import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070054import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090055import static android.net.ConnectivityManager.TYPE_WIFI;
56import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070057import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070058import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080059import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080060import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080061import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070062import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080063import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040064import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090065import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090066import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090067import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
70import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060071import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080075import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
76import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080077import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090078import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080079import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
80import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080081import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
82import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
83import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090084import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090085import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060086import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070087import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080088import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090089import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070090import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
91import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070092import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080093import static android.os.Process.VPN_UID;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090094import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Patrick Rohr2857ac42022-01-21 14:58:16 +010095import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070096import static android.system.OsConstants.IPPROTO_TCP;
97import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060098
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090099import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
Xiao Ma60142372022-07-16 17:30:20 +0900100import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
paulhu3ffffe72021-09-16 10:15:22 +0800101import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
102import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
103import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900104
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800105import static java.util.Map.Entry;
106
Chalard Jean5b639762020-03-09 21:25:37 +0900107import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000108import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800109import android.annotation.Nullable;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800110import android.annotation.TargetApi;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800111import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800112import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700113import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700114import android.app.admin.DevicePolicyManager;
junyulaie7c7d2a2021-01-26 15:29:15 +0800115import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700116import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800117import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700121import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800122import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700123import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900124import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900125import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700126import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800127import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800128import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800129import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900130import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800131import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900132import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900133import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800134import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900135import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800136import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700137import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900138import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800139import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800140import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800141import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800142import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800143import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900144import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900145import android.net.INetworkMonitor;
146import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900147import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900148import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700149import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800150import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900151import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900152import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900153import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800154import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100155import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800156import android.net.NativeNetworkConfig;
157import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800158import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700159import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700160import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900161import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700162import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800163import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700164import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900165import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900166import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000167import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900168import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700169import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900170import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700171import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900172import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700173import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800174import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900175import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700176import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000177import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800178import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900179import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800180import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400181import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700182import android.net.QosCallbackException;
183import android.net.QosFilter;
184import android.net.QosSocketFilter;
185import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700186import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800187import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800188import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800189import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900190import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400191import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800192import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800193import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400194import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800195import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900196import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900197import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900198import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800199import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900200import android.net.networkstack.ModuleNetworkStackClient;
201import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900202import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800203import android.net.resolv.aidl.DnsHealthEventParcel;
204import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
205import android.net.resolv.aidl.Nat64PrefixEventParcel;
206import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900207import android.net.shared.PrivateDnsConfig;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900208import android.net.util.MultinetworkPolicyTracker;
he_won.hwang881307a2022-03-15 21:23:52 +0900209import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800210import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800211import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800212import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700213import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700215import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700216import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800217import android.os.Looper;
218import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700219import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700220import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900221import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800222import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700223import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700224import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800225import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700226import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900227import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900228import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700229import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700230import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400231import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900233import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700234import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700235import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700236import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800237import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900238import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000239import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600240import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900241import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700242import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700243import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800244
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900245import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400246import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400247import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700248import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900249import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800250import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900251import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800252import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900253import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900254import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100255import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900256import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
257import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900258import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800259import com.android.net.module.util.NetworkCapabilitiesUtils;
Junyu Lai00d92df2022-07-05 11:01:52 +0800260import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800261import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100262import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000263import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900264import com.android.server.connectivity.AutodestructReference;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800265import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800266import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900267import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900268import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500269import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700270import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900271import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900272import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100273import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700274import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700275import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600276import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900277import com.android.server.connectivity.NetworkNotificationManager;
278import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900279import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900280import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700281import com.android.server.connectivity.PermissionMonitor;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800282import com.android.server.connectivity.ProfileNetworkPreferenceList;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900283import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700284import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800285import com.android.server.connectivity.UidRangeUtils;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600286
Josh Gao461a1222020-06-16 15:58:11 -0700287import libcore.io.IoUtils;
288
The Android Open Source Project28527d22009-03-03 19:31:44 -0800289import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100290import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800291import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900292import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700293import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700294import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900295import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700296import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700297import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700298import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700299import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800300import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900301import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800302import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700303import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700304import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700305import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700306import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900307import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700308import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900309import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600310import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900311import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600312import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900313import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800314
315/**
316 * @hide
317 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800318public class ConnectivityService extends IConnectivityManager.Stub
319 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900320 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800321
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900322 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900323 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900324 private static final String NETWORK_ARG = "networks";
325 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800326 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900327
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900328 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900329 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
330 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800331
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900332 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700333
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100334 /**
335 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
336 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800337 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100338 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
339 * (preferably via runtime resource overlays).
340 */
341 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
342 "http://connectivitycheck.gstatic.com/generate_204";
343
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700344 // TODO: create better separation between radio types and network types
345
Robert Greenwalt2034b912009-08-12 16:08:25 -0700346 // how long to wait before switching back to a radio's default network
347 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
348 // system property that can override the above value
349 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
350 "android.telephony.apn-restore";
351
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900352 // How long to wait before putting up a "This network doesn't have an Internet connection,
353 // connect anyway?" dialog after the user selects a network that doesn't validate.
354 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
355
junyulai0ac374f2020-12-14 18:41:52 +0800356 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900357 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
358 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800359 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700360
he_won.hwang881307a2022-03-15 21:23:52 +0900361 // The maximum value for the blocking validation result, in milliseconds.
362 public static final int MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS = 10000;
363
Daniel Brightf9e945b2020-06-15 16:10:01 -0700364 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900365 @VisibleForTesting
366 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700367
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900368 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700369 @VisibleForTesting
370 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900371
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900372 @VisibleForTesting
373 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800374 @VisibleForTesting
375 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900376 // True if the cell radio of the device is capable of time-sharing.
377 @VisibleForTesting
378 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900379
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800380 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800381 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800382 private final int mReleasePendingIntentDelayMs;
383
Chalard Jean46bfbf02022-02-02 00:56:25 +0900384 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900385
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000386 @VisibleForTesting
387 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700388
Chalard Jean9473c982021-07-29 20:03:04 +0900389 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800390 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700391 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800392 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700393
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900394 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700395
junyulaif2c67e42018-08-07 19:50:45 +0800396 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000397 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
398 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800399 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900400 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800401
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900402 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900403 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000404 // The Context is created for UserHandle.ALL.
405 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900406 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900407 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700408 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700409 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800410
Chenbo Feng15416292018-11-08 17:36:21 -0800411 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800412 protected IDnsResolver mDnsResolver;
413 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800414 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700415 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900416 private final NetworkStatsManager mStatsManager;
417 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800418 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700419
Benedict Wong493e04b2018-11-09 14:45:34 -0800420 /**
421 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
422 * instances.
423 */
424 @GuardedBy("mTNSLock")
425 private TestNetworkService mTNS;
426
427 private final Object mTNSLock = new Object();
428
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700429 private String mCurrentTcpBufferSizes;
430
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900431 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800432 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900433
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500434 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400435 // Tear down networks that have no chance (e.g. even if validated) of becoming
436 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500437 // all networks have been rematched against all NetworkRequests.
438 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400439 // Don't reap networks. This should be passed when some networks have not yet been
440 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500441 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900442 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500443
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900444 private enum UnneededFor {
445 LINGER, // Determine whether this network is unneeded and should be lingered.
446 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
447 }
448
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700449 /**
paulhuaa0743d2021-05-26 21:56:03 +0800450 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800451 * should have priority. The order is passed to netd which will use it together
452 * with UID ranges to generate the corresponding IP rule. This serves to
453 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800454 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800455 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000456 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800457 *
paulhu48291862021-07-14 14:53:57 +0800458 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
459 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800460 */
paulhu48291862021-07-14 14:53:57 +0800461 // Used when sending to netd to code for "no order".
462 static final int PREFERENCE_ORDER_NONE = 0;
463 // Order for requests that don't code for a per-app preference. As it is
464 // out of the valid range, the corresponding order should be
465 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800466 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800467 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800468 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800469 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
470 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800471 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800472 static final int PREFERENCE_ORDER_OEM = 10;
473 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800474 // See {@link #setProfileNetworkPreference}.
475 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800476 static final int PREFERENCE_ORDER_PROFILE = 20;
477 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800478 // better scores are connected.
479 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800480 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800481 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900482 // Preference order that signifies the network shouldn't be set as a default network for
483 // the UIDs, only give them access to it. TODO : replace this with a boolean
484 // in NativeUidRangeConfig
485 @VisibleForTesting
486 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
487 // Bound for the lowest valid preference order.
488 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800489
490 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700491 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700492 * from one net to another. Clear happens when we get a new
493 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
494 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700495 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700496 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700497
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700498 /**
499 * used internally to reload global proxy settings
500 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700501 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700502
Robert Greenwalt34848c02011-03-25 13:09:25 -0700503 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400504 * PAC manager has received new port.
505 */
506 private static final int EVENT_PROXY_HAS_CHANGED = 16;
507
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700508 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900509 * used internally when registering NetworkProviders
510 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700511 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900512 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700513
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700514 /**
515 * used internally when registering NetworkAgents
516 * obj = Messenger
517 */
518 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
519
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700520 /**
521 * used to add a network request
522 * includes a NetworkRequestInfo
523 */
524 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
525
526 /**
527 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900528 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700529 * cancel it.
530 * includes a NetworkRequestInfo
531 */
532 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
533
534 /**
535 * used to add a network listener - no request
536 * includes a NetworkRequestInfo
537 */
538 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
539
540 /**
541 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400542 * arg1 = UID of caller
543 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700544 */
545 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
546
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700547 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900548 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700549 * obj = Messenger
550 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900551 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700552
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700553 /**
554 * used internally to expire a wakelock when transitioning
555 * from one net to another. Expire happens when we fail to find
556 * a new network (typically after 1 minute) -
557 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
558 * a replacement network.
559 */
560 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
561
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700562 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800563 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400564 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800565 */
566 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
567
568 /**
569 * used to remove a pending intent and its associated network request.
570 * arg1 = UID of caller
571 * obj = PendingIntent
572 */
573 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
574
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900575 /**
576 * used to specify whether a network should be used even if unvalidated.
577 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
578 * arg2 = whether to remember this choice in the future (1 or 0)
579 * obj = network
580 */
581 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
582
583 /**
584 * used to ask the user to confirm a connection to an unvalidated network.
585 * obj = network
586 */
587 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700588
Erik Kline05f2b402015-04-30 12:58:40 +0900589 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700590 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900591 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700592 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900593
Paul Jensenc8873fc2015-06-17 14:15:39 -0400594 /**
595 * used to add a network listener with a pending intent
596 * obj = NetworkRequestInfo
597 */
598 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
599
Hugo Benichid6b510a2017-04-06 17:22:18 +0900600 /**
601 * used to specify whether a network should not be penalized when it becomes unvalidated.
602 */
603 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
604
605 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700606 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900607 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700608 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900609
Erik Kline31b4a9e2018-01-11 21:07:29 +0900610 // Handle changes in Private DNS settings.
611 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
612
dalyk1720e542018-03-05 12:42:22 -0500613 // Handle private DNS validation status updates.
614 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
615
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900616 /**
617 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
618 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800619 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
620 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
621 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900622 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900623 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900624
625 /**
626 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
627 * config was resolved.
628 * obj = PrivateDnsConfig
629 * arg2 = netid
630 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900631 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900632
633 /**
634 * Request ConnectivityService display provisioning notification.
635 * arg1 = Whether to make the notification visible.
636 * arg2 = NetID.
637 * obj = Intent to be launched when notification selected by user, null if !arg1.
638 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900639 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900640
641 /**
lucaslin2240ef62019-03-12 13:08:03 +0800642 * Used to specify whether a network should be used even if connectivity is partial.
643 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
644 * false)
645 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
646 * obj = network
647 */
lucaslin444d43a2020-02-20 16:56:59 +0800648 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800649
650 /**
lucasline117e2e2019-10-22 18:27:33 +0800651 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
652 * Both of the arguments are bitmasks, and the value of bits come from
653 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900654 * arg1 = unused
655 * arg2 = netId
656 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800657 */
lucaslin444d43a2020-02-20 16:56:59 +0800658 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800659
660 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900661 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
662 * arg1 = unused
663 * arg2 = netId
664 * obj = captive portal data
665 */
lucaslin444d43a2020-02-20 16:56:59 +0800666 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900667
668 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900669 * Used by setRequireVpnForUids.
670 * arg1 = whether the specified UID ranges are required to use a VPN.
671 * obj = Array of UidRange objects.
672 */
673 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
674
675 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900676 * Used internally when setting the default networks for OemNetworkPreferences.
677 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800678 */
679 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
680
681 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800682 * Used to indicate the system default network becomes active.
683 */
684 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
685
686 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900687 * Used internally when setting a network preference for a user profile.
688 * obj = Pair<ProfileNetworkPreference, Listener>
689 */
690 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
691
692 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000693 * Event to specify that reasons for why an uid is blocked changed.
694 * arg1 = uid
695 * arg2 = blockedReasons
696 */
697 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
698
699 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900700 * Event to register a new network offer
701 * obj = NetworkOffer
702 */
703 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
704
705 /**
706 * Event to unregister an existing network offer
707 * obj = INetworkOfferCallback
708 */
709 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
710
711 /**
paulhu51f77dc2021-06-07 02:34:20 +0000712 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
713 */
714 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
715
716 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800717 * Event to set temporary allow bad wifi within a limited time to override
718 * {@code config_networkAvoidBadWifi}.
719 */
720 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
721
722 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100723 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
724 */
725 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
726
727 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900728 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
729 * should be shown.
730 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900731 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900732
733 /**
734 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
735 * should be hidden.
736 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900737 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900738
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800739 /**
740 * The maximum alive time to allow bad wifi configuration for testing.
741 */
742 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
743
Patrick Rohr2857ac42022-01-21 14:58:16 +0100744 /**
745 * The priority of the tc police rate limiter -- smaller value is higher priority.
746 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
747 */
748 private static final short TC_PRIO_POLICE = 1;
749
750 /**
751 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
752 */
753 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700754 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100755
Hugo Benichi47011212017-03-30 10:46:05 +0900756 private static String eventName(int what) {
757 return sMagicDecoderRing.get(what, Integer.toString(what));
758 }
759
paulhua10d8212020-11-10 15:32:56 +0800760 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900761 final DnsResolverServiceManager dsm = context.getSystemService(
762 DnsResolverServiceManager.class);
763 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800764 }
765
Cody Kesting73708bf2019-12-18 10:57:50 -0800766 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900767 @VisibleForTesting
768 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700769 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700770 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700771 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700772 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800773 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
774 @VisibleForTesting
775 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
776
Erik Kline32120082017-12-13 19:40:49 +0900777 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900778 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700779
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400780 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800781 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400782
Chalard Jean46bfbf02022-02-02 00:56:25 +0900783 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800784 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700785
Chalard Jean5d70ba42018-06-07 16:44:04 +0900786 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
787 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000788 @VisibleForTesting
789 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400790
Erik Kline05f2b402015-04-30 12:58:40 +0900791 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700792
Chalard Jean46bfbf02022-02-02 00:56:25 +0900793 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400794
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700795 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900796 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700797
Valentin Iftime9fa35092019-09-24 13:32:13 +0200798 private Set<String> mWolSupportedInterfaces;
799
Roshan Pius08c94fb2020-01-16 12:17:17 -0800800 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800801 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800802 private final AppOpsManager mAppOpsManager;
803
804 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400805
Chalard Jean46bfbf02022-02-02 00:56:25 +0900806 private final KeepaliveTracker mKeepaliveTracker;
807 private final QosCallbackTracker mQosCallbackTracker;
808 private final NetworkNotificationManager mNotifier;
809 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900810
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700811 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800812 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700813
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900814 // Sequence number for NetworkProvider IDs.
815 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
816 NetworkProvider.FIRST_PROVIDER_ID);
817
Erik Klineedf878b2015-07-09 18:24:03 +0900818 // NetworkRequest activity String log entries.
819 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
820 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
821
Hugo Benichid159fdd2016-07-11 11:05:12 +0900822 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900823 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900824 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
825
Hugo Benichi47011212017-03-30 10:46:05 +0900826 private static final int MAX_WAKELOCK_LOGS = 20;
827 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900828 private int mTotalWakelockAcquisitions = 0;
829 private int mTotalWakelockReleases = 0;
830 private long mTotalWakelockDurationMs = 0;
831 private long mMaxWakelockDurationMs = 0;
832 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900833
Hugo Benichi208c0102016-07-28 17:53:06 +0900834 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900835
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700836 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900837 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700838
Erik Kline95ecfee2016-10-02 18:02:14 +0900839 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900840 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900841
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900842 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800843 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
844 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800845
Patrick Rohr2857ac42022-01-21 14:58:16 +0100846 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
847 // configured via {@link
848 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
849 // Only the handler thread is allowed to access this field.
850 private long mIngressRateLimit = -1;
851
Robert Greenwalt802c1102014-06-02 15:32:02 -0700852 /**
853 * Implements support for the legacy "one network per network type" model.
854 *
855 * We used to have a static array of NetworkStateTrackers, one for each
856 * network type, but that doesn't work any more now that we can have,
857 * for example, more that one wifi network. This class stores all the
858 * NetworkAgentInfo objects that support a given type, but the legacy
859 * API will only see the first one.
860 *
861 * It serves two main purposes:
862 *
863 * 1. Provide information about "the network for a given type" (since this
864 * API only supports one).
865 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
866 * the first network for a given type changes, or if the default network
867 * changes.
868 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900869 @VisibleForTesting
870 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900871
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900872 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900873 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900874
Robert Greenwalt802c1102014-06-02 15:32:02 -0700875 /**
876 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
877 * Each list holds references to all NetworkAgentInfos that are used to
878 * satisfy requests for that network type.
879 *
880 * This array is built out at startup such that an unsupported network
881 * doesn't get an ArrayList instance, making this a tristate:
882 * unsupported, supported but not active and active.
883 *
884 * The actual lists are populated when we scan the network types that
885 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900886 *
887 * Threading model:
888 * - addSupportedType() is only called in the constructor
889 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
890 * They are therefore not thread-safe with respect to each other.
891 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
892 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900893 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900894 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700895 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900896 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900897 @NonNull
898 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700899
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900900 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
901 // an entry have no timer (equivalent to -1). Lazily loaded.
902 @NonNull
903 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
904
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900905 LegacyTypeTracker(@NonNull ConnectivityService service) {
906 mService = service;
907 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700908 }
909
Chiachang Wang3bc52762021-11-25 14:17:57 +0800910 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
911 // addressed.
912 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900913 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
914 final PackageManager pm = ctx.getPackageManager();
915 if (pm.hasSystemFeature(FEATURE_WIFI)) {
916 addSupportedType(TYPE_WIFI);
917 }
918 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
919 addSupportedType(TYPE_WIFI_P2P);
920 }
921 if (tm.isDataCapable()) {
922 // Telephony does not have granular support for these types: they are either all
923 // supported, or none is supported
924 addSupportedType(TYPE_MOBILE);
925 addSupportedType(TYPE_MOBILE_MMS);
926 addSupportedType(TYPE_MOBILE_SUPL);
927 addSupportedType(TYPE_MOBILE_DUN);
928 addSupportedType(TYPE_MOBILE_HIPRI);
929 addSupportedType(TYPE_MOBILE_FOTA);
930 addSupportedType(TYPE_MOBILE_IMS);
931 addSupportedType(TYPE_MOBILE_CBS);
932 addSupportedType(TYPE_MOBILE_IA);
933 addSupportedType(TYPE_MOBILE_EMERGENCY);
934 }
935 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
936 addSupportedType(TYPE_BLUETOOTH);
937 }
938 if (pm.hasSystemFeature(FEATURE_WATCH)) {
939 // TYPE_PROXY is only used on Wear
940 addSupportedType(TYPE_PROXY);
941 }
942 // Ethernet is often not specified in the configs, although many devices can use it via
943 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +0000944 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900945 addSupportedType(TYPE_ETHERNET);
946 }
947
948 // Always add TYPE_VPN as a supported type
949 addSupportedType(TYPE_VPN);
950 }
951
952 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700953 if (mTypeLists[type] != null) {
954 throw new IllegalStateException(
955 "legacy list for type " + type + "already initialized");
956 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900957 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700958 }
959
Robert Greenwalt802c1102014-06-02 15:32:02 -0700960 public boolean isTypeSupported(int type) {
961 return isNetworkTypeValid(type) && mTypeLists[type] != null;
962 }
963
964 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900965 synchronized (mTypeLists) {
966 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
967 return mTypeLists[type].get(0);
968 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700969 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900970 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700971 }
972
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900973 public int getRestoreTimerForType(int type) {
974 synchronized (mTypeLists) {
975 if (mRestoreTimers == null) {
976 mRestoreTimers = loadRestoreTimers();
977 }
978 return mRestoreTimers.getOrDefault(type, -1);
979 }
980 }
981
982 private ArrayMap<Integer, Integer> loadRestoreTimers() {
983 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900984 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900985 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
986 for (final String config : configs) {
987 final String[] splits = TextUtils.split(config, ",");
988 if (splits.length != 2) {
989 logwtf("Invalid restore timer token count: " + config);
990 continue;
991 }
992 try {
993 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
994 } catch (NumberFormatException e) {
995 logwtf("Invalid restore timer number format: " + config, e);
996 }
997 }
998 return ret;
999 }
1000
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001001 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001002 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001003 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001004 log("Sending " + state
1005 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001006 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001007 }
1008 }
1009
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001010 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1011 // network type, to preserve previous behaviour.
1012 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1013 if (vpnNai != mService.getLegacyLockdownNai()) return;
1014
1015 if (vpnNai.declaredUnderlyingNetworks == null
1016 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1017 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1018 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1019 return;
1020 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001021 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001022 vpnNai.declaredUnderlyingNetworks[0]);
1023 if (underlyingNai == null) return;
1024
1025 final int type = underlyingNai.networkInfo.getType();
1026 final DetailedState state = DetailedState.CONNECTED;
1027 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1028 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1029 }
1030
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001031 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001032 public void add(int type, NetworkAgentInfo nai) {
1033 if (!isTypeSupported(type)) {
1034 return; // Invalid network type.
1035 }
1036 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1037
1038 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1039 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001040 return;
1041 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001042 synchronized (mTypeLists) {
1043 list.add(nai);
1044 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001045
Chalard Jean5b409c72021-02-04 13:12:59 +09001046 // Send a broadcast if this is the first network of its type or if it's the default.
1047 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001048
1049 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1050 // to preserve previous behaviour.
1051 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001052 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001053 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1054 mService.sendLegacyNetworkBroadcast(nai, state, type);
1055 }
1056
1057 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1058 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001059 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001060 }
1061
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001062 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001063 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001064 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1065 if (list == null || list.isEmpty()) {
1066 return;
1067 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001068 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001069
Hugo Benichi389633f2016-06-21 09:48:07 +09001070 synchronized (mTypeLists) {
1071 if (!list.remove(nai)) {
1072 return;
1073 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001074 }
1075
Lorenzo Colitti49767722015-05-01 00:30:10 +09001076 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001077 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1078 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001079 }
1080
1081 if (!list.isEmpty() && wasFirstNetwork) {
1082 if (DBG) log("Other network available for type " + type +
1083 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001084 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001085 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001086 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001087 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001088 }
1089 }
1090
1091 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001092 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1093 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001094 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001095 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001096 }
1097 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001098
Chalard Jean46bfbf02022-02-02 00:56:25 +09001099 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001100 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001101 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001102 final DetailedState state = nai.networkInfo.getDetailedState();
1103 for (int type = 0; type < mTypeLists.length; type++) {
1104 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001105 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001106 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001107 if (isFirst || contains && isDefault) {
1108 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001109 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001110 }
1111 }
1112 }
1113
Robert Greenwalt94e22142014-07-30 16:31:24 -07001114 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001115 pw.println("mLegacyTypeTracker:");
1116 pw.increaseIndent();
1117 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001118 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001119 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001120 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001121 pw.println();
1122 pw.println("Current state:");
1123 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001124 synchronized (mTypeLists) {
1125 for (int type = 0; type < mTypeLists.length; type++) {
1126 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1127 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001128 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001129 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001130 }
1131 }
1132 pw.decreaseIndent();
1133 pw.decreaseIndent();
1134 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001135 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001136 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001137 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001138
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001139 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001140 /**
1141 * Helper class which parses out priority arguments and dumps sections according to their
1142 * priority. If priority arguments are omitted, function calls the legacy dump command.
1143 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001144 private class LocalPriorityDump {
1145 private static final String PRIORITY_ARG = "--dump-priority";
1146 private static final String PRIORITY_ARG_HIGH = "HIGH";
1147 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1148
1149 LocalPriorityDump() {}
1150
1151 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1152 doDump(fd, pw, new String[] {DIAG_ARG});
1153 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001154 }
1155
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001156 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1157 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001158 }
1159
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001160 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1161 if (args == null) {
1162 dumpNormal(fd, pw, args);
1163 return;
1164 }
1165
1166 String priority = null;
1167 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1168 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1169 argIndex++;
1170 priority = args[argIndex];
1171 }
1172 }
1173
1174 if (PRIORITY_ARG_HIGH.equals(priority)) {
1175 dumpHigh(fd, pw);
1176 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1177 dumpNormal(fd, pw, args);
1178 } else {
1179 // ConnectivityService publishes binder service using publishBinderService() with
1180 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001181 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1182 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001183 // TODO: Integrate into signal dump.
1184 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001185 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001186 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001187 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001188
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001189 /**
1190 * Dependencies of ConnectivityService, for injection in tests.
1191 */
1192 @VisibleForTesting
1193 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001194 public int getCallingUid() {
1195 return Binder.getCallingUid();
1196 }
1197
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001198 /**
1199 * Get system properties to use in ConnectivityService.
1200 */
1201 public MockableSystemProperties getSystemProperties() {
1202 return new MockableSystemProperties();
1203 }
1204
1205 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001206 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1207 */
1208 public ConnectivityResources getResources(@NonNull Context ctx) {
1209 return new ConnectivityResources(ctx);
1210 }
1211
1212 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001213 * Create a HandlerThread to use in ConnectivityService.
1214 */
1215 public HandlerThread makeHandlerThread() {
1216 return new HandlerThread("ConnectivityServiceThread");
1217 }
1218
1219 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001220 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001221 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001222 public NetworkStackClientBase getNetworkStack() {
1223 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001224 }
1225
1226 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001227 * @see ProxyTracker
1228 */
1229 public ProxyTracker makeProxyTracker(@NonNull Context context,
1230 @NonNull Handler connServiceHandler) {
1231 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1232 }
1233
1234 /**
1235 * @see NetIdManager
1236 */
1237 public NetIdManager makeNetIdManager() {
1238 return new NetIdManager();
1239 }
1240
1241 /**
1242 * @see NetworkUtils#queryUserAccess(int, int)
1243 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001244 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1245 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001246 }
1247
1248 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001249 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1250 * requires CAP_NET_ADMIN, which the unit tests do not have.
1251 */
1252 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1253 InetSocketAddress remote) {
1254 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1255 }
1256
1257 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001258 * @see MultinetworkPolicyTracker
1259 */
1260 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1261 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1262 return new MultinetworkPolicyTracker(c, h, r);
1263 }
1264
Aaron Huang330a4c02020-10-27 03:36:19 +08001265 /**
1266 * @see BatteryStatsManager
1267 */
1268 public void reportNetworkInterfaceForTransports(Context context, String iface,
1269 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001270 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001271 context.getSystemService(BatteryStatsManager.class);
1272 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1273 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001274
1275 public boolean getCellular464XlatEnabled() {
1276 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1277 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001278
1279 /**
1280 * @see PendingIntent#intentFilterEquals
1281 */
1282 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1283 return a.intentFilterEquals(b);
1284 }
1285
1286 /**
1287 * @see LocationPermissionChecker
1288 */
1289 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1290 return new LocationPermissionChecker(context);
1291 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001292
1293 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001294 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001295 *
1296 * This method returns null in versions before T, where carrier privilege
1297 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001298 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001299 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001300 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1301 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1302 if (SdkLevel.isAtLeastT()) {
1303 return new CarrierPrivilegeAuthenticator(context, tm);
1304 } else {
1305 return null;
1306 }
1307 }
1308
1309 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001310 * @see DeviceConfigUtils#isFeatureEnabled
1311 */
1312 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1313 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1314 TETHERING_MODULE_NAME, defaultEnabled);
1315 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001316
1317 /**
1318 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001319 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001320 * @return BpfNetMaps implementation.
1321 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001322 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1323 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001324 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001325
1326 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001327 * @see ClatCoordinator
1328 */
1329 public ClatCoordinator getClatCoordinator(INetd netd) {
1330 return new ClatCoordinator(
1331 new ClatCoordinator.Dependencies() {
1332 @NonNull
1333 public INetd getNetd() {
1334 return netd;
1335 }
1336 });
1337 }
1338
1339 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001340 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1341 */
1342 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1343 final InterfaceParams params = InterfaceParams.getByName(iface);
1344 if (params == null) {
1345 // the interface might have disappeared.
1346 logw("Failed to get interface params for interface " + iface);
1347 return;
1348 }
1349 try {
1350 // converting rateInBytesPerSecond from long to int is safe here because the
1351 // setting's range is limited to INT_MAX.
1352 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001353 Log.i(TAG,
1354 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001355 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1356 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1357 } catch (IOException e) {
1358 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1359 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1360 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1361 + ") failure: ", e);
1362 }
1363 }
1364
1365 /**
1366 * Wraps {@link TcUtils#tcFilterDelDev}
1367 */
1368 public void disableIngressRateLimit(String iface) {
1369 final InterfaceParams params = InterfaceParams.getByName(iface);
1370 if (params == null) {
1371 // the interface might have disappeared.
1372 logw("Failed to get interface params for interface " + iface);
1373 return;
1374 }
1375 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001376 Log.i(TAG,
1377 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001378 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1379 } catch (IOException e) {
1380 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1381 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1382 }
1383 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001384 }
1385
junyulaie7c7d2a2021-01-26 15:29:15 +08001386 public ConnectivityService(Context context) {
1387 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001388 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1389 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001390 }
1391
1392 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001393 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1394 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001395 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001396
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001397 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001398 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001399 mSystemProperties = mDeps.getSystemProperties();
1400 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001401 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001402 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001403 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1404 // Pass limit - 1 to maintain backward compatibility.
1405 // TODO: Remove the workaround.
1406 mNetworkRequestCounter =
1407 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1408 mSystemNetworkRequestCounter =
1409 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001410
Hugo Benichi208c0102016-07-28 17:53:06 +09001411 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001412 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001413 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1414 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001415 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001416 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001417 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001418 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1419 mDefaultNetworkRequests.add(mDefaultRequest);
1420 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001421
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001422 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001423 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001424
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001425 // The default WiFi request is a background request so that apps using WiFi are
1426 // migrated to a better network (typically ethernet) when one comes up, instead
1427 // of staying on WiFi forever.
1428 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1429 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1430
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001431 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1432 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1433 NetworkRequest.Type.BACKGROUND_REQUEST);
1434
Chalard Jean0702f982021-09-16 21:50:07 +09001435 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1436 // TODO: Consider making the timer customizable.
1437 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1438 mCellularRadioTimesharingCapable =
1439 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1440
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001441 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001442 mHandlerThread.start();
1443 mHandler = new InternalHandler(mHandlerThread.getLooper());
1444 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001445 mConnectivityDiagnosticsHandler =
1446 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001447
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001448 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001449 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001450
junyulaie7c7d2a2021-01-26 15:29:15 +08001451 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001452 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001453 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001454 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001455
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001456 mNetd = netd;
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001457 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Wink Saville32506bc2013-06-29 21:10:57 -07001458 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001459 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001460 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001461 mCarrierPrivilegeAuthenticator =
1462 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001463
Sudheer Shanka9967d462021-03-18 19:09:25 +00001464 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001465 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1466 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001467 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001468
1469 final PowerManager powerManager = (PowerManager) context.getSystemService(
1470 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001471 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001472 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001473
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001474 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1475 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001476 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001477 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001478 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001479 mProtectedNetworks.add(p);
1480 } else {
1481 if (DBG) loge("Ignoring protectedNetwork " + p);
1482 }
1483 }
1484
soma, kawata29444ae2019-05-23 09:30:40 +09001485 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1486
Wayne Ma2fde98c2022-01-17 18:04:05 +08001487 mPermissionMonitor = new PermissionMonitor(mContext, mNetd, mBpfNetMaps);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001488
James Mattis02220e22021-03-13 19:27:21 -08001489 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001490 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001491 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001492 final IntentFilter userIntentFilter = new IntentFilter();
1493 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1494 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1495 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1496 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001497
James Mattis02220e22021-03-13 19:27:21 -08001498 // Listen to package add/removes for netd
1499 final IntentFilter packageIntentFilter = new IntentFilter();
1500 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1501 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1502 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1503 packageIntentFilter.addDataScheme("package");
1504 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001505 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001506
lucaslind5c2d072021-02-20 18:59:47 +08001507 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001508
Chalard Jean46bfbf02022-02-02 00:56:25 +09001509 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001510 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001511 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001512 } catch (RemoteException | ServiceSpecificException e) {
1513 loge("Error registering event listener :" + e);
1514 }
1515
Erik Kline05f2b402015-04-30 12:58:40 +09001516 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1517 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001518
junyulai7e06ad42019-03-04 22:45:36 +08001519 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001520 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001521 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001522
1523 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001524 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001525 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1526 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001527 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001528 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1529 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001530
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001531 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001532 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001533 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001534
Chiachang Wangc1215d32020-10-20 15:38:58 +08001535 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001536 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001537
Chalard Jean28018572020-12-21 18:36:52 +09001538 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1539 // request that doesn't allow fallback to the default network. It should never be visible
1540 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1541 // arguments like the handler or the DnsResolver.
1542 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001543 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001544 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001545 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001546 new LinkProperties(), new NetworkCapabilities(),
1547 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001548 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1549 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001550
1551 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001552 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1553 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1554 // Even if it could, running on S would at least require mocking out the BPF map,
1555 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1556 // the bpf syscall. http://aosp/1907693
1557 if (SdkLevel.isAtLeastT()) {
1558 mDscpPolicyTracker = new DscpPolicyTracker();
1559 }
Tyler Wear72388212021-09-09 14:49:02 -07001560 } catch (ErrnoException e) {
1561 loge("Unable to create DscpPolicyTracker");
1562 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001563
1564 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1565 mContext);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001566 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001567
Xiao Ma0a171c02022-01-23 16:14:51 +00001568 /**
1569 * Check whether or not the device supports Ethernet transport.
1570 */
1571 public static boolean deviceSupportsEthernet(final Context context) {
1572 final PackageManager pm = context.getPackageManager();
1573 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1574 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1575 }
1576
Chalard Jean46adcf32018-04-18 20:18:38 +09001577 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001578 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1579 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001580 }
1581
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001582 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1583 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001584 final NetworkCapabilities netCap = new NetworkCapabilities();
1585 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001586 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001587 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001588 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001589 return netCap;
1590 }
1591
James Mattis45d81842021-01-10 14:24:24 -08001592 private NetworkRequest createDefaultRequest() {
1593 return createDefaultInternetRequestForTransport(
1594 TYPE_NONE, NetworkRequest.Type.REQUEST);
1595 }
1596
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001597 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001598 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001599 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001600 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001601 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001602 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001603 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001604 netCap.addTransportType(transportType);
1605 }
James Mattis45d81842021-01-10 14:24:24 -08001606 return createNetworkRequest(type, netCap);
1607 }
1608
1609 private NetworkRequest createNetworkRequest(
1610 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001611 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001612 }
1613
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001614 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1615 NetworkRequest.Type type) {
1616 final NetworkCapabilities netCap = new NetworkCapabilities();
1617 netCap.clearAll();
1618 netCap.addCapability(capability);
1619 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1620 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1621 }
1622
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001623 // Used only for testing.
1624 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001625 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001626 // changing ContentResolver to make registerContentObserver non-final).
1627 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1628 // by subclassing SettingsObserver.
1629 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001630 void updateAlwaysOnNetworks() {
1631 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001632 }
1633
Erik Kline9a62f012018-03-21 07:18:33 -07001634 // See FakeSettingsProvider comment above.
1635 @VisibleForTesting
1636 void updatePrivateDnsSettings() {
1637 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1638 }
1639
paulhu51f77dc2021-06-07 02:34:20 +00001640 @VisibleForTesting
1641 void updateMobileDataPreferredUids() {
1642 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1643 }
1644
Patrick Rohr2857ac42022-01-21 14:58:16 +01001645 @VisibleForTesting
1646 void updateIngressRateLimit() {
1647 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1648 }
1649
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001650 private void handleAlwaysOnNetworkRequest(
1651 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001652 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001653 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001654 handleAlwaysOnNetworkRequest(networkRequest, enable);
1655 }
1656
1657 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001658 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001659 if (enable == isEnabled) {
1660 return; // Nothing to do.
1661 }
1662
1663 if (enable) {
1664 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001665 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001666 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001667 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001668 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001669 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1670 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001671 }
1672 }
1673
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001674 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001675 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1676 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1677 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1678 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001679 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1680 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001681 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001682 }
1683
paulhu51f77dc2021-06-07 02:34:20 +00001684 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001685 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001686 private void registerSettingsCallbacks() {
1687 // Watch for global HTTP proxy changes.
1688 mSettingsObserver.observe(
1689 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1690 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1691
Chalard Jean46bfbf02022-02-02 00:56:25 +09001692 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001693 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001694 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001695 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1696
Chalard Jean46bfbf02022-02-02 00:56:25 +09001697 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001698 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001699 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001700 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001701
1702 // Watch for mobile data preferred uids changes.
1703 mSettingsObserver.observe(
1704 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1705 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001706
1707 // Watch for ingress rate limit changes.
1708 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001709 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001710 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1711 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001712 }
1713
Erik Kline31b4a9e2018-01-11 21:07:29 +09001714 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001715 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1716 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001717 }
1718 }
1719
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001720 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001721 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1722 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001723 return mNextNetworkRequestId++;
1724 }
1725
junyulai74f9a8b2018-06-13 15:00:37 +08001726 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001727 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001728 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001729 if (network == null) {
1730 return null;
1731 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001732 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001733 }
1734
1735 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001736 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001737 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001738 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001739 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001740
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001741 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001742 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001743 private NetworkAgentInfo getVpnForUid(int uid) {
1744 synchronized (mNetworkForNetId) {
1745 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1746 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001747 if (nai.isVPN() && nai.everConnected()
1748 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001749 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001750 }
1751 }
1752 }
1753 return null;
1754 }
1755
Chalard Jean46bfbf02022-02-02 00:56:25 +09001756 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001757 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001758 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001759 final NetworkAgentInfo nai = getVpnForUid(uid);
1760 if (nai != null) return nai.declaredUnderlyingNetworks;
1761 return null;
1762 }
1763
Lorenzo Colittia7574052021-01-19 01:33:05 +09001764 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001765 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001766
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001767 final Network[] networks = getVpnUnderlyingNetworks(uid);
1768 if (networks != null) {
1769 // getUnderlyingNetworks() returns:
1770 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1771 // empty array => the VPN explicitly said "no default network".
1772 // non-empty array => the VPN specified one or more default networks; we use the
1773 // first one.
1774 if (networks.length > 0) {
1775 nai = getNetworkAgentInfoForNetwork(networks[0]);
1776 } else {
1777 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001778 }
1779 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001780 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001781 }
1782
1783 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001784 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001785 */
paulhu7aeba372020-12-30 00:42:19 +08001786 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1787 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001788 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001789 if (ignoreBlocked) {
1790 return false;
1791 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001792 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001793 final long ident = Binder.clearCallingIdentity();
1794 try {
1795 final boolean metered = nc == null ? true : nc.isMetered();
1796 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1797 } finally {
1798 Binder.restoreCallingIdentity(ident);
1799 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001800 }
1801
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001802 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001803 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1804 return;
1805 }
Hugo Benichi47011212017-03-30 10:46:05 +09001806 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001807 synchronized (mBlockedAppUids) {
1808 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001809 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001810 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001811 blocked = false;
1812 } else {
1813 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001814 }
1815 }
Hugo Benichi47011212017-03-30 10:46:05 +09001816 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1817 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1818 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001819 }
1820
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001821 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001822 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1823 return;
1824 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001825 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001826 final int requestId = nri.getActiveRequest() != null
1827 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001828 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001829 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001830 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001831 }
1832
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001833 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001834 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001835 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001836 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001837 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001838 @NonNull
1839 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1840 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001841 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1842 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1843 // but only exists if an app asks about them or requests them. Ensure the requesting app
1844 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001845 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001846 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1847 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1848 null /* extraInfo */);
1849 }
1850 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001851 return filtered;
1852 }
1853
1854 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1855 boolean ignoreBlocked) {
1856 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1857 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001858 }
1859
1860 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001861 * Return NetworkInfo for the active (i.e., connected) network interface.
1862 * It is assumed that at most one network is active at a time. If more
1863 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001864 * @return the info for the active network, or {@code null} if none is
1865 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001866 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001867 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001868 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001869 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001870 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001871 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001872 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1873 if (nai == null) return null;
1874 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1875 maybeLogBlockedNetworkInfo(networkInfo, uid);
1876 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001877 }
1878
Paul Jensen1f567382015-02-13 14:18:39 -05001879 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001880 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001881 public Network getActiveNetwork() {
1882 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001883 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001884 }
1885
1886 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001887 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001888 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001889 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001890 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001891 }
1892
Chalard Jean46bfbf02022-02-02 00:56:25 +09001893 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001894 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001895 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1896 if (vpnNai != null) {
1897 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1898 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1899 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001900 }
Paul Jensen1f567382015-02-13 14:18:39 -05001901 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001902
James Mattis2516da32021-01-31 17:06:19 -08001903 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001904 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1905 ignoreBlocked)) {
1906 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001907 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001908 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001909 }
1910
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001911 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001912 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001913 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001914 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001915 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1916 if (nai == null) return null;
1917 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001918 }
1919
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001920 /** Returns a NetworkInfo object for a network that doesn't exist. */
1921 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1922 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1923 getNetworkTypeName(networkType), "" /* subtypeName */);
1924 info.setIsAvailable(true);
1925 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1926 // background data is restricted.
1927 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1928 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1929 ? DetailedState.BLOCKED
1930 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001931 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1932 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001933 return info;
1934 }
1935
Lorenzo Colittia7574052021-01-19 01:33:05 +09001936 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001937 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1938 return null;
1939 }
1940 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001941 if (nai == null) {
1942 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001943 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001944 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1945 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001946 }
1947
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001948 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001949 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001950 public NetworkInfo getNetworkInfo(int networkType) {
1951 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001952 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001953 if (getVpnUnderlyingNetworks(uid) != null) {
1954 // A VPN is active, so we may need to return one of its underlying networks. This
1955 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001956 // getNetworkAgentInfoForUid.
1957 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1958 if (nai == null) return null;
1959 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1960 if (networkInfo.getType() == networkType) {
1961 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001962 }
1963 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001964 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001965 }
1966
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001967 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001968 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001969 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001970 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001971 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001972 if (nai == null) return null;
1973 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001974 }
1975
1976 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001977 public NetworkInfo[] getAllNetworkInfo() {
1978 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001979 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001980 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1981 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001982 NetworkInfo info = getNetworkInfo(networkType);
1983 if (info != null) {
1984 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001985 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001986 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001987 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001988 }
1989
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001990 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001991 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001992 public Network getNetworkForType(int networkType) {
1993 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001994 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1995 return null;
1996 }
1997 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1998 if (nai == null) {
1999 return null;
2000 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002001 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002002 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2003 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002004 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002005 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002006 }
2007
2008 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002009 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002010 public Network[] getAllNetworks() {
2011 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002012 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002013 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002014 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002015 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002016 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002017 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002018 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002019 }
2020
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002021 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002022 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002023 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002024 // The basic principle is: if an app's traffic could possibly go over a
2025 // network, without the app doing anything multinetwork-specific,
2026 // (hence, by "default"), then include that network's capabilities in
2027 // the array.
2028 //
2029 // In the normal case, app traffic only goes over the system's default
2030 // network connection, so that's the only network returned.
2031 //
2032 // With a VPN in force, some app traffic may go into the VPN, and thus
2033 // over whatever underlying networks the VPN specifies, while other app
2034 // traffic may go over the system default network (e.g.: a split-tunnel
2035 // VPN, or an app disallowed by the VPN), so the set of networks
2036 // returned includes the VPN's underlying networks and the system
2037 // default.
2038 enforceAccessPermission();
2039
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002040 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002041
James Mattis2516da32021-01-31 17:06:19 -08002042 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2043 if (!nri.isBeingSatisfied()) {
2044 continue;
2045 }
2046 final NetworkAgentInfo nai = nri.getSatisfier();
2047 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2048 if (null != nc
2049 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2050 && !result.containsKey(nai.network)) {
2051 result.put(
2052 nai.network,
2053 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002054 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002055 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2056 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002057 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002058 }
2059
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002060 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002061 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002062 if (null != networks) {
2063 for (final Network network : networks) {
2064 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2065 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002066 result.put(
2067 network,
2068 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002069 nc,
2070 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002071 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002072 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002073 }
2074 }
2075 }
2076
2077 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2078 out = result.values().toArray(out);
2079 return out;
2080 }
2081
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002082 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002083 public boolean isNetworkSupported(int networkType) {
2084 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002085 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002086 }
2087
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002088 /**
2089 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002090 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002091 * @return the ip properties for the active network, or {@code null} if
2092 * none is active
2093 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002094 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002095 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002096 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002097 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002098 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2099 if (nai == null) return null;
2100 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002101 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002102 }
2103
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002104 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002105 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002106 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002107 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002108 final LinkProperties lp = getLinkProperties(nai);
2109 if (lp == null) return null;
2110 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002111 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002112 }
2113
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002114 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002115 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002116 public LinkProperties getLinkProperties(Network network) {
2117 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002118 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2119 if (lp == null) return null;
2120 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002121 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002122 }
2123
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002124 @Nullable
2125 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002126 if (nai == null) {
2127 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002128 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002129 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002130 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002131 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002132 }
2133
lucaslinc582d502022-01-27 09:07:00 +08002134 @Override
2135 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002136 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002137 @NonNull String packageName, @Nullable String callingAttributionTag) {
2138 Objects.requireNonNull(packageName);
2139 Objects.requireNonNull(lp);
2140 enforceNetworkStackOrSettingsPermission();
2141 if (!checkAccessPermission(-1 /* pid */, uid)) {
2142 return null;
2143 }
2144 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2145 }
2146
Qingxi Lib2748102020-01-08 12:51:49 -08002147 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2148 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2149 }
2150
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002151 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002152 if (nai == null) return null;
2153 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002154 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002155 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002156 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002157 }
2158
2159 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002160 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2161 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002162 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002163 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002164 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002165 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002166 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002167 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002168 }
2169
lucaslinc582d502022-01-27 09:07:00 +08002170 @Override
lucaslind2b06132022-03-02 10:56:57 +08002171 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2172 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2173 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002174 Objects.requireNonNull(nc);
2175 Objects.requireNonNull(packageName);
2176 enforceNetworkStackOrSettingsPermission();
2177 if (!checkAccessPermission(-1 /* pid */, uid)) {
2178 return null;
2179 }
2180 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2181 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2182 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2183 callingAttributionTag);
2184 }
2185
lucaslin69e1aa92022-03-22 18:15:09 +08002186 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2187 if (nc.getUnderlyingNetworks() != null
2188 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2189 nc.setUnderlyingNetworks(null);
2190 }
2191 }
2192
Qingxi Libb8da982020-01-17 17:54:27 -08002193 @VisibleForTesting
2194 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002195 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002196 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2197 // this would be expensive (one more permission check every time any NC callback is
2198 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2199 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2200 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002201 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002202 if (!checkSettingsPermission(callerPid, callerUid)) {
2203 newNc.setUids(null);
2204 newNc.setSSID(null);
2205 }
Etan Cohen107ae952018-12-30 17:59:59 -08002206 if (newNc.getNetworkSpecifier() != null) {
2207 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2208 }
Benedict Wonga5604ea2021-07-09 00:13:45 -07002209 if (!checkAnyPermissionOf(callerPid, callerUid, android.Manifest.permission.NETWORK_STACK,
2210 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2211 newNc.setAdministratorUids(new int[0]);
2212 }
Benedict Wong53de25f2021-03-24 14:01:51 -07002213 if (!checkAnyPermissionOf(
2214 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002215 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002216 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002217 }
lucaslin69e1aa92022-03-22 18:15:09 +08002218 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002219
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002220 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002221 }
2222
Roshan Pius98f59ec2021-02-23 08:47:39 -08002223 /**
2224 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002225 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002226 * NetworkCapabilities.
2227 * Note: This wrapper does not support any sort of invalidation and thus must not be
2228 * persistent or long-lived. It may only be used for the time necessary to
2229 * compute the redactions required by one particular NetworkCallback or
2230 * synchronous call.
2231 */
2232 private class RedactionPermissionChecker {
2233 private final int mCallingPid;
2234 private final int mCallingUid;
2235 @NonNull private final String mCallingPackageName;
2236 @Nullable private final String mCallingAttributionTag;
2237
2238 private Boolean mHasLocationPermission = null;
2239 private Boolean mHasLocalMacAddressPermission = null;
2240 private Boolean mHasSettingsPermission = null;
2241
2242 RedactionPermissionChecker(int callingPid, int callingUid,
2243 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2244 mCallingPid = callingPid;
2245 mCallingUid = callingUid;
2246 mCallingPackageName = callingPackageName;
2247 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002248 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002249
2250 private boolean hasLocationPermissionInternal() {
2251 final long token = Binder.clearCallingIdentity();
2252 try {
2253 return mLocationPermissionChecker.checkLocationPermission(
2254 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2255 null /* message */);
2256 } finally {
2257 Binder.restoreCallingIdentity(token);
2258 }
2259 }
2260
2261 /**
2262 * Returns whether the app holds location permission or not (might return cached result
2263 * if the permission was already checked before).
2264 */
2265 public boolean hasLocationPermission() {
2266 if (mHasLocationPermission == null) {
2267 // If there is no cached result, perform the check now.
2268 mHasLocationPermission = hasLocationPermissionInternal();
2269 }
2270 return mHasLocationPermission;
2271 }
2272
2273 /**
2274 * Returns whether the app holds local mac address permission or not (might return cached
2275 * result if the permission was already checked before).
2276 */
2277 public boolean hasLocalMacAddressPermission() {
2278 if (mHasLocalMacAddressPermission == null) {
2279 // If there is no cached result, perform the check now.
2280 mHasLocalMacAddressPermission =
2281 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2282 }
2283 return mHasLocalMacAddressPermission;
2284 }
2285
2286 /**
2287 * Returns whether the app holds settings permission or not (might return cached
2288 * result if the permission was already checked before).
2289 */
2290 public boolean hasSettingsPermission() {
2291 if (mHasSettingsPermission == null) {
2292 // If there is no cached result, perform the check now.
2293 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2294 }
2295 return mHasSettingsPermission;
2296 }
2297 }
2298
2299 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2300 @NetworkCapabilities.NetCapability long redaction) {
2301 return (redactions & redaction) != 0;
2302 }
2303
2304 /**
2305 * Use the provided |applicableRedactions| to check the receiving app's
2306 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2307 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2308 * before being sent to the corresponding app.
2309 */
2310 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2311 @NetworkCapabilities.RedactionType long applicableRedactions,
2312 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2313 boolean includeLocationSensitiveInfo) {
2314 long redactions = applicableRedactions;
2315 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2316 if (includeLocationSensitiveInfo
2317 && redactionPermissionChecker.hasLocationPermission()) {
2318 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2319 }
2320 }
2321 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2322 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2323 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2324 }
2325 }
2326 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2327 if (redactionPermissionChecker.hasSettingsPermission()) {
2328 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2329 }
2330 }
2331 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002332 }
2333
Qingxi Lib2748102020-01-08 12:51:49 -08002334 @VisibleForTesting
2335 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002336 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002337 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002338 int callingPid, int callingUid, @NonNull String callingPkgName,
2339 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002340 if (nc == null) {
2341 return null;
2342 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002343 // Avoid doing location permission check if the transport info has no location sensitive
2344 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002345 final RedactionPermissionChecker redactionPermissionChecker =
2346 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2347 callingAttributionTag);
2348 final long redactions = retrieveRequiredRedactions(
2349 nc.getApplicableRedactions(), redactionPermissionChecker,
2350 includeLocationSensitiveInfo);
2351 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002352 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002353 // TODO : calling UID is redacted because apps should generally not know what UID is
2354 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002355 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002356 newNc.setOwnerUid(INVALID_UID);
2357 return newNc;
2358 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002359 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2360 if (nc.hasTransport(TRANSPORT_VPN)) {
2361 // Owner UIDs already checked above. No need to re-check.
2362 return newNc;
2363 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002364 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2365 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002366 // compatibility for older apps.
2367 if (!includeLocationSensitiveInfo
2368 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002369 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002370 newNc.setOwnerUid(INVALID_UID);
2371 return newNc;
2372 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002373 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002374 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002375 newNc.setOwnerUid(INVALID_UID);
2376 }
Qingxi Lib2748102020-01-08 12:51:49 -08002377 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002378 }
2379
lucaslinc582d502022-01-27 09:07:00 +08002380 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002381 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2382 LinkProperties lp, int callerPid, int callerUid) {
2383 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002384 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2385 // this would be expensive (one more permission check every time any LP callback is
2386 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2387 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2388 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002389
2390 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2391 final boolean needsSanitization =
2392 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2393 if (!needsSanitization) {
2394 return new LinkProperties(lp);
2395 }
2396
2397 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002398 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002399 }
2400
2401 final LinkProperties newLp = new LinkProperties(lp);
2402 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2403 // object gets parceled.
2404 newLp.setCaptivePortalApiUrl(null);
2405 newLp.setCaptivePortalData(null);
2406 return newLp;
2407 }
2408
Roshan Pius08c94fb2020-01-16 12:17:17 -08002409 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2410 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002411 // There is no need to track the effective UID of the request here. If the caller
2412 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002413 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002414 // Unprivileged apps can only pass in null or their own UID.
2415 if (nc.getUids() == null) {
2416 // If the caller passes in null, the callback will also match networks that do not
2417 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2418 // In this case, redact everything in the request immediately. This ensures that the
2419 // app is not able to get any redacted information by filing an unredacted request
2420 // and observing whether the request matches something.
2421 if (nc.getNetworkSpecifier() != null) {
2422 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2423 }
2424 } else {
2425 nc.setSingleUid(callerUid);
2426 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002427 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002428 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002429 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002430
2431 // Clear owner UID; this can never come from an app.
2432 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002433 }
2434
Chalard Jean38354d12018-03-20 19:13:57 +09002435 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002436 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002437 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2438 }
2439 }
2440
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002441 @Override
2442 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2443 enforceAccessPermission();
2444 final int callerUid = Binder.getCallingUid();
2445 final long token = Binder.clearCallingIdentity();
2446 try {
2447 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2448 } finally {
2449 Binder.restoreCallingIdentity(token);
2450 }
2451 }
2452
junyulaiebd15162021-03-03 12:09:05 +08002453 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002454 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002455 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002456 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002457 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002458
Serik Beketayev05130302021-01-15 16:47:25 -08002459 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002460 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002461 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2462 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002463 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002464 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002465 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002466 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2467 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002468 }
2469 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002470 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002471 }
2472
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002473 @Override
junyulaiebd15162021-03-03 12:09:05 +08002474 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002475 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002476 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002477 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002478
2479 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2480 for (Network network : getAllNetworks()) {
2481 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09002482 if (nai != null && nai.everConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002483 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2484 // NetworkCapabilities, which may contain UIDs of apps to which the
2485 // network applies. Should the UIDs be cleared so as not to leak or
2486 // interfere ?
2487 result.add(nai.getNetworkStateSnapshot());
2488 }
2489 }
2490 return result;
2491 }
2492
2493 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002494 public boolean isActiveNetworkMetered() {
2495 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002496
Qingxi Lib2748102020-01-08 12:51:49 -08002497 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002498 if (caps != null) {
2499 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2500 } else {
2501 // Always return the most conservative value
2502 return true;
2503 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002504 }
2505
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002506 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002507 * Ensures that the system cannot call a particular method.
2508 */
2509 private boolean disallowedBecauseSystemCaller() {
2510 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002511 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2512 // for devices launched with Q and above. However, existing devices upgrading to Q and
2513 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002514 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002515 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002516 log("This method exists only for app backwards compatibility"
2517 + " and must not be called by system services.");
2518 return true;
2519 }
2520 return false;
2521 }
2522
paulhub2c28682021-08-18 18:35:54 +08002523 private int getAppUid(final String app, final UserHandle user) {
2524 final PackageManager pm =
2525 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2526 final long token = Binder.clearCallingIdentity();
2527 try {
2528 return pm.getPackageUid(app, 0 /* flags */);
2529 } catch (PackageManager.NameNotFoundException e) {
2530 return -1;
2531 } finally {
2532 Binder.restoreCallingIdentity(token);
2533 }
2534 }
2535
2536 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2537 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2538 if (getAppUid(packageName, user) != callingUid) {
2539 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2540 }
2541 }
2542
Lorenzo Colitti23862912018-09-28 11:31:55 +09002543 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002544 * Ensure that a network route exists to deliver traffic to the specified
2545 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002546 * @param networkType the type of the network over which traffic to the
2547 * specified host is to be routed
2548 * @param hostAddress the IP address of the host to which the route is
2549 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002550 * @return {@code true} on success, {@code false} on failure
2551 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002552 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002553 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2554 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002555 if (disallowedBecauseSystemCaller()) {
2556 return false;
2557 }
paulhub2c28682021-08-18 18:35:54 +08002558 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002559 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002560 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002561 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002562 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002563
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002564 InetAddress addr;
2565 try {
2566 addr = InetAddress.getByAddress(hostAddress);
2567 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002568 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002569 return false;
2570 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002571
The Android Open Source Project28527d22009-03-03 19:31:44 -08002572 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002573 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002574 return false;
2575 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002576
2577 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2578 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002579 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002580 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2581 } else {
2582 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2583 }
2584 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002585 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002586
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002587 DetailedState netState;
2588 synchronized (nai) {
2589 netState = nai.networkInfo.getDetailedState();
2590 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002591
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002592 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002593 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002594 log("requestRouteToHostAddress on down network "
2595 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002596 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002597 }
2598 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002599 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002600
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002601 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002602 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002603 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002604 LinkProperties lp;
2605 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002606 synchronized (nai) {
2607 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002608 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002609 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002610 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002611 if (DBG) {
2612 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2613 }
Wink Saville32506bc2013-06-29 21:10:57 -07002614 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002615 } finally {
2616 Binder.restoreCallingIdentity(token);
2617 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002618 }
2619
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002620 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002621 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002622 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002623 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002624 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002625 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002626 if (bestRoute.getGateway().equals(addr)) {
2627 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002628 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002629 } else {
2630 // if we will connect to this through another route, add a direct route
2631 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002632 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002633 }
2634 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002635 if (DBG) log("Adding legacy route " + bestRoute +
2636 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002637
2638 final String dst = bestRoute.getDestinationLinkAddress().toString();
2639 final String nextHop = bestRoute.hasGateway()
2640 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002641 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002642 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2643 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002644 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002645 return false;
2646 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002647 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002648 }
2649
paulhu7c0a2e62021-01-08 00:51:49 +08002650 class DnsResolverUnsolicitedEventCallback extends
2651 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002652 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002653 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002654 try {
2655 mHandler.sendMessage(mHandler.obtainMessage(
2656 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002657 new PrivateDnsValidationUpdate(event.netId,
2658 InetAddresses.parseNumericAddress(event.ipAddress),
2659 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002660 } catch (IllegalArgumentException e) {
2661 loge("Error parsing ip address in validation event");
2662 }
2663 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002664
2665 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002666 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2667 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002668 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2669 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2670 // event callback for certain nai. e.g. cellular. Register here to pass to
2671 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002672 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002673 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2674 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002675 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002676 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002677 }
2678 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002679
2680 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002681 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2682 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2683 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002684 }
dalyk1720e542018-03-05 12:42:22 -05002685
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002686 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002687 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002688 return this.VERSION;
2689 }
2690
2691 @Override
2692 public String getInterfaceHash() {
2693 return this.HASH;
2694 }
paulhu7c0a2e62021-01-08 00:51:49 +08002695 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002696
2697 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002698 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2699 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002700
paulhu7c0a2e62021-01-08 00:51:49 +08002701 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002702 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002703 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002704 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002705 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002706 }
2707 }
2708
Sudheer Shanka9967d462021-03-18 19:09:25 +00002709 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002710 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002711 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002712 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2713 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002714 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002715 };
2716
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002717 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002718 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002719 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002720 }
2721
paulhu1a407652019-03-22 16:35:06 +08002722 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2723 for (String permission : permissions) {
2724 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2725 return true;
2726 }
2727 }
2728 return false;
2729 }
2730
Paul Jensen83f5d572014-08-29 09:54:01 -04002731 private void enforceInternetPermission() {
2732 mContext.enforceCallingOrSelfPermission(
2733 android.Manifest.permission.INTERNET,
2734 "ConnectivityService");
2735 }
2736
The Android Open Source Project28527d22009-03-03 19:31:44 -08002737 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002738 mContext.enforceCallingOrSelfPermission(
2739 android.Manifest.permission.ACCESS_NETWORK_STATE,
2740 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002741 }
2742
lucaslinc582d502022-01-27 09:07:00 +08002743 private boolean checkAccessPermission(int pid, int uid) {
2744 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2745 == PERMISSION_GRANTED;
2746 }
2747
paulhua6ee2122021-02-22 15:40:43 +08002748 /**
2749 * Performs a strict and comprehensive check of whether a calling package is allowed to
2750 * change the state of network, as the condition differs for pre-M, M+, and
2751 * privileged/preinstalled apps. The caller is expected to have either the
2752 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2753 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2754 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2755 * permission and cannot be revoked. See http://b/23597341
2756 *
2757 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2758 * of this app will be updated to the current time.
2759 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002760 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002761 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2762 == PackageManager.PERMISSION_GRANTED) {
2763 return;
2764 }
2765
2766 if (callingPkg == null) {
2767 throw new SecurityException("Calling package name is null.");
2768 }
2769
2770 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2771 final int uid = mDeps.getCallingUid();
2772 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2773 callingPkg, callingAttributionTag, null /* message */);
2774
2775 if (mode == AppOpsManager.MODE_ALLOWED) {
2776 return;
2777 }
2778
2779 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2780 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2781 return;
2782 }
2783
2784 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2785 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2786 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002787 }
2788
Charles He9369e612017-05-15 17:07:18 +01002789 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002790 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002791 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002792 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002793 }
2794
paulhu8e96a752019-08-12 16:25:11 +08002795 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002796 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002797 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002798 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002799 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002800 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002801 }
2802
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002803 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002804 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002805 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002806 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002807 android.Manifest.permission.NETWORK_SETTINGS,
2808 android.Manifest.permission.NETWORK_FACTORY,
2809 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2810 }
2811
2812 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002813 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002814 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002815 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002816 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2817 android.Manifest.permission.NETWORK_FACTORY,
2818 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2819 }
2820
lucaslin69e1aa92022-03-22 18:15:09 +08002821 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2822 return PERMISSION_GRANTED == mContext.checkPermission(
2823 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2824 || PERMISSION_GRANTED == mContext.checkPermission(
2825 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2826 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002827 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002828 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002829 }
2830
Chalard Jean9a396cc2018-02-21 18:43:54 +09002831 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002832 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002833 android.Manifest.permission.NETWORK_SETTINGS,
2834 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002835 }
2836
2837 private boolean checkSettingsPermission(int pid, int uid) {
2838 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002839 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2840 || PERMISSION_GRANTED == mContext.checkPermission(
2841 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002842 }
2843
paulhu8e96a752019-08-12 16:25:11 +08002844 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002845 enforceNetworkStackPermissionOr(mContext,
2846 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002847 }
2848
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002849 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002850 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002851 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002852 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002853 }
2854
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002855 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002856 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002857 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2858 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002859 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002860 }
2861
James Mattis8378aec2021-01-26 14:05:36 -08002862 private void enforceOemNetworkPreferencesPermission() {
2863 mContext.enforceCallingOrSelfPermission(
2864 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2865 "ConnectivityService");
2866 }
2867
James Mattisfa270db2021-05-31 17:11:10 -07002868 private void enforceManageTestNetworksPermission() {
2869 mContext.enforceCallingOrSelfPermission(
2870 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2871 "ConnectivityService");
2872 }
2873
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002874 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002875 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002876 android.Manifest.permission.NETWORK_STACK,
2877 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002878 }
2879
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002880 private boolean checkNetworkStackPermission(int pid, int uid) {
2881 return checkAnyPermissionOf(pid, uid,
2882 android.Manifest.permission.NETWORK_STACK,
2883 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2884 }
2885
paulhu1a407652019-03-22 16:35:06 +08002886 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2887 return checkAnyPermissionOf(pid, uid,
2888 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002889 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2890 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002891 }
2892
Paul Hu8fc2a552022-05-04 18:44:42 +08002893 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
2894 boolean checkUidsAllowedList) {
2895 if (PermissionUtils.checkAnyPermissionOf(mContext,
2896 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
2897 return true;
2898 }
2899
2900 // fallback to ConnectivityInternalPermission
2901 // TODO: Remove this fallback check after all apps have declared
2902 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2903 if (PermissionUtils.checkAnyPermissionOf(mContext,
2904 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
2905 return true;
2906 }
2907
2908 // Check whether uid is in allowed on restricted networks list.
2909 if (checkUidsAllowedList
2910 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
2911 return true;
2912 }
2913 return false;
2914 }
2915
2916 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
2917 final int callingUid = mDeps.getCallingUid();
2918 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
2919 throw new SecurityException("ConnectivityService: user " + callingUid
2920 + " has no permission to access restricted network.");
2921 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09002922 }
2923
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002924 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002925 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002926 }
2927
Roshan Pius98f59ec2021-02-23 08:47:39 -08002928 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2929 return PERMISSION_GRANTED == mContext.checkPermission(
2930 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2931 }
2932
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002933 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002934 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002935 }
2936
2937 private void sendInetConditionBroadcast(NetworkInfo info) {
2938 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2939 }
2940
Wink Saville4f0de1e2011-08-04 15:01:58 -07002941 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002942 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002943 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002944 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002945 if (info.isFailover()) {
2946 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2947 info.setFailover(false);
2948 }
2949 if (info.getReason() != null) {
2950 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2951 }
2952 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002953 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2954 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002955 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002956 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002957 return intent;
2958 }
2959
2960 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2961 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2962 }
2963
Chiachang Wang3bc52762021-11-25 14:17:57 +08002964 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2965 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002966 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002967 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002968 if (!mSystemReady
2969 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002970 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002971 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002972 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002973 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002974 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002975 }
2976
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002977 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002978 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002979 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002980 final NetworkInfo ni = intent.getParcelableExtra(
2981 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002982 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2983 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2984 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002985 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002986 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002987 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002988 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002989 } finally {
2990 Binder.restoreCallingIdentity(ident);
2991 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002992 }
2993 }
2994
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002995 /**
Aaron Huang96011892020-06-27 07:18:23 +08002996 * Called by SystemServer through ConnectivityManager when the system is ready.
2997 */
2998 @Override
2999 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003000 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003001 throw new SecurityException("Calling Uid is not system uid.");
3002 }
3003 systemReadyInternal();
3004 }
3005
3006 /**
3007 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003008 */
3009 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003010 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003011 // Load flags after PackageManager is ready to query module version
3012 mFlags.loadFlags(mDeps, mContext);
3013
Aaron Huang9a57acf2020-12-08 10:03:29 +08003014 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3015 // listening network request which is sent by MultipathPolicyTracker won't be added
3016 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3017 // be called after PermissionMonitor#startMonitoring().
3018 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3019 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3020 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08003021 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003022 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003023 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003024
Hugo Benichie5220992017-04-26 14:53:28 +09003025 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003026 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003027 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003028 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003029 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003030 }
3031 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003032
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003033 // Create network requests for always-on networks.
3034 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003035
3036 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003037 // Note that updating can be skipped here if the list is empty only because no uid
3038 // rules are applied before system ready. Normally, the empty uid list means to clear
3039 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003040 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3041 updateMobileDataPreferredUids();
3042 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003043
3044 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3045 if (SdkLevel.isAtLeastT()) {
3046 mBpfNetMaps.setPullAtomCallback(mContext);
3047 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003048 }
3049
The Android Open Source Project28527d22009-03-03 19:31:44 -08003050 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003051 * Start listening for default data network activity state changes.
3052 */
3053 @Override
3054 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003055 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003056 }
3057
3058 /**
3059 * Stop listening for default data network activity state changes.
3060 */
3061 @Override
3062 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003063 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003064 }
3065
3066 /**
3067 * Check whether the default network radio is currently active.
3068 */
3069 @Override
3070 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003071 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003072 }
3073
3074 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003075 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003076 * and set it on it's iface.
3077 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003078 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
3079 final String iface = newLp.getInterfaceName();
3080 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09003081 if (oldLp == null && mtu == 0) {
3082 // Silently ignore unset MTU value.
3083 return;
3084 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003085 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
3086 if (VDBG) log("identical MTU - not setting");
3087 return;
3088 }
paulhucbbc3db2019-03-08 16:35:20 +08003089 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003090 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003091 return;
3092 }
sy.yun4aa73922013-09-02 05:24:09 +09003093
w19976e714f1d2014-08-05 15:18:11 -07003094 // Cannot set MTU without interface name
3095 if (TextUtils.isEmpty(iface)) {
3096 loge("Setting MTU size with null iface.");
3097 return;
3098 }
3099
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003100 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003101 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003102 mNetd.interfaceSetMtu(iface, mtu);
3103 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003104 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003105 }
3106 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003107
Chenbo Feng15416292018-11-08 17:36:21 -08003108 @VisibleForTesting
3109 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003110
lucaslin821c9782018-11-28 19:27:52 +08003111 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003112 String[] values = null;
3113 if (tcpBufferSizes != null) {
3114 values = tcpBufferSizes.split(",");
3115 }
3116
3117 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003118 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003119 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3120 values = tcpBufferSizes.split(",");
3121 }
3122
3123 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3124
3125 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003126 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003127
Chenbo Feng15416292018-11-08 17:36:21 -08003128 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3129 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3130 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003131 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003132 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003133 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003134 }
3135 }
3136
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003137 @Override
3138 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003139 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003140 NETWORK_RESTORE_DELAY_PROP_NAME);
3141 if(restoreDefaultNetworkDelayStr != null &&
3142 restoreDefaultNetworkDelayStr.length() != 0) {
3143 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003144 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003145 } catch (NumberFormatException e) {
3146 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003147 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003148 // if the system property isn't set, use the value for the apn type
3149 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3150
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003151 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3152 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003153 }
3154 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003155 }
3156
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003157 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003158 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003159 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003160 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003161 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003162 // Start gathering diagnostic information.
3163 netDiags.add(new NetworkDiagnostics(
3164 nai.network,
3165 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003166 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003167 DIAG_TIME_MS));
3168 }
3169
3170 for (NetworkDiagnostics netDiag : netDiags) {
3171 pw.println();
3172 netDiag.waitForMeasurements();
3173 netDiag.dump(pw);
3174 }
3175 }
3176
The Android Open Source Project28527d22009-03-03 19:31:44 -08003177 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003178 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3179 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003180 if (!checkDumpPermission(mContext, TAG, writer)) return;
3181
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003182 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003183 }
3184
lucaslin99473f62020-12-10 15:10:54 +08003185 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3186 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3187 != PackageManager.PERMISSION_GRANTED) {
3188 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003189 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003190 + " due to missing android.permission.DUMP permission");
3191 return false;
3192 } else {
3193 return true;
3194 }
3195 }
3196
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003197 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003198 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003199
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003200 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003201 dumpNetworkDiagnostics(pw);
3202 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003203 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003204 dumpNetworks(pw);
3205 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003206 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003207 dumpNetworkRequests(pw);
3208 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003209 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3210 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3211 dumpTrafficController(pw, fd, verbose);
3212 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003213 }
Erik Kline9647f382015-06-05 17:47:34 +09003214
Junyu Lai0da479b2022-04-20 15:06:29 +08003215 pw.println("NetworkProviders for:");
3216 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003217 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003218 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003219 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003220 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003221 pw.println();
3222
Chalard Jean5b409c72021-02-04 13:12:59 +09003223 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003224 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003225 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003226 pw.println("none");
3227 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003228 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003229 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003230 pw.println();
3231
James Mattis8b298a02021-06-01 22:34:04 -07003232 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003233 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003234 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003235 pw.decreaseIndent();
3236 pw.println();
3237
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003238 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003239 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003240 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003241 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003242 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003243
junyulaif2c67e42018-08-07 19:50:45 +08003244 pw.println("Status for known UIDs:");
3245 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003246 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003247 for (int i = 0; i < size; i++) {
3248 // Don't crash if the array is modified while dumping in bugreports.
3249 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003250 final int uid = mUidBlockedReasons.keyAt(i);
3251 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3252 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003253 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003254 } catch (ArrayIndexOutOfBoundsException e) {
3255 pw.println(" ArrayIndexOutOfBoundsException");
3256 } catch (ConcurrentModificationException e) {
3257 pw.println(" ConcurrentModificationException");
3258 }
3259 }
3260 pw.println();
3261 pw.decreaseIndent();
3262
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003263 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003264 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003265 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003266 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003267 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003268
Junyu Lai0da479b2022-04-20 15:06:29 +08003269 pw.println("Network Offers:");
3270 pw.increaseIndent();
3271 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3272 pw.println(offerInfo.offer);
3273 }
3274 pw.decreaseIndent();
3275 pw.println();
3276
Robert Greenwalt94e22142014-07-30 16:31:24 -07003277 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003278
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003279 pw.println();
markchien5e866652019-09-30 14:40:57 +08003280 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003281
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003282 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003283 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003284
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003285 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003286
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003287 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003288 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003289 pw.println("mNetworkRequestInfoLogs (most recent first):");
3290 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003291 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003292 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003293
3294 pw.println();
3295 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3296 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003297 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003298 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003299
3300 pw.println();
3301 pw.println("NetTransition WakeLock activity (most recent first):");
3302 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003303 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3304 pw.println("total releases: " + mTotalWakelockReleases);
3305 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3306 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3307 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3308 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3309 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3310 }
James Mattiscb1e0362021-04-06 17:07:42 -07003311 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003312
3313 pw.println();
3314 pw.println("bandwidth update requests (by uid):");
3315 pw.increaseIndent();
3316 synchronized (mBandwidthRequests) {
3317 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3318 pw.println("[" + mBandwidthRequests.keyAt(i)
3319 + "]: " + mBandwidthRequests.valueAt(i));
3320 }
3321 }
3322 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003323 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003324
James Mattiscb1e0362021-04-06 17:07:42 -07003325 pw.println();
3326 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3327 pw.increaseIndent();
3328 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003329 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003330 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003331
3332 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003333
3334 pw.println();
3335 pw.println("Permission Monitor:");
3336 pw.increaseIndent();
3337 mPermissionMonitor.dump(pw);
3338 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003339
3340 pw.println();
3341 pw.println("Legacy network activity:");
3342 pw.increaseIndent();
3343 mNetworkActivityTracker.dump(pw);
3344 pw.decreaseIndent();
Ken Chendaf5cb62022-07-04 11:09:28 +08003345
3346 // pre-T is logged by netd.
3347 if (SdkLevel.isAtLeastT()) {
3348 pw.println();
3349 pw.println("BPF programs & maps:");
3350 pw.increaseIndent();
3351 // Flush is required. Otherwise, the traces in fd can interleave with traces in pw.
3352 pw.flush();
3353 dumpTrafficController(pw, fd, /*verbose=*/ true);
3354 pw.decreaseIndent();
3355 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003356 }
3357
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003358 private void dumpNetworks(IndentingPrintWriter pw) {
3359 for (NetworkAgentInfo nai : networksSortedById()) {
3360 pw.println(nai.toString());
3361 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003362 pw.println("Nat464Xlat:");
3363 pw.increaseIndent();
3364 nai.dumpNat464Xlat(pw);
3365 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003366 pw.println(String.format(
3367 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3368 nai.numForegroundNetworkRequests(),
3369 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3370 nai.numBackgroundNetworkRequests(),
3371 nai.numNetworkRequests()));
3372 pw.increaseIndent();
3373 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3374 pw.println(nai.requestAt(i).toString());
3375 }
3376 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003377 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003378 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003379 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003380 pw.decreaseIndent();
3381 pw.decreaseIndent();
3382 }
3383 }
3384
James Mattis8b298a02021-06-01 22:34:04 -07003385 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3386 if (!mProfileNetworkPreferences.isEmpty()) {
3387 pw.println("Profile preferences:");
3388 pw.increaseIndent();
3389 pw.println(mProfileNetworkPreferences.preferences);
3390 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003391 }
James Mattis8b298a02021-06-01 22:34:04 -07003392 if (!mOemNetworkPreferences.isEmpty()) {
3393 pw.println("OEM preferences:");
3394 pw.increaseIndent();
3395 pw.println(mOemNetworkPreferences);
3396 pw.decreaseIndent();
3397 }
3398 if (!mMobileDataPreferredUids.isEmpty()) {
3399 pw.println("Mobile data preferred UIDs:");
3400 pw.increaseIndent();
3401 pw.println(mMobileDataPreferredUids);
3402 pw.decreaseIndent();
3403 }
James Mattis45d81842021-01-10 14:24:24 -08003404
James Mattis8b298a02021-06-01 22:34:04 -07003405 pw.println("Default requests:");
3406 pw.increaseIndent();
3407 dumpPerAppDefaultRequests(pw);
3408 pw.decreaseIndent();
3409 }
3410
3411 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003412 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3413 if (mDefaultRequest == defaultRequest) {
3414 continue;
3415 }
3416
James Mattis8b298a02021-06-01 22:34:04 -07003417 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3418 final String networkOutput;
3419 if (null == satisfier) {
3420 networkOutput = "null";
3421 } else if (mNoServiceNetwork.equals(satisfier)) {
3422 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003423 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003424 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003425 }
James Mattis8b298a02021-06-01 22:34:04 -07003426 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3427 ? "" : " asUid: " + defaultRequest.mAsUid;
3428 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3429 + defaultRequest.mPid + asUidString + "]";
3430 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3431 + " Preference order: " + defaultRequest.mPreferenceOrder
3432 + " Tracked UIDs: " + defaultRequest.getUids();
3433 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003434 }
3435 }
3436
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003437 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003438 NetworkRequestInfo[] infos = null;
3439 while (infos == null) {
3440 try {
3441 infos = requestsSortedById();
3442 } catch (ConcurrentModificationException e) {
3443 // mNetworkRequests should only be accessed from handler thread, except dump().
3444 // As dump() is never called in normal usage, it would be needlessly expensive
3445 // to lock the collection only for its benefit. Instead, retry getting the
3446 // requests if ConcurrentModificationException is thrown during dump().
3447 }
3448 }
3449 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003450 pw.println(nri.toString());
3451 }
3452 }
3453
Ken Chene6d511f2022-01-25 11:10:42 +08003454 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3455 boolean verbose) {
3456 try {
3457 mBpfNetMaps.dump(fd, verbose);
3458 } catch (ServiceSpecificException e) {
3459 pw.println(e.getMessage());
3460 } catch (IOException e) {
3461 loge("Dump BPF maps failed, " + e);
3462 }
3463 }
3464
Chalard Jean524f0b12021-10-25 21:11:56 +09003465 private void dumpAllRequestInfoLogsToLogcat() {
3466 try (PrintWriter logPw = new PrintWriter(new Writer() {
3467 @Override
3468 public void write(final char[] cbuf, final int off, final int len) {
3469 // This method is called with 0-length and 1-length arrays for empty strings
3470 // or strings containing only the DEL character.
3471 if (len <= 1) return;
3472 Log.e(TAG, new String(cbuf, off, len));
3473 }
3474 @Override public void flush() {}
3475 @Override public void close() {}
3476 })) {
3477 mNetworkRequestInfoLogs.dump(logPw);
3478 }
3479 }
3480
Hugo Benichia480ba52018-09-03 08:19:02 +09003481 /**
3482 * Return an array of all current NetworkAgentInfos sorted by network id.
3483 */
3484 private NetworkAgentInfo[] networksSortedById() {
3485 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003486 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003487 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003488 return networks;
3489 }
3490
3491 /**
3492 * Return an array of all current NetworkRequest sorted by request id.
3493 */
James Mattis258ea3c2020-11-15 15:04:40 -08003494 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003495 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003496 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003497 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003498 // Sort the array based off the NRI containing the min requestId in its requests.
3499 Arrays.sort(requests,
3500 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3501 Comparator.comparingInt(req -> req.requestId)).requestId
3502 )
3503 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003504 return requests;
3505 }
3506
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003507 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003508 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003509 if (officialNai != null && officialNai.equals(nai)) return true;
3510 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003511 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003512 " - " + nai);
3513 }
3514 return false;
3515 }
3516
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003517 private boolean isDisconnectRequest(Message msg) {
3518 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3519 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3520 return info.getState() == NetworkInfo.State.DISCONNECTED;
3521 }
3522
Robert Greenwalt2034b912009-08-12 16:08:25 -07003523 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003524 private class NetworkStateTrackerHandler extends Handler {
3525 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003526 super(looper);
3527 }
3528
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003529 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003530 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3531 final NetworkAgentInfo nai = arg.first;
3532 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003533 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003534 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003535 }
3536 return;
3537 }
3538
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003539 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003540 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003541 return;
3542 }
3543
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003544 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003545 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003546 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3547 final NetworkCapabilities sanitized =
3548 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003549 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003550 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003551 break;
3552 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003553 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003554 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003555 processLinkPropertiesFromAgent(nai, newLp);
3556 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003557 break;
3558 }
3559 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003560 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003561 updateNetworkInfo(nai, info);
3562 break;
3563 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003564 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003565 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003566 break;
3567 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003568 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003569 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003570 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003571 // Note that if the NAI had been connected, this would affect the
3572 // score, and therefore would require re-mixing the score and performing
3573 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003574 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003575 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3576 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003577 // Mark the network as temporarily accepting partial connectivity so that it
3578 // will be validated (and possibly become default) even if it only provides
3579 // partial internet access. Note that if user connects to partial connectivity
3580 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3581 // out of wifi coverage) and if the same wifi is available again, the device
3582 // will auto connect to this wifi even though the wifi has "no internet".
3583 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003584 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003585 break;
3586 }
junyulai011b1f12019-01-03 18:50:15 +08003587 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003588 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003589 break;
3590 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003591 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003592 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003593 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003594
3595 if (isLegacyLockdownNai(nai)
3596 && (underlying == null || underlying.size() != 1)) {
3597 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3598 + " must have exactly one underlying network: " + underlying);
3599 }
3600
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003601 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3602 nai.declaredUnderlyingNetworks = (underlying != null)
3603 ? underlying.toArray(new Network[0]) : null;
3604
3605 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3606 if (DBG) {
3607 log(nai.toShortString() + " changed underlying networks to "
3608 + Arrays.toString(nai.declaredUnderlyingNetworks));
3609 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003610 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003611 notifyIfacesChangedForNetworkStats();
3612 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003613 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003614 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003615 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3616 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3617 nai.teardownDelayMs = msg.arg1;
3618 } else {
3619 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3620 }
Chalard Jean550b5212021-03-05 23:07:53 +09003621 break;
3622 }
3623 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3624 nai.setLingerDuration((int) arg.second);
3625 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003626 }
Tyler Wear72388212021-09-09 14:49:02 -07003627 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3628 DscpPolicy policy = (DscpPolicy) arg.second;
3629 if (mDscpPolicyTracker != null) {
3630 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3631 }
3632 break;
3633 }
3634 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3635 if (mDscpPolicyTracker != null) {
3636 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3637 }
3638 break;
3639 }
3640 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3641 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003642 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003643 }
3644 break;
3645 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003646 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003647 // If nai is not yet created, or is already destroyed, ignore.
3648 if (!shouldDestroyNativeNetwork(nai)) break;
3649
3650 final int timeoutMs = (int) arg.second;
3651 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3652 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3653 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3654 }
3655
3656 // Marking a network awaiting replacement is used to ensure that any requests
3657 // satisfied by the network do not switch to another network until a
3658 // replacement is available or the wait for a replacement times out.
3659 // If the network is inactive (i.e., nascent or lingering), then there are no
3660 // such requests, and there is no point keeping it. Just tear it down.
3661 // Note that setLingerDuration(0) cannot be used to do this because the network
3662 // could be nascent.
3663 nai.clearInactivityState();
3664 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3665 Log.d(TAG, nai.toShortString()
3666 + " marked awaiting replacement is unneeded, tearing down instead");
3667 teardownUnneededNetwork(nai);
3668 break;
3669 }
3670
3671 Log.d(TAG, "Marking " + nai.toShortString()
3672 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3673 destroyNativeNetwork(nai);
3674
3675 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3676 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3677 // consider the fact that the network could already have disconnected or been
3678 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3679 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3680 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3681 mKeepaliveTracker.handleStopAllKeepalives(nai,
3682 SocketKeepalive.ERROR_INVALID_NETWORK);
3683
3684 nai.updateScoreForNetworkAgentUpdate();
3685 // This rematch is almost certainly not going to result in any changes, because
3686 // the destroyed flag is only just above the "current satisfier wins"
3687 // tie-breaker. But technically anything that affects scoring should rematch.
3688 rematchAllNetworksAndRequests();
3689 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3690 break;
3691 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003692 }
3693 }
3694
3695 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003696 final int netId = msg.arg2;
3697 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003698 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003699 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003700 switch (msg.what) {
3701 default:
3702 return false;
lucasline117e2e2019-10-22 18:27:33 +08003703 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003704 if (nai == null) {
3705 break;
3706 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003707 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3708 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003709 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003710 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003711 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003712 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003713 if (probePrivateDnsCompleted) {
3714 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3715 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003716 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003717 }
3718 // Only show the notification when the private DNS is broken and the
3719 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003720 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003721 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3722 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003723 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003724 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3725 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3726 // private DNS is broken, it means this network is being reevaluated.
3727 // Either probing private DNS is not necessary any more or it hasn't been
3728 // done yet. In either case, the networkCapabilities should be updated to
3729 // reflect the new status.
3730 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003731 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003732 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003733 }
3734 break;
3735 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003736 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003737 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3738
Erik Kline31b4a9e2018-01-11 21:07:29 +09003739 if (nai == null) break;
3740
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003741 handleNetworkTested(nai, results.mTestResult,
3742 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003743 break;
3744 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003745 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003746 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003747 // If captive portal status has changed, update capabilities or disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003748 if (nai != null && (visible != nai.captivePortalDetected())) {
3749 nai.setCaptivePortalDetected(visible);
3750 if (visible && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3751 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003752 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003753 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003754 teardownUnneededNetwork(nai);
3755 break;
3756 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003757 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003758 }
3759 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003760 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003761 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003762 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3763 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003764 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003765 if (nai == null) {
3766 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3767 break;
3768 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003769 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003770 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003771 (PendingIntent) msg.obj,
3772 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003773 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003774 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003775 break;
3776 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003777 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003778 if (nai == null) break;
3779
Erik Kline9a62f012018-03-21 07:18:33 -07003780 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003781 break;
3782 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003783 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003784 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003785 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003786 break;
3787 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003788 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003789 return true;
3790 }
3791
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003792 private void handleNetworkTested(
3793 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
he_won.hwang881307a2022-03-15 21:23:52 +09003794 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3795 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3796 // Assume the validation failure is due to a temporary failure after roaming
3797 // and ignore it. NetworkMonitor will continue to retry validation. If it
3798 // continues to fail after the block timeout expires, the network will be
3799 // marked unvalidated. If it succeeds, then validation state will not change.
3800 return;
3801 }
3802
Chalard Jean254bd162022-08-25 13:04:51 +09003803 final boolean wasValidated = nai.isValidated();
3804 final boolean wasPartial = nai.partialConnectivity();
3805 nai.setPartialConnectivity((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3806 final boolean partialConnectivityChanged = (wasPartial != nai.partialConnectivity());
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003807
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003808 if (DBG) {
3809 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3810 ? " with redirect to " + redirectUrl
3811 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003812 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003813 }
Chalard Jean254bd162022-08-25 13:04:51 +09003814 if (valid != nai.isValidated()) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003815 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09003816 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003817 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003818 if (valid) {
3819 handleFreshlyValidatedNetwork(nai);
3820 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3821 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003822 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003823 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003824 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003825 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003826 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003827 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003828 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003829 NotificationType.PRIVATE_DNS_BROKEN);
3830 // If network becomes valid, the hasShownBroken should be reset for
3831 // that network so that the notification will be fired when the private
3832 // DNS is broken again.
3833 nai.networkAgentConfig.hasShownBroken = false;
3834 }
3835 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003836 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003837 }
3838 updateInetCondition(nai);
3839 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003840 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003841 nai.onValidationStatusChanged(
3842 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3843 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003844
3845 // If NetworkMonitor detects partial connectivity before
3846 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3847 // immediately. Re-notify partial connectivity silently if no internet
3848 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09003849 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003850 // Remove delayed message if there is a pending message.
3851 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3852 handlePromptUnvalidated(nai.network);
3853 }
3854
Chalard Jean254bd162022-08-25 13:04:51 +09003855 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003856 handleNetworkUnvalidated(nai);
3857 }
3858 }
3859
Calvin Ondada1452016-10-11 15:10:46 -07003860 private int getCaptivePortalMode() {
3861 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003862 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3863 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003864 }
3865
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003866 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3867 switch (msg.what) {
3868 default:
3869 return false;
3870 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3871 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3872 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3873 handleLingerComplete(nai);
3874 }
3875 break;
3876 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003877 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3878 handleNetworkAgentRegistered(msg);
3879 break;
3880 }
3881 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3882 handleNetworkAgentDisconnected(msg);
3883 break;
3884 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003885 }
3886 return true;
3887 }
3888
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003889 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09003890 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003891 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003892 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003893 maybeHandleNetworkAgentMessage(msg);
3894 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003895 }
3896 }
3897
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003898 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003899 private final int mNetId;
3900 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003901
3902 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003903 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003904 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003905 }
3906
3907 @Override
3908 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3909 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003910 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003911 }
3912
3913 @Override
3914 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003915 // Legacy version of notifyNetworkTestedWithExtras.
3916 // Would only be called if the system has a NetworkStack module older than the
3917 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003918 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003919 }
3920
3921 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003922 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003923 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3924 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003925 final Message msg = mTrackerHandler.obtainMessage(
3926 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003927 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003928 new NetworkTestedResults(
3929 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003930 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003931
3932 // Invoke ConnectivityReport generation for this Network test event.
3933 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3934 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003935
Cody Kestingf1120be2020-08-03 18:01:40 -07003936 // NetworkMonitor reports the network validation result as a bitmask while
3937 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3938 // logical value for ConnectivityDiagnostics.
3939 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3940 p.result);
3941
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003942 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003943 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003944 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3945 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3946
Aaron Huang959d3642021-01-21 15:47:41 +08003947 ConnectivityReportEvent reportEvent =
3948 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3949 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09003950 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003951 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003952 }
3953
3954 @Override
3955 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3956 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3957 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003958 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003959 }
3960
3961 @Override
lucasline117e2e2019-10-22 18:27:33 +08003962 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3963 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3964 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003965 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08003966 }
3967
3968 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003969 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3970 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3971 EVENT_CAPPORT_DATA_CHANGED,
3972 0, mNetId, data));
3973 }
3974
3975 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003976 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003977 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003978 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003979
3980 final PendingIntent pendingIntent;
3981 // Only the system server can register notifications with package "android"
3982 final long token = Binder.clearCallingIdentity();
3983 try {
paulhu7746e4e2020-06-09 19:07:03 +08003984 pendingIntent = PendingIntent.getBroadcast(
3985 mContext,
3986 0 /* requestCode */,
3987 intent,
3988 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003989 } finally {
3990 Binder.restoreCallingIdentity(token);
3991 }
3992 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3993 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003994 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003995 }
3996
3997 @Override
3998 public void hideProvisioningNotification() {
3999 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004000 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004001 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004002
4003 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004004 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004005 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004006 }
4007
4008 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004009 public int getInterfaceVersion() {
4010 return this.VERSION;
4011 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004012
4013 @Override
4014 public String getInterfaceHash() {
4015 return this.HASH;
4016 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004017 }
4018
Cody Kestingf1120be2020-08-03 18:01:40 -07004019 /**
4020 * Converts the given NetworkMonitor-specific validation result bitmask to a
4021 * ConnectivityDiagnostics-specific validation result int.
4022 */
4023 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4024 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4025 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4026 }
4027 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4028 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4029 }
4030 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4031 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4032 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4033 }
4034
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004035 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004036 log("Data stall detected with methods: " + p.detectionMethod);
4037
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004038 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004039 int detectionMethod = 0;
4040 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4041 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4042 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4043 }
4044 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4045 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4046 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4047 p.tcpMetricsCollectionPeriodMillis);
4048 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004049 }
4050
Cody Kestingf53a0752020-04-15 12:33:28 -07004051 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004052 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004053 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004054
4055 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4056 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4057 // the cost of going through two handlers.
4058 mConnectivityDiagnosticsHandler.sendMessage(msg);
4059 }
4060
Cody Kestingb37958e2020-05-15 10:36:01 -07004061 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4062 return (p.detectionMethod & detectionMethod) != 0;
4063 }
4064
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004065 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4066 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004067 }
4068
Erik Klinea73af002018-06-26 18:53:43 +09004069 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4070 if (nai == null) return;
4071 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4072 // in order to restart a validation pass from within netd.
4073 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4074 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004075 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004076 }
4077 }
4078
Erik Kline31b4a9e2018-01-11 21:07:29 +09004079 private void handlePrivateDnsSettingsChanged() {
4080 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4081
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004082 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004083 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004084 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004085 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4086 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004087 }
4088 }
4089
Erik Kline9a62f012018-03-21 07:18:33 -07004090 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4091 // Private DNS only ever applies to networks that might provide
4092 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004093 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004094
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004095 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004096 // schedule DNS resolutions. If a DNS resolution is required the
4097 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004098 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004099
4100 // With Private DNS bypass support, we can proceed to update the
4101 // Private DNS config immediately, even if we're in strict mode
4102 // and have not yet resolved the provider name into a set of IPs.
4103 updatePrivateDns(nai, cfg);
4104 }
4105
4106 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4107 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004108 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004109 }
4110
dalyk1720e542018-03-05 12:42:22 -05004111 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4112 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4113 if (nai == null) {
4114 return;
4115 }
4116 mDnsManager.updatePrivateDnsValidation(update);
4117 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4118 }
4119
paulhu7c0a2e62021-01-08 00:51:49 +08004120 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004121 int prefixLength) {
4122 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4123 if (nai == null) return;
4124
paulhu7c0a2e62021-01-08 00:51:49 +08004125 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4126 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004127
4128 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004129 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004130 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004131 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004132 prefixLength);
4133 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004134 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004135 return;
4136 }
4137 }
4138
Lorenzo Colittid523d142020-04-01 20:16:30 +09004139 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004140 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4141 }
4142
Hai Shalome58bdc62021-01-11 18:45:34 -08004143 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004144 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004145 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004146 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4147 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4148 }
4149
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004150 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004151 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004152 * @param nai the agent info to update
4153 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004154 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004155 */
junyulai2b6f0c22021-02-03 20:15:30 +08004156 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4157 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4158 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004159 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004160 // one lingered request, set inactive.
4161 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004162 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004163 if (DBG) log("Unsetting inactive " + nai.toShortString());
4164 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004165 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004166 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004167 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004168 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4169 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004170 }
junyulai2b6f0c22021-02-03 20:15:30 +08004171 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004172 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004173 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004174 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004175 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004176 }
4177
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004178 private void handleNetworkAgentRegistered(Message msg) {
4179 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4180 if (!mNetworkAgentInfos.contains(nai)) {
4181 return;
4182 }
4183
4184 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4185 if (VDBG) log("NetworkAgent registered");
4186 } else {
4187 loge("Error connecting NetworkAgent");
4188 mNetworkAgentInfos.remove(nai);
4189 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004190 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004191 synchronized (mNetworkForNetId) {
4192 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004193 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004194 mNetIdManager.releaseNetId(nai.network.getNetId());
4195 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004196 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004197 }
4198 }
4199 }
Paul Jensend5f53392014-11-25 15:26:53 -05004200
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004201 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004202 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004203 }
4204
he_won.hwang881307a2022-03-15 21:23:52 +09004205 private boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004206 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004207 if (SdkLevel.isAtLeastT()) return false;
4208 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4209 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
4210 if (blockTimeOut <= MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS
4211 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004212 final long currentTimeMs = SystemClock.elapsedRealtime();
4213 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004214 if (timeSinceLastRoam <= blockTimeOut) {
4215 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4216 return true;
4217 }
4218 }
4219 return false;
4220 }
4221
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004222 private void handleNetworkAgentDisconnected(Message msg) {
4223 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004224 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004225 }
4226
Chalard Jeand9fffc32018-05-11 20:19:20 +09004227 // Destroys a network, remove references to it from the internal state managed by
4228 // ConnectivityService, free its interfaces and clean up.
4229 // Must be called on the Handler thread.
4230 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004231 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004232
4233 if (!mNetworkAgentInfos.contains(nai)) return;
4234
Chalard Jeand9fffc32018-05-11 20:19:20 +09004235 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004236 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004237 }
lucaslinb25c9a62019-02-12 15:30:13 +08004238 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004239 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004240 // A network agent has disconnected.
4241 // TODO - if we move the logic to the network agent (have them disconnect
4242 // because they lost all their requests or because their score isn't good)
4243 // then they would disconnect organically, report their new state and then
4244 // disconnect the channel.
4245 if (nai.networkInfo.isConnected()) {
4246 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4247 null, null);
4248 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004249 final boolean wasDefault = isDefaultNetwork(nai);
4250 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004251 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004252 }
4253 notifyIfacesChangedForNetworkStats();
4254 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4255 // by other networks that are already connected. Perhaps that can be done by
4256 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4257 // of rematchAllNetworksAndRequests
4258 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004259 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004260
4261 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004262 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4263 // Disable wakeup packet monitoring for each interface.
4264 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4265 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004266 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004267 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004268 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004269 synchronized (mNetworkForNetId) {
4270 // Remove the NetworkAgent, but don't mark the netId as
4271 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004272 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004273 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004274 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004275 // Remove all previously satisfied requests.
4276 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004277 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004278 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004279 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004280 if (currentNetwork != null
4281 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004282 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004283 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4284 // rematch not to keep disconnected agents instead of setting it here ; this
4285 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004286 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004287 for (final NetworkOfferInfo noi : mNetworkOffers) {
4288 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004289 }
James Mattise3ef1912020-12-20 11:09:58 -08004290
Chalard Jean5b409c72021-02-04 13:12:59 +09004291 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004292 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004293 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004294 // network, because while incorrect this is the closest to the old (also
4295 // incorrect) behavior.
4296 mNetworkActivityTracker.updateDataActivityTracking(
4297 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004298 ensureNetworkTransitionWakelock(nai.toShortString());
4299 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004300 }
4301 }
junyulai2b6f0c22021-02-03 20:15:30 +08004302 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004303 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004304 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004305 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004306 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004307 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004308 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004309
4310 // Immediate teardown.
4311 if (nai.teardownDelayMs == 0) {
4312 destroyNetwork(nai);
4313 return;
4314 }
4315
4316 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004317 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304318 try {
4319 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4320 } catch (RemoteException e) {
4321 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4322 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004323 }
4324 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4325 }
4326
4327 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004328 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004329 // Tell netd to clean up the configuration for this network
4330 // (routing rules, DNS, etc).
4331 // This may be slow as it requires a lot of netd shelling out to ip and
4332 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004333 // after we've rematched networks with requests (which might change the default
4334 // network or service a new request from an app), so network traffic isn't interrupted
4335 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004336 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004337 }
Chalard Jean254bd162022-08-25 13:04:51 +09004338 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004339 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4340 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4341 // false if the network was never created.
4342 // TODO: delete when S is no longer supported.
4343 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004344 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004345 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004346 }
4347
Ken Chen6df7a902021-04-09 15:08:42 +08004348 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004349 try {
4350 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004351 final NativeNetworkConfig config;
4352 if (nai.isVPN()) {
4353 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004354 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004355 return false;
4356 }
4357 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4358 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004359 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004360 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004361 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004362 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004363 getNetworkPermission(nai.networkCapabilities),
4364 false /* secure */,
4365 VpnManager.TYPE_VPN_NONE,
4366 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004367 }
Ken Chen6df7a902021-04-09 15:08:42 +08004368 mNetd.networkCreate(config);
4369 mDnsResolver.createNetworkCache(nai.network.getNetId());
4370 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4371 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004372 return true;
4373 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004374 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004375 return false;
4376 }
4377 }
4378
Ken Chen6df7a902021-04-09 15:08:42 +08004379 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004380 if (mDscpPolicyTracker != null) {
4381 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4382 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004383 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004384 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004385 } catch (RemoteException | ServiceSpecificException e) {
4386 loge("Exception destroying network(networkDestroy): " + e);
4387 }
4388 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004389 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004390 } catch (RemoteException | ServiceSpecificException e) {
4391 loge("Exception destroying network: " + e);
4392 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004393 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4394 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4395 // gets created, could add data to DnsManager data structures that will never get deleted.
4396 mDnsManager.removeNetwork(nai.network);
4397
4398 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004399 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004400 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4401 }
4402
Chalard Jean254bd162022-08-25 13:04:51 +09004403 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004404 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004405 }
4406
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004407 // If this method proves to be too slow then we can maintain a separate
4408 // pendingIntent => NetworkRequestInfo map.
4409 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4410 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004411 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4412 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4413 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004414 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004415 return entry.getValue();
4416 }
4417 }
4418 return null;
4419 }
4420
Chalard Jean524f0b12021-10-25 21:11:56 +09004421 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4422 if (SdkLevel.isAtLeastT()) {
4423 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4424 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4425 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4426 // bug is fixed.
4427 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004428 throw new IllegalStateException("This NRI is already registered. New : " + nri
4429 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004430 }
4431 }
4432 }
4433 }
4434
Chalard Jeanac9ace02022-01-26 16:54:05 +09004435 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4436 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004437 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004438 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4439 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004440 }
4441 return false;
4442 }
4443
James Mattisf7027322020-12-13 16:28:14 -08004444 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004445 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004446 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4447 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4448 final NetworkRequestInfo existingRequest =
4449 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004450 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004451 if (DBG) {
4452 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4453 + nri.mRequests.get(0) + " because their intents matched.");
4454 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004455 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004456 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004457 }
Erik Kline05f2b402015-04-30 12:58:40 +09004458 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004459 }
4460
James Mattisf7027322020-12-13 16:28:14 -08004461 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004462 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004463 }
4464
James Mattis3ce3d3c2021-02-09 18:18:28 -08004465 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004466 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004467 for (final NetworkRequestInfo nri : nris) {
4468 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004469 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004470 for (final NetworkRequest req : nri.mRequests) {
4471 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004472 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004473 if (req.isListen()) {
4474 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4475 if (req.networkCapabilities.hasSignalStrength()
4476 && network.satisfiesImmutableCapabilitiesOf(req)) {
4477 updateSignalStrengthThresholds(network, "REGISTER", req);
4478 }
James Mattisf7027322020-12-13 16:28:14 -08004479 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004480 }
4481 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004482
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004483 // If this NRI has a satisfier already, it is replacing an older request that
4484 // has been removed. Track it.
4485 final NetworkRequest activeRequest = nri.getActiveRequest();
4486 if (null != activeRequest) {
4487 // If there is an active request, then for sure there is a satisfier.
4488 nri.getSatisfier().addRequest(activeRequest);
4489 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004490 }
James Mattisf7027322020-12-13 16:28:14 -08004491
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004492 if (mFlags.noRematchAllRequestsOnRegister()) {
4493 rematchNetworksAndRequests(nris);
4494 } else {
4495 rematchAllNetworksAndRequests();
4496 }
James Mattis45d81842021-01-10 14:24:24 -08004497
Chalard Jean0354d8c2021-01-12 10:58:56 +09004498 // Requests that have not been matched to a network will not have been sent to the
4499 // providers, because the old satisfier and the new satisfier are the same (null in this
4500 // case). Send these requests to the providers.
4501 for (final NetworkRequestInfo nri : nris) {
4502 for (final NetworkOfferInfo noi : mNetworkOffers) {
4503 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004504 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004505 }
4506 }
4507
James Mattisf7027322020-12-13 16:28:14 -08004508 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4509 final int callingUid) {
4510 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004511 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004512 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4513 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4514 handleReleaseNetworkRequest(
4515 nri.mRequests.get(0),
4516 callingUid,
4517 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004518 }
4519 }
4520
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004521 // Determines whether the network is the best (or could become the best, if it validated), for
4522 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4523 // on the value of reason:
4524 //
4525 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4526 // then it should be torn down.
4527 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4528 // then it should be lingered.
4529 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004530 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004531
Chalard Jean254bd162022-08-25 13:04:51 +09004532 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004533 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4534 return false;
4535 }
4536
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004537 final int numRequests;
4538 switch (reason) {
4539 case TEARDOWN:
4540 numRequests = nai.numRequestNetworkRequests();
4541 break;
4542 case LINGER:
4543 numRequests = nai.numForegroundNetworkRequests();
4544 break;
4545 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004546 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004547 return true;
4548 }
4549
Chalard Jean947acd42021-03-08 22:29:27 +09004550 if (numRequests > 0) return false;
4551
Paul Jensende49eb12015-06-25 15:30:08 -04004552 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004553 if (reason == UnneededFor.LINGER
4554 && !nri.isMultilayerRequest()
4555 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004556 // Background requests don't affect lingering.
4557 continue;
4558 }
4559
James Mattis3d229892020-11-16 16:46:28 -08004560 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004561 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004562 }
4563 }
Paul Jensende49eb12015-06-25 15:30:08 -04004564 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004565 }
4566
James Mattis3d229892020-11-16 16:46:28 -08004567 private boolean isNetworkPotentialSatisfier(
4568 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4569 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004570 // request, return immediately. For multilayer requests, check to see if any of the
4571 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004572 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4573 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004574 return false;
4575 }
4576 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004577 // This multilayer listen request is satisfied therefore no further requests need to be
4578 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004579 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004580 return false;
4581 }
James Mattis3d229892020-11-16 16:46:28 -08004582 // As non-multilayer listen requests have already returned, the below would only happen
4583 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004584 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004585 continue;
4586 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004587 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004588 // there is hope for it to become one if it validated, then it is needed.
4589 if (candidate.satisfies(req)) {
4590 // As soon as a network is found that satisfies a request, return. Specifically for
4591 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4592 // is important so as to not evaluate lower priority requests further in
4593 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004594 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4595 ? nri.getSatisfier() : null;
4596 // Note that this catches two important cases:
4597 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4598 // is currently satisfying the request. This is desirable when
4599 // cellular ends up validating but WiFi does not.
4600 // 2. Unvalidated WiFi will not be reaped when validated cellular
4601 // is currently satisfying the request. This is desirable when
4602 // WiFi ends up validating and out scoring cellular.
4603 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004604 }
4605 }
4606
4607 return false;
4608 }
4609
Erik Kline0c04b742016-07-07 16:50:58 +09004610 private NetworkRequestInfo getNriForAppRequest(
4611 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004612 // Looking up the app passed param request in mRequests isn't possible since it may return
4613 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4614 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004615 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4616 // to avoid potential race conditions when validating a package->uid mapping when sending
4617 // the callback on the very low-chance that an application shuts down prior to the callback
4618 // being sent.
4619 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4620 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004621
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004622 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004623 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004624 log(String.format("UID %d attempted to %s for unowned request %s",
4625 callingUid, requestedOperation, nri));
4626 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004627 }
Erik Kline0c04b742016-07-07 16:50:58 +09004628 }
4629
4630 return nri;
4631 }
4632
James Mattisf7027322020-12-13 16:28:14 -08004633 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4634 final String callingMethod) {
4635 if (nri.isMultilayerRequest()) {
4636 throw new IllegalStateException(
4637 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004638 }
4639 }
4640
James Mattisf7027322020-12-13 16:28:14 -08004641 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004642 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004643 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4644 // single NetworkRequest and thus does not apply to multilayer requests.
4645 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4646 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004647 return;
4648 }
James Mattis2516da32021-01-31 17:06:19 -08004649 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004650 return;
4651 }
James Mattisf7027322020-12-13 16:28:14 -08004652 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4653 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004654 }
4655 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004656 callCallbackForRequest(
4657 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004658 }
4659
James Mattisf7027322020-12-13 16:28:14 -08004660 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4661 final int callingUid,
4662 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004663 final NetworkRequestInfo nri =
4664 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4665 if (nri == null) {
4666 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004667 }
James Mattisf7027322020-12-13 16:28:14 -08004668 if (VDBG || (DBG && request.isRequest())) {
4669 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004670 }
4671 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004672 if (callOnUnavailable) {
4673 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4674 }
Erik Kline155a59a2015-11-25 12:49:38 +09004675 }
Erik Kline0c04b742016-07-07 16:50:58 +09004676
James Mattisa076c532020-12-02 14:12:41 -08004677 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004678 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004679 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004680 if (null == mNetworkRequests.remove(req)) {
4681 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4682 continue;
4683 }
James Mattisa076c532020-12-02 14:12:41 -08004684 if (req.isListen()) {
4685 removeListenRequestFromNetworks(req);
4686 }
4687 }
James Mattis8f036802021-06-20 16:26:01 -07004688 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004689 if (mDefaultNetworkRequests.remove(nri)) {
4690 // If this request was one of the defaults, then the UID rules need to be updated
4691 // WARNING : if the app(s) for which this network request is the default are doing
4692 // traffic, this will kill their connected sockets, even if an equivalent request
4693 // is going to be reinstated right away ; unconnected traffic will go on the default
4694 // until the new default is set, which will happen very soon.
4695 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4696 // remove ranges for those requests that won't have a replacement
4697 final NetworkAgentInfo satisfier = nri.getSatisfier();
4698 if (null != satisfier) {
4699 try {
paulhu0e79d952021-06-09 16:11:35 +08004700 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4701 satisfier.network.getNetId(),
4702 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004703 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004704 } catch (RemoteException e) {
4705 loge("Exception setting network preference default network", e);
4706 }
4707 }
4708 }
Junyu Lai00d92df2022-07-05 11:01:52 +08004709 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004710 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004711 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004712
4713 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004714 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004715 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004716 }
4717 }
4718
Chalard Jean0354d8c2021-01-12 10:58:56 +09004719 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4720 // needed for this offer.
4721 for (final NetworkOfferInfo noi : mNetworkOffers) {
4722 for (final NetworkRequest req : nri.mRequests) {
4723 if (req.isRequest() && noi.offer.neededFor(req)) {
4724 noi.offer.onNetworkUnneeded(req);
4725 }
4726 }
4727 }
James Mattisa076c532020-12-02 14:12:41 -08004728 }
4729
James Mattis3ce3d3c2021-02-09 18:18:28 -08004730 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4731 for (final NetworkRequestInfo nri : nris) {
4732 if (mDefaultRequest == nri) {
4733 // Make sure we never remove the default request.
4734 continue;
4735 }
4736 handleRemoveNetworkRequest(nri);
4737 }
4738 }
4739
James Mattisa076c532020-12-02 14:12:41 -08004740 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4741 // listens don't have a singular affected Network. Check all networks to see
4742 // if this listen request applies and remove it.
4743 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4744 nai.removeRequest(req.requestId);
4745 if (req.networkCapabilities.hasSignalStrength()
4746 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4747 updateSignalStrengthThresholds(nai, "RELEASE", req);
4748 }
4749 }
4750 }
4751
4752 /**
4753 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4754 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4755 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4756 */
4757 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4758 boolean wasKept = false;
4759 final NetworkAgentInfo nai = nri.getSatisfier();
4760 if (nai != null) {
4761 final int requestLegacyType = nri.getActiveRequest().legacyType;
4762 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4763 nai.removeRequest(nri.getActiveRequest().requestId);
4764 if (VDBG || DDBG) {
4765 log(" Removing from current network " + nai.toShortString()
4766 + ", leaving " + nai.numNetworkRequests() + " requests.");
4767 }
4768 // If there are still lingered requests on this network, don't tear it down,
4769 // but resume lingering instead.
4770 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004771 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004772 notifyNetworkLosing(nai, now);
4773 }
4774 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4775 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4776 teardownUnneededNetwork(nai);
4777 } else {
4778 wasKept = true;
4779 }
James Mattisa076c532020-12-02 14:12:41 -08004780 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4781 // Went from foreground to background.
4782 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004783 }
4784
Erik Kline0c04b742016-07-07 16:50:58 +09004785 // Maintain the illusion. When this request arrived, we might have pretended
4786 // that a network connected to serve it, even though the network was already
4787 // connected. Now that this request has gone away, we might have to pretend
4788 // that the network disconnected. LegacyTypeTracker will generate that
4789 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004790 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004791 boolean doRemove = true;
4792 if (wasKept) {
4793 // check if any of the remaining requests for this network are for the
4794 // same legacy type - if so, don't remove the nai
4795 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4796 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004797 if (otherRequest.legacyType == requestLegacyType
4798 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004799 if (DBG) log(" still have other legacy request - leaving");
4800 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004801 }
4802 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004803 }
4804
Erik Kline0c04b742016-07-07 16:50:58 +09004805 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004806 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004807 }
4808 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004809 }
4810 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004811
Junyu Lai00d92df2022-07-05 11:01:52 +08004812 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004813 return checkAnyPermissionOf(
4814 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4815 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4816 }
4817
Lorenzo Colittid6459092016-07-04 12:55:44 +09004818 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004819 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004820 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004821 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004822 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004823 }
4824
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004825 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004826 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4827 enforceNetworkStackSettingsOrSetup();
4828 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4829 encodeBool(accept), encodeBool(always), network));
4830 }
4831
4832 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004833 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004834 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004835 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4836 }
4837
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004838 @Override
4839 public void setTestAllowBadWifiUntil(long timeMs) {
4840 enforceSettingsPermission();
4841 if (!Build.isDebuggable()) {
4842 throw new IllegalStateException("Does not support in non-debuggable build");
4843 }
4844
4845 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4846 throw new IllegalArgumentException("It should not exceed "
4847 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4848 }
4849
4850 mHandler.sendMessage(
4851 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4852 }
4853
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004854 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4855 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4856 " accept=" + accept + " always=" + always);
4857
4858 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4859 if (nai == null) {
4860 // Nothing to do.
4861 return;
4862 }
4863
Chalard Jean254bd162022-08-25 13:04:51 +09004864 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004865 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004866 return;
4867 }
4868
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004869 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004870 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004871 }
4872
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004873 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4874 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004875 // If network becomes partial connectivity and user already accepted to use this
4876 // network, we should respect the user's option and don't need to popup the
4877 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004878 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004879 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004880 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004881 }
4882
4883 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004884 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004885 }
4886
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004887 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004888 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004889 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004890 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004891 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004892 }
4893
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004894 }
4895
lucaslin2240ef62019-03-12 13:08:03 +08004896 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4897 boolean always) {
4898 if (DBG) {
4899 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4900 + " always=" + always);
4901 }
4902
4903 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4904 if (nai == null) {
4905 // Nothing to do.
4906 return;
4907 }
4908
Chalard Jean254bd162022-08-25 13:04:51 +09004909 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08004910 // The network validated while the dialog box was up. Take no action.
4911 return;
4912 }
4913
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004914 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4915 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004916 }
4917
4918 // TODO: Use the current design or save the user choice into IpMemoryStore.
4919 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004920 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004921 }
4922
4923 if (!accept) {
4924 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004925 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004926 // Tear down the network.
4927 teardownUnneededNetwork(nai);
4928 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004929 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4930 // result in a partial connectivity result which will be processed by
4931 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004932 //
4933 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4934 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004935 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004936 }
4937 }
4938
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004939 private void handleSetAvoidUnvalidated(Network network) {
4940 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09004941 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004942 // Nothing to do. The network either disconnected or revalidated.
4943 return;
4944 }
Chalard Jean254bd162022-08-25 13:04:51 +09004945 if (0L == nai.getAvoidUnvalidated()) {
4946 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09004947 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004948 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004949 }
4950 }
4951
Chalard Jean4c463082022-09-08 20:52:25 +09004952 private void scheduleUnvalidatedPrompt(@NonNull final Network network) {
4953 scheduleUnvalidatedPrompt(network, PROMPT_UNVALIDATED_DELAY_MS);
4954 }
4955
4956 /** Schedule unvalidated prompt for testing */
4957 @VisibleForTesting
4958 public void scheduleUnvalidatedPrompt(@NonNull final Network network, final long delayMs) {
4959 if (VDBG) log("scheduleUnvalidatedPrompt " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004960 mHandler.sendMessageDelayed(
Chalard Jean4c463082022-09-08 20:52:25 +09004961 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004962 }
4963
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004964 @Override
4965 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004966 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004967 mHandler.post(() -> {
4968 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4969 if (nai == null) return;
4970 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004971 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004972 });
4973 }
4974
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004975 /**
4976 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4977 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004978 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004979 * @param appExtras Bundle to use as intent extras for the captive portal application.
4980 * Must be treated as opaque to avoid preventing the captive portal app to
4981 * update its arguments.
4982 */
4983 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004984 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004985 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4986 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004987
4988 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4989 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004990 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4991 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004992 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4993
lucaslin75ff7022020-12-17 04:14:35 +08004994 final long token = Binder.clearCallingIdentity();
4995 try {
4996 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4997 } finally {
4998 Binder.restoreCallingIdentity(token);
4999 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005000 }
5001
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005002 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5003 private final Network mNetwork;
5004
5005 private CaptivePortalImpl(Network network) {
5006 mNetwork = network;
5007 }
5008
5009 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005010 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005011 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5012 enforceSettingsPermission();
5013 }
5014
Chiachang Wang938bfba2020-01-09 13:50:55 +08005015 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005016 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005017 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005018 }
5019
5020 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005021 public void appRequest(final int request) {
5022 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5023 if (nm == null) return;
5024
5025 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005026 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005027 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005028 }
5029 }
5030
5031 @Nullable
5032 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5033 // getNetworkAgentInfoForNetwork is thread-safe
5034 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5035 if (nai == null) return null;
5036
5037 // nai.networkMonitor() is thread-safe
5038 return nai.networkMonitor();
5039 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005040 }
5041
Hugo Benichic9048bc2016-09-14 23:23:08 +00005042 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005043 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005044 }
5045
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005046 /**
5047 * Return whether the device should maintain continuous, working connectivity by switching away
5048 * from WiFi networks having no connectivity.
5049 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5050 */
5051 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005052 if (!checkNetworkStackPermission()) {
5053 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5054 }
5055 return avoidBadWifi();
5056 }
5057
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005058 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005059 ensureRunningOnConnectivityServiceThread();
5060 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005061 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005062 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005063 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005064 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5065 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5066 for (final NetworkOfferInfo noi : offersToUpdate) {
5067 updateOfferScore(noi.offer);
5068 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005069 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005070 }
5071
Erik Kline95ecfee2016-10-02 18:02:14 +09005072 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005073 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005074 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005075 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005076 if (!configRestrict) {
5077 pw.println("Bad Wi-Fi avoidance: unrestricted");
5078 return;
5079 }
5080
5081 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5082 pw.increaseIndent();
5083 pw.println("Config restrict: " + configRestrict);
5084
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005085 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005086 String description;
5087 // Can't use a switch statement because strings are legal case labels, but null is not.
5088 if ("0".equals(value)) {
5089 description = "get stuck";
5090 } else if (value == null) {
5091 description = "prompt";
5092 } else if ("1".equals(value)) {
5093 description = "avoid";
5094 } else {
5095 description = value + " (?)";
5096 }
5097 pw.println("User setting: " + description);
5098 pw.println("Network overrides:");
5099 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005100 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005101 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005102 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005103 }
5104 }
5105 pw.decreaseIndent();
5106 pw.decreaseIndent();
5107 }
5108
paulhu7746e4e2020-06-09 19:07:03 +08005109 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5110 // unify the method.
5111 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5112 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5113 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5114 return settingsComponent != null
5115 ? settingsComponent.getPackageName() : "com.android.settings";
5116 }
5117
lucaslinb1e8e382019-01-24 15:55:30 +08005118 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005119 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005120 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005121 switch (type) {
5122 case NO_INTERNET:
5123 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005124 // High priority because it is only displayed for explicitly selected networks.
5125 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005126 break;
lucasline117e2e2019-10-22 18:27:33 +08005127 case PRIVATE_DNS_BROKEN:
5128 action = Settings.ACTION_WIRELESS_SETTINGS;
5129 // High priority because we should let user know why there is no internet.
5130 highPriority = true;
5131 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005132 case LOST_INTERNET:
5133 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005134 // High priority because it could help the user avoid unexpected data usage.
5135 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005136 break;
lucaslin2240ef62019-03-12 13:08:03 +08005137 case PARTIAL_CONNECTIVITY:
5138 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005139 // Don't bother the user with a high-priority notification if the network was not
5140 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005141 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005142 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005143 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005144 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005145 return;
5146 }
5147
5148 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005149 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005150 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005151 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005152 // Some OEMs have their own Settings package. Thus, need to get the current using
5153 // Settings package name instead of just use default name "com.android.settings".
5154 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5155 intent.setClassName(settingsPkgName,
5156 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005157 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005158
paulhu2af50222020-10-11 22:52:27 +08005159 PendingIntent pendingIntent = PendingIntent.getActivity(
5160 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005161 0 /* requestCode */,
5162 intent,
paulhu2af50222020-10-11 22:52:27 +08005163 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005164
Serik Beketayevec8ad212020-12-07 22:43:07 -08005165 mNotifier.showNotification(
5166 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005167 }
5168
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005169 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5170 // Don't prompt if the network is validated, and don't prompt on captive portals
5171 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005172 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005173 return false;
5174 }
5175
5176 // If a network has partial connectivity, always prompt unless the user has already accepted
5177 // partial connectivity and selected don't ask again. This ensures that if the device
5178 // automatically connects to a network that has partial Internet access, the user will
5179 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005180 // because we have prompted them.
5181 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005182 return true;
5183 }
5184
5185 // If a network has no Internet access, only prompt if the network was explicitly selected
5186 // and if the user has not already told us to use the network regardless of whether it
5187 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005188 if (nai.networkAgentConfig.explicitlySelected
5189 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005190 return true;
5191 }
5192
5193 return false;
5194 }
5195
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005196 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09005197 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005198 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5199
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005200 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005201 return;
5202 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005203
5204 // Stop automatically reconnecting to this network in the future. Automatically connecting
5205 // to a network that provides no or limited connectivity is not useful, because the user
5206 // cannot use that network except through the notification shown by this method, and the
5207 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005208 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005209
lucaslin2240ef62019-03-12 13:08:03 +08005210 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
5211 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
5212 // popup the notification immediately when the network is partial connectivity.
Chalard Jean254bd162022-08-25 13:04:51 +09005213 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005214 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005215 } else {
5216 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5217 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005218 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005219
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005220 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5221 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005222 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005223
lucaslin2240ef62019-03-12 13:08:03 +08005224 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5225 return;
5226 }
5227
5228 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005229 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005230 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005231 }
5232
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005233 @Override
5234 public int getMultipathPreference(Network network) {
5235 enforceAccessPermission();
5236
5237 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005238 if (nai != null && nai.networkCapabilities
5239 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005240 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5241 }
5242
Aaron Huang9a57acf2020-12-08 10:03:29 +08005243 final NetworkPolicyManager netPolicyManager =
5244 mContext.getSystemService(NetworkPolicyManager.class);
5245
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005246 final long token = Binder.clearCallingIdentity();
5247 final int networkPreference;
5248 try {
5249 networkPreference = netPolicyManager.getMultipathPreference(network);
5250 } finally {
5251 Binder.restoreCallingIdentity(token);
5252 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005253 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005254 return networkPreference;
5255 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005256 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5257 }
5258
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005259 @Override
5260 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005261 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005262 }
5263
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005264 private class InternalHandler extends Handler {
5265 public InternalHandler(Looper looper) {
5266 super(looper);
5267 }
5268
5269 @Override
5270 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005271 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005272 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005273 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005274 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005275 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005276 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005277 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005278 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005279 break;
5280 }
Jason Monka69f1b02013-10-10 14:02:51 -04005281 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005282 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5283 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005284 break;
5285 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005286 case EVENT_REGISTER_NETWORK_PROVIDER: {
5287 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005288 break;
5289 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005290 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5291 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005292 break;
5293 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005294 case EVENT_REGISTER_NETWORK_OFFER: {
5295 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5296 break;
5297 }
5298 case EVENT_UNREGISTER_NETWORK_OFFER: {
5299 final NetworkOfferInfo offer =
5300 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5301 if (null != offer) {
5302 handleUnregisterNetworkOffer(offer);
5303 }
5304 break;
5305 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005306 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005307 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5308 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5309 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005310 break;
5311 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005312 case EVENT_REGISTER_NETWORK_REQUEST:
5313 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005314 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005315 break;
5316 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005317 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5318 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005319 handleRegisterNetworkRequestWithIntent(msg);
5320 break;
5321 }
Erik Kline155a59a2015-11-25 12:49:38 +09005322 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5323 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5324 handleTimedOutNetworkRequest(nri);
5325 break;
5326 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005327 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5328 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5329 break;
5330 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005331 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005332 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5333 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005334 break;
5335 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005336 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005337 Network network = (Network) msg.obj;
5338 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005339 break;
5340 }
lucaslin2240ef62019-03-12 13:08:03 +08005341 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5342 Network network = (Network) msg.obj;
5343 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5344 toBool(msg.arg2));
5345 break;
5346 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005347 case EVENT_SET_AVOID_UNVALIDATED: {
5348 handleSetAvoidUnvalidated((Network) msg.obj);
5349 break;
5350 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005351 case EVENT_PROMPT_UNVALIDATED: {
5352 handlePromptUnvalidated((Network) msg.obj);
5353 break;
5354 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005355 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5356 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005357 break;
5358 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005359 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005360 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005361 mKeepaliveTracker.handleStartKeepalive(msg);
5362 break;
5363 }
5364 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005365 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005366 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5367 int slot = msg.arg1;
5368 int reason = msg.arg2;
5369 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5370 break;
5371 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005372 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5373 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5374 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005375 break;
5376 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005377 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5378 handlePrivateDnsSettingsChanged();
5379 break;
dalyk1720e542018-03-05 12:42:22 -05005380 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5381 handlePrivateDnsValidationUpdate(
5382 (PrivateDnsValidationUpdate) msg.obj);
5383 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005384 case EVENT_UID_BLOCKED_REASON_CHANGED:
5385 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005386 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005387 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5388 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5389 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005390 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005391 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5392 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005393 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005394 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005395 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005396 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005397 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5398 IOnCompleteListener> arg =
5399 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5400 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005401 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005402 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005403 }
lucaslin1193a5d2021-01-21 02:04:15 +08005404 case EVENT_REPORT_NETWORK_ACTIVITY:
5405 mNetworkActivityTracker.handleReportNetworkActivity();
5406 break;
paulhu51f77dc2021-06-07 02:34:20 +00005407 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5408 handleMobileDataPreferredUidsChanged();
5409 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005410 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5411 final long timeMs = ((Long) msg.obj).longValue();
5412 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5413 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005414 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5415 handleIngressRateLimitChanged();
5416 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005417 }
5418 }
5419 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005420
Lorenzo Colittid6459092016-07-04 12:55:44 +09005421 @Override
markchien5776f962019-12-16 20:15:20 +08005422 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005423 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005424 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005425 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5426 Context.TETHERING_SERVICE);
5427 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005428 }
5429
Lorenzo Colittid6459092016-07-04 12:55:44 +09005430 @Override
markchien5776f962019-12-16 20:15:20 +08005431 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005432 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005433 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005434 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5435 Context.TETHERING_SERVICE);
5436 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005437 }
5438
Lorenzo Colittid6459092016-07-04 12:55:44 +09005439 @Override
markchien5776f962019-12-16 20:15:20 +08005440 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005441 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005442 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005443 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5444 Context.TETHERING_SERVICE);
5445 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005446 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005447
markchien5776f962019-12-16 20:15:20 +08005448
Lorenzo Colittid6459092016-07-04 12:55:44 +09005449 @Override
markchien5776f962019-12-16 20:15:20 +08005450 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005451 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005452 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005453 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5454 Context.TETHERING_SERVICE);
5455
5456 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005457 }
5458
Lorenzo Colittid6459092016-07-04 12:55:44 +09005459 @Override
markchien5776f962019-12-16 20:15:20 +08005460 @Deprecated
5461 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005462 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005463 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5464 Context.TETHERING_SERVICE);
5465
5466 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005467 }
5468
Udam Saini8f7d6a72017-06-07 12:06:28 -07005469 @Override
markchien5776f962019-12-16 20:15:20 +08005470 @Deprecated
5471 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005472 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005473 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5474 Context.TETHERING_SERVICE);
5475 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005476 }
5477
Robert Greenwalte0b00512014-07-02 09:59:16 -07005478 // Called when we lose the default network and have no replacement yet.
5479 // This will automatically be cleared after X seconds or a new default network
5480 // becomes CONNECTED, whichever happens first. The timer is started by the
5481 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005482 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005483 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005484 if (mNetTransitionWakeLock.isHeld()) {
5485 return;
5486 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005487 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005488 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5489 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005490 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005491 mWakelockLogs.log("ACQUIRE for " + forWhom);
5492 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005493 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005494 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005495 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005496 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005497
Hugo Benichi471b62a2017-03-30 23:18:10 +09005498 // Called when we gain a new default network to release the network transition wakelock in a
5499 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5500 // message is cancelled.
5501 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005502 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005503 if (!mNetTransitionWakeLock.isHeld()) {
5504 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005505 }
5506 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005507 // Cancel self timeout on wakelock hold.
5508 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5509 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5510 mHandler.sendMessageDelayed(msg, 1000);
5511 }
5512
5513 // Called when either message of ensureNetworkTransitionWakelock or
5514 // scheduleReleaseNetworkTransitionWakelock is processed.
5515 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5516 String event = eventName(eventId);
5517 synchronized (this) {
5518 if (!mNetTransitionWakeLock.isHeld()) {
5519 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005520 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005521 return;
5522 }
5523 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005524 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5525 mTotalWakelockDurationMs += lockDuration;
5526 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5527 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005528 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005529 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005530 }
5531
Robert Greenwalt986c7412010-09-08 15:24:47 -07005532 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005533 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005534 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005535 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005536 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005537 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005538 }
5539
Lorenzo Colittid6459092016-07-04 12:55:44 +09005540 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005541 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005542 enforceAccessPermission();
5543 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005544 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005545 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005546
5547 final NetworkAgentInfo nai;
5548 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005549 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005550 } else {
5551 nai = getNetworkAgentInfoForNetwork(network);
5552 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005553
5554 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005555 mHandler.obtainMessage(
5556 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005557 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005558
Hugo Benichid6b510a2017-04-06 17:22:18 +09005559 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005560 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005561 if (nai == null
5562 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005563 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005564 return;
5565 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005566 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005567 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005568 mConnectivityDiagnosticsHandler.sendMessage(
5569 mConnectivityDiagnosticsHandler.obtainMessage(
5570 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5571 new ReportedNetworkConnectivityInfo(
5572 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005573 return;
5574 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005575 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005576 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005577 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005578 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005579 // Validating a network that has not yet connected could result in a call to
5580 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005581 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005582 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005583 }
paulhu7aeba372020-12-30 00:42:19 +08005584 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5585 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005586 return;
5587 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005588
5589 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5590 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5591 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5592 // completed.
5593 mConnectivityDiagnosticsHandler.sendMessage(
5594 mConnectivityDiagnosticsHandler.obtainMessage(
5595 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5596 new ReportedNetworkConnectivityInfo(
5597 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005598 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005599 }
5600
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005601 // TODO: call into netd.
5602 private boolean queryUserAccess(int uid, Network network) {
5603 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5604 if (nai == null) return false;
5605
5606 // Any UID can use its default network.
5607 if (nai == getDefaultNetworkForUid(uid)) return true;
5608
5609 // Privileged apps can use any network.
5610 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5611 return true;
5612 }
5613
5614 // An unprivileged UID can use a VPN iff the VPN applies to it.
5615 if (nai.isVPN()) {
5616 return nai.networkCapabilities.appliesToUid(uid);
5617 }
5618
5619 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5620 // sockets, i.e., if it is the owner.
5621 final NetworkAgentInfo vpn = getVpnForUid(uid);
5622 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5623 && uid != vpn.networkCapabilities.getOwnerUid()) {
5624 return false;
5625 }
5626
5627 // The UID's permission must be at least sufficient for the network. Since the restricted
5628 // permission was already checked above, that just leaves background networks.
5629 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5630 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5631 }
5632
5633 // Unrestricted network. Anyone gets to use it.
5634 return true;
5635 }
5636
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005637 /**
5638 * Returns information about the proxy a certain network is using. If given a null network, it
5639 * it will return the proxy for the bound network for the caller app or the default proxy if
5640 * none.
5641 *
5642 * @param network the network we want to get the proxy information for.
5643 * @return Proxy information if a network has a proxy configured, or otherwise null.
5644 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005645 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005646 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005647 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005648 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005649 if (network == null) {
5650 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005651 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005652 true);
5653 if (activeNetwork == null) {
5654 return null;
5655 }
5656 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005657 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005658 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5659 // caller may not have.
5660 return getLinkPropertiesProxyInfo(network);
5661 }
5662 // No proxy info available if the calling UID does not have network access.
5663 return null;
5664 }
5665
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005666
5667 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005668 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5669 if (nai == null) return null;
5670 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005671 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5672 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005673 }
5674 }
5675
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005676 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005677 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005678 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005679 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005680 }
5681
Chalard Jean777e2e52018-06-07 18:02:37 +09005682 @Override
5683 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005684 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005685 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005686 }
5687
Jason Monk4d5e20f2014-04-25 15:00:09 -04005688 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005689 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005690 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005691 proxy = null;
5692 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005693 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005694 }
5695
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005696 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5697 // when any network changes proxy.
5698 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5699 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005700 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005701 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5702 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5703
Chalard Jean7d97afc2018-06-07 17:41:29 +09005704 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005705 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005706 }
5707 }
5708
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005709 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005710 final private HashMap<Uri, Integer> mUriEventMap;
5711 final private Context mContext;
5712 final private Handler mHandler;
5713
5714 SettingsObserver(Context context, Handler handler) {
5715 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005716 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005717 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005718 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005719 }
5720
Erik Kline05f2b402015-04-30 12:58:40 +09005721 void observe(Uri uri, int what) {
5722 mUriEventMap.put(uri, what);
5723 final ContentResolver resolver = mContext.getContentResolver();
5724 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005725 }
5726
5727 @Override
5728 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005729 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005730 }
5731
5732 @Override
5733 public void onChange(boolean selfChange, Uri uri) {
5734 final Integer what = mUriEventMap.get(uri);
5735 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005736 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005737 } else {
5738 loge("No matching event to send for URI=" + uri);
5739 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005740 }
5741 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005742
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005743 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005744 Log.d(TAG, s);
5745 }
5746
5747 private static void logw(String s) {
5748 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005749 }
5750
Daniel Brightf9e945b2020-06-15 16:10:01 -07005751 private static void logwtf(String s) {
5752 Log.wtf(TAG, s);
5753 }
5754
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005755 private static void logwtf(String s, Throwable t) {
5756 Log.wtf(TAG, s, t);
5757 }
5758
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005759 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005760 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005761 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005762
Hugo Benichi39621362017-02-11 17:04:43 +09005763 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005764 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005765 }
5766
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005767 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005768 * Return the information of all ongoing VPNs.
5769 *
5770 * <p>This method is used to update NetworkStatsService.
5771 *
5772 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005773 */
junyulai2050bed2021-01-23 09:46:34 +08005774 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005775 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005776 if (mLockdownEnabled) {
5777 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005778 }
junyulai2050bed2021-01-23 09:46:34 +08005779 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005780 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005781 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005782 if (info != null) {
5783 infoList.add(info);
5784 }
5785 }
junyulai2050bed2021-01-23 09:46:34 +08005786 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005787 }
5788
5789 /**
5790 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005791 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005792 */
junyulai2050bed2021-01-23 09:46:34 +08005793 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005794 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005795 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5796 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005797 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5798 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5799 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005800 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5801 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005802 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005803 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005804 }
5805 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005806
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005807 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005808
5809 List<String> interfaces = new ArrayList<>();
5810 for (Network network : underlyingNetworks) {
5811 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5812 if (underlyingNai == null) continue;
5813 LinkProperties lp = underlyingNai.linkProperties;
5814 for (String iface : lp.getAllInterfaceNames()) {
5815 if (!TextUtils.isEmpty(iface)) {
5816 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005817 }
5818 }
Benedict Wong34857f82019-06-12 17:46:15 +00005819 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005820
5821 if (interfaces.isEmpty()) return null;
5822
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005823 // Must be non-null or NetworkStatsService will crash.
5824 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5825 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005826 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005827 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005828
junyulai2050bed2021-01-23 09:46:34 +08005829 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5830 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005831 }
5832
James Mattisd31bdfa2020-12-23 16:37:26 -08005833 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005834 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5835 Network[] underlyingNetworks) {
5836 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005837 if (underlyingNetworks == null && defaultNetwork != null) {
5838 // null underlying networks means to track the default.
5839 underlyingNetworks = new Network[] { defaultNetwork };
5840 }
5841 return underlyingNetworks;
5842 }
5843
5844 // Returns true iff |network| is an underlying network of |nai|.
5845 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5846 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5847 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005848 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005849 final Network[] underlying = underlyingNetworksOrDefault(
5850 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005851 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005852 }
5853
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005854 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005855 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005856 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005857 * When underlying networks change, such networks may have to update capabilities to reflect
5858 * things like the metered bit, their transports, and so on. The capabilities are calculated
5859 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005860 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005861 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005862 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005863 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005864 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005865 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005866 }
5867 }
5868 }
5869
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005870 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5871 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5872 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5873 // a VPN is not up.
5874 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5875 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5876 for (UidRange range : blockedUidRanges) {
5877 if (range.contains(uid)) return true;
5878 }
5879 return false;
5880 }
5881
5882 @Override
5883 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005884 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005885 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5886 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5887 }
5888
5889 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5890 if (DBG) {
5891 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5892 + Arrays.toString(ranges));
5893 }
5894 // Cannot use a Set since the list of UID ranges might contain duplicates.
5895 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5896 for (int i = 0; i < ranges.length; i++) {
5897 if (requireVpn) {
5898 newVpnBlockedUidRanges.add(ranges[i]);
5899 } else {
5900 newVpnBlockedUidRanges.remove(ranges[i]);
5901 }
5902 }
5903
5904 try {
5905 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5906 } catch (RemoteException | ServiceSpecificException e) {
5907 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5908 + Arrays.toString(ranges) + "): netd command failed: " + e);
5909 }
5910
Motomu Utsumib08654c2022-05-11 05:56:26 +00005911 if (SdkLevel.isAtLeastT()) {
5912 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
5913 }
5914
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005915 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5916 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005917 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5918 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005919 }
5920
5921 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5922 }
5923
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005924 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005925 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005926 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005927 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005928 }
5929
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005930 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5931 return mLockdownEnabled
5932 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5933 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005934 }
5935
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005936 private NetworkAgentInfo getLegacyLockdownNai() {
5937 if (!mLockdownEnabled) {
5938 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005939 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005940 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005941 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5942 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005943
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005944 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005945 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5946 // a local variable. There is no need to make a copy because its contents cannot change.
5947 final Network[] underlying = nai.declaredUnderlyingNetworks;
5948 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005949 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005950 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005951
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005952 // The legacy lockdown VPN always uses the default network.
5953 // If the VPN's underlying network is no longer the current default network, it means that
5954 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005955 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5956 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005957 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005958 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005959 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005960 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005961
5962 return nai;
5963 };
5964
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005965 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5966 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5967 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005968 private DetailedState getLegacyLockdownState(DetailedState origState) {
5969 if (origState != DetailedState.CONNECTED) {
5970 return origState;
5971 }
5972 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5973 ? DetailedState.CONNECTING
5974 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005975 }
5976
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005977 private void filterForLegacyLockdown(NetworkInfo ni) {
5978 if (!mLockdownEnabled || !ni.isConnected()) return;
5979 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5980 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5981 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5982 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5983 // network, this time with a state of CONNECTED.
5984 //
5985 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5986 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5987 // is not too far off the truth, since an always-on VPN, when not connected, is always
5988 // trying to reconnect.
5989 if (getLegacyLockdownNai() == null) {
5990 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5991 }
5992 }
5993
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005994 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005995 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005996 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005997 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005998 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5999 return;
6000 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006001 final long ident = Binder.clearCallingIdentity();
6002 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006003 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006004 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006005 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006006 } finally {
6007 Binder.restoreCallingIdentity(ident);
6008 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006009 }
Wink Savillecb117d32013-08-29 14:57:08 -07006010
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006011 @Override
6012 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006013 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006014 final long ident = Binder.clearCallingIdentity();
6015 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006016 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006017 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006018 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6019 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006020 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006021 } finally {
6022 Binder.restoreCallingIdentity(ident);
6023 }
6024 }
6025
James Mattis02220e22021-03-13 19:27:21 -08006026 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006027 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08006028 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6029 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6030 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006031 }
6032
James Mattis02220e22021-03-13 19:27:21 -08006033 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006034 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09006035 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006036 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08006037 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006038 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006039 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6040 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6041 }
junyulaid91e7052020-08-28 13:44:33 +08006042 }
6043
James Mattis02220e22021-03-13 19:27:21 -08006044 private void onPackageChanged(@NonNull final String packageName) {
6045 // This is necessary in case a package is added or removed, but also when it's replaced to
6046 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6047 // as one in the preferences, then it should follow the same routing as that other package,
6048 // which means updating the rules is never to be needed in this case (whether it joins or
6049 // leaves a UID with a preference).
6050 if (isMappedInOemNetworkPreference(packageName)) {
6051 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6052 }
6053 }
6054
6055 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006056 @Override
6057 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006058 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006059 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006060 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006061
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006062 // User should be filled for below intents, check the existence.
6063 if (user == null) {
6064 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6065 return;
6066 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006067
Lorenzo Colitticd675292021-02-04 17:32:07 +09006068 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006069 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006070 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006071 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006072 } else {
junyulaid91e7052020-08-28 13:44:33 +08006073 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006074 }
6075 }
6076 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006077
James Mattis02220e22021-03-13 19:27:21 -08006078 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6079 @Override
6080 public void onReceive(Context context, Intent intent) {
6081 ensureRunningOnConnectivityServiceThread();
6082 switch (intent.getAction()) {
6083 case Intent.ACTION_PACKAGE_ADDED:
6084 case Intent.ACTION_PACKAGE_REMOVED:
6085 case Intent.ACTION_PACKAGE_REPLACED:
6086 onPackageChanged(intent.getData().getSchemeSpecificPart());
6087 break;
6088 default:
6089 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6090 }
6091 }
6092 };
6093
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006094 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006095 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006096
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006097 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006098 public final String name;
6099 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006100 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006101 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006102
lifraf3a3492021-03-10 13:58:14 +08006103 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6104 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006105 this.name = name;
6106 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006107 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006108 mDeathRecipient = deathRecipient;
6109
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006110 if (mDeathRecipient == null) {
6111 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006112 }
6113 }
6114
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006115 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006116 try {
6117 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6118 } catch (RemoteException e) {
6119 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006120 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006121 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006122 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006123
James Mattis4fce5d12020-11-12 15:53:42 -08006124 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6125 for (int i = 0; i < requests.size(); i++) {
6126 ensureNetworkRequestHasType(requests.get(i));
6127 }
6128 }
6129
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006130 private void ensureNetworkRequestHasType(NetworkRequest request) {
6131 if (request.type == NetworkRequest.Type.NONE) {
6132 throw new IllegalArgumentException(
6133 "All NetworkRequests in ConnectivityService must have a type");
6134 }
6135 }
6136
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006137 /**
6138 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006139 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006140 */
James Mattis258ea3c2020-11-15 15:04:40 -08006141 @VisibleForTesting
6142 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006143 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6144 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006145 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006146
James Mattisa076c532020-12-02 14:12:41 -08006147 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6148 void setSatisfier(
6149 @Nullable final NetworkAgentInfo satisfier,
6150 @Nullable final NetworkRequest activeRequest) {
6151 mSatisfier = satisfier;
6152 mActiveRequest = activeRequest;
6153 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006154
James Mattisd31bdfa2020-12-23 16:37:26 -08006155 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006156 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006157 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006158 private NetworkAgentInfo mSatisfier;
6159 NetworkAgentInfo getSatisfier() {
6160 return mSatisfier;
6161 }
6162
6163 // The request in mRequests assigned to a network agent. This is null if none of the
6164 // requests in mRequests can be satisfied. This member has the constraint of only being
6165 // accessible on the handler thread.
6166 @Nullable
6167 private NetworkRequest mActiveRequest;
6168 NetworkRequest getActiveRequest() {
6169 return mActiveRequest;
6170 }
6171
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006172 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006173 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006174 @Nullable
6175 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006176
6177 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006178 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006179 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006180 final int mPid;
6181 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006182 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006183 @Nullable
6184 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006185
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006186 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006187 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006188
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006189 // Effective UID of this request. This is different from mUid when a privileged process
6190 // files a request on behalf of another UID. This UID is used to determine blocked status,
6191 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6192 // maximum limit of registered callbacks per UID.
6193 final int mAsUid;
6194
paulhu48291862021-07-14 14:53:57 +08006195 // Preference order of this request.
6196 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006197
James Mattis3ce3d3c2021-02-09 18:18:28 -08006198 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6199 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6200 // maintained for keying off of. This is only a concern when the original nri
6201 // mNetworkRequests changes which happens currently for apps that register callbacks to
6202 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6203 // that match the per-app default nri that currently tracks the calling app's uid so that
6204 // callbacks are fired at the appropriate time. When the callbacks fire,
6205 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6206 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6207 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6208 @NonNull
6209 private final NetworkRequest mNetworkRequestForCallback;
6210 NetworkRequest getNetworkRequestForCallback() {
6211 return mNetworkRequestForCallback;
6212 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006213
James Mattisd31bdfa2020-12-23 16:37:26 -08006214 /**
6215 * Get the list of UIDs this nri applies to.
6216 */
6217 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006218 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006219 // networkCapabilities.getUids() returns a defensive copy.
6220 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006221 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6222 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006223 }
6224
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006225 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6226 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006227 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006228 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006229 }
6230
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006231 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006232 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006233 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006234 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006235 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006236 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006237 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006238 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006239 mBinder = null;
6240 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006241 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006242 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006243 mPerUidCounter = getRequestCounter(this);
6244 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006245 /**
6246 * Location sensitive data not included in pending intent. Only included in
6247 * {@link NetworkCallback}.
6248 */
6249 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006250 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006251 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006252 }
6253
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006254 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006255 @Nullable final IBinder binder,
6256 @NetworkCallback.Flag int callbackFlags,
6257 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006258 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6259 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006260 }
6261
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006262 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006263 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006264 @Nullable final IBinder binder,
6265 @NetworkCallback.Flag int callbackFlags,
6266 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006267 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006268 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006269 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006270 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006271 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006272 mBinder = binder;
6273 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006274 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006275 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006276 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006277 mPerUidCounter = getRequestCounter(this);
6278 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006279 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006280 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006281 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006282 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006283 }
6284
James Mattis3ce3d3c2021-02-09 18:18:28 -08006285 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6286 @NonNull final List<NetworkRequest> r) {
6287 super();
6288 ensureAllNetworkRequestsHaveType(r);
6289 mRequests = initializeRequests(r);
6290 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006291 final NetworkAgentInfo satisfier = nri.getSatisfier();
6292 if (null != satisfier) {
6293 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6294 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006295 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006296 // As this code creates a new NRI with a new set of requests, figure out which of
6297 // the list of requests should be the active request. It is always the first
6298 // request of the list that can be satisfied by the satisfier since the order of
6299 // requests is a priority order.
6300 // Note even in the presence of a satisfier there may not be an active request,
6301 // when the satisfier is the no-service network.
6302 NetworkRequest activeRequest = null;
6303 for (final NetworkRequest candidate : r) {
6304 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6305 activeRequest = candidate;
6306 break;
6307 }
6308 }
6309 setSatisfier(satisfier, activeRequest);
6310 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006311 mMessenger = nri.mMessenger;
6312 mBinder = nri.mBinder;
6313 mPid = nri.mPid;
6314 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006315 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006316 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006317 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006318 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006319 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006320 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006321 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006322 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006323 }
6324
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006325 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006326 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006327 }
6328
paulhue9913722021-05-26 15:19:20 +08006329 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006330 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006331 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006332 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006333 }
6334
James Mattis2516da32021-01-31 17:06:19 -08006335 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6336 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6337 // false.
6338 boolean isBeingSatisfied() {
6339 return (null != mSatisfier && null != mActiveRequest);
6340 }
6341
James Mattis3d229892020-11-16 16:46:28 -08006342 boolean isMultilayerRequest() {
6343 return mRequests.size() > 1;
6344 }
6345
James Mattis45d81842021-01-10 14:24:24 -08006346 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6347 // Creating a defensive copy to prevent the sender from modifying the list being
6348 // reflected in the return value of this method.
6349 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006350 return Collections.unmodifiableList(tempRequests);
6351 }
6352
James Mattisb1392002021-03-31 13:57:52 -07006353 void linkDeathRecipient() {
6354 if (null != mBinder) {
6355 try {
6356 mBinder.linkToDeath(this, 0);
6357 } catch (RemoteException e) {
6358 binderDied();
6359 }
6360 }
6361 }
6362
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006363 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006364 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006365 try {
6366 mBinder.unlinkToDeath(this, 0);
6367 } catch (NoSuchElementException e) {
6368 // Temporary workaround for b/194394697 pending analysis of additional logs
6369 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6370 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006371 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006372 }
6373
paulhu48291862021-07-14 14:53:57 +08006374 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6375 // Compare two preference orders.
6376 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006377 }
6378
paulhu48291862021-07-14 14:53:57 +08006379 int getPreferenceOrderForNetd() {
6380 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6381 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6382 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006383 }
paulhu48291862021-07-14 14:53:57 +08006384 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006385 }
6386
James Mattis4fce5d12020-11-12 15:53:42 -08006387 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006388 public void binderDied() {
6389 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006390 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006391 // As an immutable collection, mRequests cannot change by the time the
6392 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6393 // is acceptable. Use handleReleaseNetworkRequest and not directly
6394 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6395 // the app already unregistered the request.
6396 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6397 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006398 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006399
James Mattis4fce5d12020-11-12 15:53:42 -08006400 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006401 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006402 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6403 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006404 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006405 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006406 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006407 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006408 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006409 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006410 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006411 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006412 }
6413
Junyu Lai00d92df2022-07-05 11:01:52 +08006414 // Keep backward compatibility since the ServiceSpecificException is used by
6415 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6416 public static class RequestInfoPerUidCounter extends PerUidCounter {
6417 RequestInfoPerUidCounter(int maxCountPerUid) {
6418 super(maxCountPerUid);
6419 }
6420
6421 @Override
6422 public synchronized void incrementCountOrThrow(int uid) {
6423 try {
6424 super.incrementCountOrThrow(uid);
6425 } catch (IllegalStateException e) {
6426 throw new ServiceSpecificException(
6427 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6428 "Uid " + uid + " exceeded its allotted requests limit");
6429 }
6430 }
6431
6432 @Override
6433 public synchronized void decrementCountOrThrow(int uid) {
6434 throw new UnsupportedOperationException("Use decrementCount instead.");
6435 }
6436
6437 public synchronized void decrementCount(int uid) {
6438 try {
6439 super.decrementCountOrThrow(uid);
6440 } catch (IllegalStateException e) {
6441 logwtf("Exception when decrement per uid request count: ", e);
6442 }
6443 }
6444 }
6445
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006446 // This checks that the passed capabilities either do not request a
6447 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006448 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006449 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006450 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006451 throw new SecurityException("Insufficient permissions to request a specific SSID");
6452 }
paulhu1a407652019-03-22 16:35:06 +08006453
6454 if (nc.hasSignalStrength()
6455 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6456 throw new SecurityException(
6457 "Insufficient permissions to request a specific signal strength");
6458 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006459 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006460
junyulai2217bec2021-04-14 23:33:31 +08006461 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006462 enforceNetworkFactoryPermission();
6463 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006464 }
6465
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006466 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006467 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006468 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006469 // mNetworkRequests may contain the same value multiple times in case of
6470 // multilayer requests. It won't matter in this case because the thresholds
6471 // will then be the same and be deduplicated as they enter the `thresholds` set.
6472 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006473 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6474 for (final NetworkRequest req : nri.mRequests) {
6475 if (req.networkCapabilities.hasSignalStrength()
6476 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6477 thresholds.add(req.networkCapabilities.getSignalStrength());
6478 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006479 }
6480 }
6481 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006482 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006483 }
6484
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006485 private void updateSignalStrengthThresholds(
6486 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006487 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006488
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006489 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006490 String detail;
6491 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6492 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6493 } else {
6494 detail = reason;
6495 }
6496 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006497 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006498 }
6499
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006500 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006501 }
6502
Chalard Jeandd421992021-12-16 23:16:02 +09006503 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006504 if (nc == null) {
6505 return;
6506 }
6507 NetworkSpecifier ns = nc.getNetworkSpecifier();
6508 if (ns == null) {
6509 return;
6510 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006511 if (ns instanceof MatchAllNetworkSpecifier) {
6512 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6513 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006514 }
6515
Chalard Jeandd421992021-12-16 23:16:02 +09006516 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006517 ensureValidNetworkSpecifier(nc);
6518 if (nc.isPrivateDnsBroken()) {
6519 throw new IllegalArgumentException("Can't request broken private DNS");
6520 }
Chalard Jeande665262022-02-25 16:12:12 +09006521 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006522 throw new IllegalArgumentException("Can't request access UIDs");
6523 }
lucasline117e2e2019-10-22 18:27:33 +08006524 }
6525
Chalard Jeandd421992021-12-16 23:16:02 +09006526 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6527 ensureListenableCapabilities(nc);
6528 final String badCapability = nc.describeFirstNonRequestableCapability();
6529 if (badCapability != null) {
6530 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6531 }
6532 }
6533
Chiachang Wang3bc52762021-11-25 14:17:57 +08006534 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6535 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006536 private boolean isTargetSdkAtleast(int version, int callingUid,
6537 @NonNull String callingPackageName) {
6538 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006539 final PackageManager pm =
6540 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006541 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006542 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006543 if (callingVersion < version) return false;
6544 } catch (PackageManager.NameNotFoundException e) { }
6545 return true;
6546 }
6547
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006548 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006549 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006550 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006551 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006552 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006553 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006554 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6555 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006556 throw new SecurityException("Insufficient permissions to specify legacy type");
6557 }
markchienfac84a22020-03-18 21:16:15 +08006558 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006559 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006560 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006561 // Privileged callers can track the default network of another UID by passing in a UID.
6562 if (asUid != Process.INVALID_UID) {
6563 enforceSettingsPermission();
6564 } else {
6565 asUid = callingUid;
6566 }
junyulaiad010792021-01-11 16:53:38 +08006567 final NetworkRequest.Type reqType;
6568 try {
6569 reqType = NetworkRequest.Type.values()[reqTypeInt];
6570 } catch (ArrayIndexOutOfBoundsException e) {
6571 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6572 }
6573 switch (reqType) {
6574 case TRACK_DEFAULT:
6575 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006576 // is unused and will be replaced by ones appropriate for the UID (usually, the
6577 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006578 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006579 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006580 enforceAccessPermission();
6581 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006582 case TRACK_SYSTEM_DEFAULT:
6583 enforceSettingsPermission();
6584 networkCapabilities = new NetworkCapabilities(defaultNc);
6585 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006586 case BACKGROUND_REQUEST:
6587 enforceNetworkStackOrSettingsPermission();
6588 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006589 case REQUEST:
6590 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6591 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006592 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006593 // TODO: this is incorrect. We mark the request as metered or not depending on
6594 // the state of the app when the request is filed, but we never change the
6595 // request if the app changes network state. http://b/29964605
6596 enforceMeteredApnPolicy(networkCapabilities);
6597 break;
junyulai1b1c8742021-03-12 20:05:08 +08006598 case LISTEN_FOR_BEST:
6599 enforceAccessPermission();
6600 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6601 break;
junyulaiad010792021-01-11 16:53:38 +08006602 default:
6603 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006604 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006605 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006606 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006607 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006608
junyulai1b1c8742021-03-12 20:05:08 +08006609 // Enforce FOREGROUND if the caller does not have permission to use background network.
6610 if (reqType == LISTEN_FOR_BEST) {
6611 restrictBackgroundRequestForCaller(networkCapabilities);
6612 }
6613
6614 // Set the UID range for this request to the single UID of the requester, unless the
6615 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006616 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6617 // are no visible methods to set the UIDs, an app could use reflection to try and get
6618 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006619 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006620 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6621 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006622
Etan Cohen85000162017-02-05 10:42:27 -08006623 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006624 throw new IllegalArgumentException("Bad timeout specified");
6625 }
Etan Cohen9786d922015-11-18 10:56:15 -08006626
James Mattis3ce3d3c2021-02-09 18:18:28 -08006627 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006628 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006629 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006630 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006631 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006632 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006633
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006634 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6635 // copied from the default request above. (This is necessary to ensure, for example, that
6636 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6637 // changes don't alter request matching.
6638 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6639 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006640 throw new IllegalStateException(
6641 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006642 + networkCapabilities + " vs. " + defaultNc);
6643 }
6644
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006645 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006646 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006647 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006648 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006649 }
6650 return networkRequest;
6651 }
6652
James Mattis3ce3d3c2021-02-09 18:18:28 -08006653 /**
6654 * Return the nri to be used when registering a network request. Specifically, this is used with
6655 * requests registered to track the default request. If there is currently a per-app default
6656 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6657 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006658 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6659 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006660 * @param nr the network request for the nri.
6661 * @param msgr the messenger for the nri.
6662 * @param binder the binder for the nri.
6663 * @param callingAttributionTag the calling attribution tag for the nri.
6664 * @return the nri to register.
6665 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006666 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006667 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006668 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006669 @Nullable String callingAttributionTag) {
6670 final List<NetworkRequest> requests;
6671 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6672 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006673 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006674 } else {
6675 requests = Collections.singletonList(nr);
6676 }
Roshan Pius951c0032020-12-22 15:10:42 -08006677 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006678 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006679 }
6680
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006681 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006682 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006683 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006684 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6685 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6686 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6687 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006688 }
junyulai96bd9fe2022-03-08 17:36:42 +08006689 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006690 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006691 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006692 }
6693 }
6694
fenglu3f357402015-03-20 11:29:56 -07006695 @Override
fenglub00f4882015-04-21 17:12:05 -07006696 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006697 enforceAccessPermission();
6698 NetworkAgentInfo nai = null;
6699 if (network == null) {
6700 return false;
6701 }
6702 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006703 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006704 }
6705 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006706 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006707 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006708 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006709 Integer uidReqs = mBandwidthRequests.get(uid);
6710 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006711 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006712 }
6713 mBandwidthRequests.put(uid, ++uidReqs);
6714 }
fenglu3f357402015-03-20 11:29:56 -07006715 return true;
6716 }
6717 return false;
6718 }
6719
Felipe Leme0a5ae422016-06-20 16:36:29 -07006720 private boolean isSystem(int uid) {
6721 return uid < Process.FIRST_APPLICATION_UID;
6722 }
fenglu3f357402015-03-20 11:29:56 -07006723
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006724 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006725 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006726 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006727 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006728 return;
6729 }
Hugo Benichi39621362017-02-11 17:04:43 +09006730 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6731 // Policy already enforced.
6732 return;
6733 }
paulhuaf50d7d2020-12-24 19:47:34 +08006734 final long ident = Binder.clearCallingIdentity();
6735 try {
6736 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6737 // If UID is restricted, don't allow them to bring up metered APNs.
6738 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6739 }
6740 } finally {
6741 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006742 }
6743 }
6744
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006745 @Override
6746 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006747 PendingIntent operation, @NonNull String callingPackageName,
6748 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006749 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006750 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006751 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006752 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006753 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006754 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006755 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006756 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006757 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006758 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6759 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006760
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006761 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006762 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006763 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6764 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006765 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006766 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6767 nri));
6768 return networkRequest;
6769 }
6770
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006771 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6772 mHandler.sendMessageDelayed(
6773 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006774 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006775 }
6776
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006777 @Override
6778 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006779 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006780 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006781 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006782 }
6783
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006784 // In order to implement the compatibility measure for pre-M apps that call
6785 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6786 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6787 // This ensures it has permission to do so.
6788 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6789 if (nc == null) {
6790 return false;
6791 }
6792 int[] transportTypes = nc.getTransportTypes();
6793 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6794 return false;
6795 }
6796 try {
6797 mContext.enforceCallingOrSelfPermission(
6798 android.Manifest.permission.ACCESS_WIFI_STATE,
6799 "ConnectivityService");
6800 } catch (SecurityException e) {
6801 return false;
6802 }
6803 return true;
6804 }
6805
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006806 @Override
6807 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006808 Messenger messenger, IBinder binder,
6809 @NetworkCallback.Flag int callbackFlags,
6810 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006811 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006812 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6813 enforceAccessPermission();
6814 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006815
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006816 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006817 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006818 Binder.getCallingPid(), callingUid, callingPackageName);
6819 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006820 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6821 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6822 // onLost and onAvailable callbacks when networks move in and out of the background.
6823 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6824 // can't request networks.
6825 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006826 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006827
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006828 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006829 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006830 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006831 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006832 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006833 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006834
6835 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6836 return networkRequest;
6837 }
6838
6839 @Override
6840 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006841 PendingIntent operation, @NonNull String callingPackageName,
6842 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006843 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006844 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006845 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6846 enforceAccessPermission();
6847 }
Chalard Jeandd421992021-12-16 23:16:02 +09006848 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006849 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006850 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006851 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006852 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006853
6854 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006855 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006856 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6857 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006858 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006859
WeiZhang1cc3f172021-06-03 19:02:04 -05006860 mHandler.sendMessage(mHandler.obtainMessage(
6861 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006862 }
6863
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006864 /** Returns the next Network provider ID. */
6865 public final int nextNetworkProviderId() {
6866 return mNextNetworkProviderId.getAndIncrement();
6867 }
6868
Erik Kline0c04b742016-07-07 16:50:58 +09006869 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006870 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006871 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006872 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006873 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006874 }
6875
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006876 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6877 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006878 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6879 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6880 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006881 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006882 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006883 return;
6884 }
6885
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006886 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6887 mNetworkProviderInfos.put(npi.messenger, npi);
6888 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006889 }
6890
6891 @Override
6892 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006893 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006894 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006895 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006896 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006897 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6898 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006899 }
6900
6901 @Override
6902 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006903 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006904 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006905 }
6906
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006907 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006908 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006909 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6910 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006911 Objects.requireNonNull(score);
6912 Objects.requireNonNull(caps);
6913 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006914 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006915 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006916 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6917 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006918 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6919 }
6920
Chalard Jeanbb902a52021-08-18 01:35:19 +09006921 private void updateOfferScore(final NetworkOffer offer) {
6922 final boolean yieldToBadWiFi =
6923 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6924 final NetworkOffer newOffer = new NetworkOffer(
6925 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6926 offer.caps, offer.callback, offer.providerId);
6927 if (offer.equals(newOffer)) return;
6928 handleRegisterNetworkOffer(newOffer);
6929 }
6930
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006931 @Override
6932 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08006933 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006934 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6935 }
6936
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006937 private void handleUnregisterNetworkProvider(Messenger messenger) {
6938 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6939 if (npi == null) {
6940 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006941 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006942 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006943 // Unregister all the offers from this provider
6944 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6945 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006946 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006947 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6948 toRemove.add(noi);
6949 }
6950 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006951 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006952 handleUnregisterNetworkOffer(noi);
6953 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006954 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006955 }
6956
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006957 @Override
James Mattisf7027322020-12-13 16:28:14 -08006958 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006959 if (request.hasTransport(TRANSPORT_TEST)) {
6960 enforceNetworkFactoryOrTestNetworksPermission();
6961 } else {
6962 enforceNetworkFactoryPermission();
6963 }
James Mattisf7027322020-12-13 16:28:14 -08006964 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6965 if (nri != null) {
6966 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6967 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6968 mHandler.post(() -> handleReleaseNetworkRequest(
6969 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6970 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006971 }
6972
Paul Jensen1f567382015-02-13 14:18:39 -05006973 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6974 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006975 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006976 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006977 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006978 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006979 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006980
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006981 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006982 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006983 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006984
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006985 // UID ranges for users that are currently blocked by VPNs.
6986 // This array is accessed and iterated on multiple threads without holding locks, so its
6987 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6988 // (on the handler thread).
6989 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6990
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006991 // Must only be accessed on the handler thread
6992 @NonNull
6993 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6994
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006995 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006996 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006997
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006998 // Current OEM network preferences. This object must only be written to on the handler thread.
6999 // Since it is immutable and always non-null, other threads may read it if they only care
7000 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007001 @NonNull
7002 private OemNetworkPreferences mOemNetworkPreferences =
7003 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007004 // Current per-profile network preferences. This object follows the same threading rules as
7005 // the OEM network preferences above.
7006 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007007 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
7008 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08007009
paulhu51f77dc2021-06-07 02:34:20 +00007010 // A set of UIDs that should use mobile data preferentially if available. This object follows
7011 // the same threading rules as the OEM network preferences above.
7012 @NonNull
7013 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7014
James Mattiscb1e0362021-04-06 17:07:42 -07007015 // OemNetworkPreferences activity String log entries.
7016 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7017 @NonNull
7018 private final LocalLog mOemNetworkPreferencesLogs =
7019 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7020
James Mattis02220e22021-03-13 19:27:21 -08007021 /**
7022 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7023 * @param packageName the package name to check existence of a mapping for.
7024 * @return true if a mapping exists, false otherwise
7025 */
7026 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7027 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7028 }
7029
James Mattise3ef1912020-12-20 11:09:58 -08007030 // The always-on request for an Internet-capable network that apps without a specific default
7031 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007032 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007033 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007034 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007035 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007036 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007037 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007038 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007039
James Mattisd31bdfa2020-12-23 16:37:26 -08007040 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7041 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7042 }
7043
7044 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007045 * Return the default network request currently tracking the given uid.
7046 * @param uid the uid to check.
7047 * @return the NetworkRequestInfo tracking the given uid.
7048 */
7049 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007050 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007051 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007052 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007053 // Checking the first request is sufficient as only multilayer requests will have more
7054 // than one request and for multilayer, all requests will track the same uids.
7055 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007056 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007057 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007058 highestPriorityNri = nri;
7059 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007060 }
7061 }
paulhuaa0743d2021-05-26 21:56:03 +08007062 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007063 }
7064
7065 /**
7066 * Get a copy of the network requests of the default request that is currently tracking the
7067 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007068 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7069 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007070 * @param requestorUid the uid to check the default for.
7071 * @param requestorPackageName the requestor's package name.
7072 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7073 */
7074 @NonNull
7075 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007076 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007077 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007078 getDefaultRequestTrackingUid(asUid).mRequests,
7079 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007080 }
7081
7082 /**
7083 * Copy the given nri's NetworkRequest collection.
7084 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007085 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7086 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007087 * @param requestorUid the uid to set on the copied collection.
7088 * @param requestorPackageName the package name to set on the copied collection.
7089 * @return the copied NetworkRequest collection.
7090 */
7091 @NonNull
7092 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007093 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7094 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007095 final List<NetworkRequest> requests = new ArrayList<>();
7096 for (final NetworkRequest nr : requestsToCopy) {
7097 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007098 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007099 nr.legacyType, nextNetworkRequestId(), nr.type));
7100 }
7101 return requests;
7102 }
7103
7104 @NonNull
7105 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007106 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7107 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007108 // These capabilities are for a TRACK_DEFAULT callback, so:
7109 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7110 // mDefaultRequest and a per-UID default request.
7111 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007112 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007113 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007114 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7115 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007116 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007117 restrictRequestUidsForCallerAndSetRequestorInfo(
7118 netCap, requestorUid, requestorPackageName);
7119 return netCap;
7120 }
7121
7122 /**
7123 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7124 * @param nr the network request to check for equality against.
7125 * @return the nri if one exists, null otherwise.
7126 */
7127 @Nullable
7128 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7129 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7130 if (nri.getNetworkRequestForCallback().equals(nr)) {
7131 return nri;
7132 }
7133 }
7134 return null;
7135 }
7136
7137 /**
7138 * Check if an nri is currently being managed by per-app default networking.
7139 * @param nri the nri to check.
7140 * @return true if this nri is currently being managed by per-app default networking.
7141 */
7142 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7143 // nri.mRequests.get(0) is only different from the original request filed in
7144 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7145 // functionality therefore if these two don't match, it means this particular nri is
7146 // currently being managed by a per-app default.
7147 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7148 }
7149
7150 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007151 * Determine if an nri is a managed default request that disallows default networking.
7152 * @param nri the request to evaluate
7153 * @return true if device-default networking is disallowed
7154 */
7155 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7156 // Check if this nri is a managed default that supports the default network at its
7157 // lowest priority request.
7158 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7159 final NetworkCapabilities lowestPriorityNetCap =
7160 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7161 return isPerAppDefaultRequest(nri)
7162 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7163 lowestPriorityNetCap));
7164 }
7165
Erik Kline05f2b402015-04-30 12:58:40 +09007166 // Request used to optionally keep mobile data active even when higher
7167 // priority networks like Wi-Fi are active.
7168 private final NetworkRequest mDefaultMobileDataRequest;
7169
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007170 // Request used to optionally keep wifi data active even when higher
7171 // priority networks like ethernet are active.
7172 private final NetworkRequest mDefaultWifiRequest;
7173
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007174 // Request used to optionally keep vehicle internal network always active
7175 private final NetworkRequest mDefaultVehicleRequest;
7176
James Mattisd31bdfa2020-12-23 16:37:26 -08007177 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7178 // network with no service. This NAI should never be matched against, nor should any public API
7179 // ever return the associated network. For this reason, this NAI is not in the list of available
7180 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7181 // default requests that don't support using the device default network which will ultimately
7182 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7183 @VisibleForTesting
7184 final NetworkAgentInfo mNoServiceNetwork;
7185
Chalard Jean5b409c72021-02-04 13:12:59 +09007186 // The NetworkAgentInfo currently satisfying the default request, if any.
7187 private NetworkAgentInfo getDefaultNetwork() {
7188 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007189 }
7190
James Mattis2516da32021-01-31 17:06:19 -08007191 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007192 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007193 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7194 // Currently, all network requests will have the same uids therefore checking the first
7195 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007196 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007197 if (null == uids) {
7198 continue;
7199 }
7200 for (final UidRange range : uids) {
7201 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007202 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007203 highestPriorityNri = nri;
7204 }
James Mattis2516da32021-01-31 17:06:19 -08007205 }
7206 }
7207 }
paulhuaa0743d2021-05-26 21:56:03 +08007208 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007209 }
7210
Varun Ananddf569952019-02-06 10:13:38 -08007211 @Nullable
7212 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7213 return nai != null ? nai.network : null;
7214 }
7215
7216 private void ensureRunningOnConnectivityServiceThread() {
7217 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7218 throw new IllegalStateException(
7219 "Not running on ConnectivityService thread: "
7220 + Thread.currentThread().getName());
7221 }
7222 }
7223
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007224 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007225 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7226 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007227 }
7228
Chalard Jean29d06db2018-05-02 21:14:54 +09007229 /**
7230 * Register a new agent with ConnectivityService to handle a network.
7231 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007232 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007233 * @param networkInfo the initial info associated with this network. It can be updated later :
7234 * see {@link #updateNetworkInfo}.
7235 * @param linkProperties the initial link properties of this network. They can be updated
7236 * later : see {@link #updateLinkProperties}.
7237 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007238 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007239 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007240 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007241 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007242 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007243 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007244 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007245 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007246 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7247 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007248 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7249 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7250 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007251 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007252 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007253 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007254 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007255 } else {
7256 enforceNetworkFactoryPermission();
7257 }
7258
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007259 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007260 final long token = Binder.clearCallingIdentity();
7261 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007262 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007263 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007264 } finally {
7265 Binder.restoreCallingIdentity(token);
7266 }
7267 }
7268
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007269 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007270 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007271 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7272 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007273
Chalard Jeandbc46952022-02-02 00:14:18 +09007274 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7275 // and mutate them at any time.
7276 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7277 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7278 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7279
Chalard Jean366c5252022-01-25 18:27:53 +09007280 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007281 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007282 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7283 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007284 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007285 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007286 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007287 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7288 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007289
Chalard Jeandbc46952022-02-02 00:14:18 +09007290 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007291 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007292 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007293 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007294 mDeps.getNetworkStack().makeNetworkMonitor(
7295 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007296 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7297 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007298 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007299 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007300 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007301 }
7302
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007303 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007304 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007305 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007306 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007307 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007308 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7309 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7310 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007311
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007312 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007313
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007314 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007315 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007316 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007317 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007318
7319 try {
7320 networkMonitor.start();
7321 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007322 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007323 }
Chalard Jean366c5252022-01-25 18:27:53 +09007324
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007325 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007326 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007327 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007328 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007329 }
7330
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007331 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7332 @NonNull public final NetworkOffer offer;
7333
7334 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7335 this.offer = offer;
7336 }
7337
7338 @Override
7339 public void binderDied() {
7340 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7341 }
7342 }
7343
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007344 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7345 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7346 if (npi.providerId == providerId) return true;
7347 }
7348 return false;
7349 }
7350
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007351 /**
7352 * Register or update a network offer.
7353 * @param newOffer The new offer. If the callback member is the same as an existing
7354 * offer, it is an update of that offer.
7355 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007356 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007357 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7358 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007359 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007360 // This may actually happen if a provider updates its score or registers and then
7361 // immediately unregisters. The offer would still be in the handler queue, but the
7362 // provider would have been removed.
7363 if (DBG) log("Received offer from an unregistered provider");
7364 return;
7365 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007366 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7367 if (null != existingOffer) {
7368 handleUnregisterNetworkOffer(existingOffer);
7369 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007370 if (DBG) {
7371 // handleUnregisterNetworkOffer has already logged the old offer
7372 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7373 }
7374 } else {
7375 if (DBG) {
7376 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7377 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007378 }
7379 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7380 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007381 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007382 } catch (RemoteException e) {
7383 noi.binderDied();
7384 return;
7385 }
7386 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007387 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007388 }
7389
7390 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7391 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007392 if (DBG) {
7393 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7394 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007395
7396 // If the provider removes the offer and dies immediately afterwards this
7397 // function may be called twice in a row, but the array will no longer contain
7398 // the offer.
7399 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007400 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007401 }
7402
7403 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7404 @NonNull final INetworkOfferCallback callback) {
7405 ensureRunningOnConnectivityServiceThread();
7406 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007407 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007408 }
7409 return null;
7410 }
7411
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007412 /**
7413 * Called when receiving LinkProperties directly from a NetworkAgent.
7414 * Stores into |nai| any data coming from the agent that might also be written to the network's
7415 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7416 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007417 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007418 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007419 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7420 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007421 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007422 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007423 }
7424
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007425 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007426 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007427 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007428
Lorenzo Colittid523d142020-04-01 20:16:30 +09007429 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7430 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7431 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007432 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007433
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007434 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007435
7436 // update filtering rules, need to happen after the interface update so netd knows about the
7437 // new interface (the interface name -> index map becomes initialized)
7438 updateVpnFiltering(newLp, oldLp, networkAgent);
7439
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007440 updateMtu(newLp, oldLp);
7441 // TODO - figure out what to do for clat
7442// for (LinkProperties lp : newLp.getStackedLinks()) {
7443// updateMtu(lp, null);
7444// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007445 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007446 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7447 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007448
Erik Klineb9888902016-04-05 13:30:49 +09007449 updateRoutes(newLp, oldLp, netId);
7450 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007451 // Make sure LinkProperties represents the latest private DNS status.
7452 // This does not need to be done before updateDnses because the
7453 // LinkProperties are not the source of the private DNS configuration.
7454 // updateDnses will fetch the private DNS configuration from DnsManager.
7455 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007456
Chalard Jean5b409c72021-02-04 13:12:59 +09007457 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007458 handleApplyDefaultProxy(newLp.getHttpProxy());
7459 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007460 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007461 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007462
7463 updateWakeOnLan(newLp);
7464
Hai Shalome58bdc62021-01-11 18:45:34 -08007465 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7466 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7467 // does, it needs to be merged here.
7468 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7469 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007470
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007471 // TODO - move this check to cover the whole function
7472 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007473 synchronized (networkAgent) {
7474 networkAgent.linkProperties = newLp;
7475 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007476 // Start or stop DNS64 detection and 464xlat according to network state.
7477 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007478 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007479 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7480 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007481 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007482 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007483
7484 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007485 }
7486
Hai Shalome58bdc62021-01-11 18:45:34 -08007487 /**
7488 * @param naData captive portal data from NetworkAgent
7489 * @param apiData captive portal data from capport API
7490 */
7491 @Nullable
7492 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7493 CaptivePortalData apiData) {
7494 if (naData == null || apiData == null) {
7495 return naData == null ? apiData : naData;
7496 }
7497 final CaptivePortalData.Builder captivePortalBuilder =
7498 new CaptivePortalData.Builder(naData);
7499
7500 if (apiData.isCaptive()) {
7501 captivePortalBuilder.setCaptive(true);
7502 }
7503 if (apiData.isSessionExtendable()) {
7504 captivePortalBuilder.setSessionExtendable(true);
7505 }
7506 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7507 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7508 // otherwise data would be inconsistent. Prefer the capport API info if present,
7509 // as it can generally be refreshed more often.
7510 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7511 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7512 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7513 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7514 // No source has time / bytes remaining information: surface the newest refresh time
7515 // for other fields
7516 captivePortalBuilder.setRefreshTime(
7517 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7518 }
7519
Hai Shalom7c6ab402021-02-04 19:34:06 -08007520 // Prioritize the user portal URL from the network agent if the source is authenticated.
7521 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7522 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7523 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7524 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007525 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007526 // Prioritize the venue information URL from the network agent if the source is
7527 // authenticated.
7528 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7529 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7530 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7531 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007532 }
7533 return captivePortalBuilder.build();
7534 }
7535
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007536 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007537 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007538 // marks on unsupported interfaces is harmless.
7539 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7540 return;
7541 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007542
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007543 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7544 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7545
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007546 // Mask/mark of zero will not detect anything interesting.
7547 // Don't install rules unless both values are nonzero.
7548 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007549 return;
7550 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007551
7552 final String prefix = "iface:" + iface;
7553 try {
7554 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007555 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007556 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007557 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007558 }
7559 } catch (Exception e) {
7560 loge("Exception modifying wakeup packet monitoring: " + e);
7561 }
7562
Joel Scherpelza235a812017-05-22 13:47:41 +09007563 }
7564
Chalard Jean9589e722019-11-19 19:03:53 +09007565 private void updateInterfaces(final @Nullable LinkProperties newLp,
7566 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007567 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007568 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007569 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7570 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007571 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007572 for (final String iface : interfaceDiff.added) {
7573 try {
7574 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007575 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007576 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007577 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7578 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007579 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007580 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007581 }
Paul Jensenbff73492014-04-28 10:33:11 -04007582 }
7583 }
Chalard Jean9589e722019-11-19 19:03:53 +09007584 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007585 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007586 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007587 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007588 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007589 } catch (Exception e) {
7590 loge("Exception removing interface: " + e);
7591 }
7592 }
7593 }
7594
Tyler Weare4314862019-12-05 14:55:30 -08007595 // TODO: move to frameworks/libs/net.
7596 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7597 final String nextHop;
7598
7599 switch (route.getType()) {
7600 case RouteInfo.RTN_UNICAST:
7601 if (route.hasGateway()) {
7602 nextHop = route.getGateway().getHostAddress();
7603 } else {
7604 nextHop = INetd.NEXTHOP_NONE;
7605 }
7606 break;
7607 case RouteInfo.RTN_UNREACHABLE:
7608 nextHop = INetd.NEXTHOP_UNREACHABLE;
7609 break;
7610 case RouteInfo.RTN_THROW:
7611 nextHop = INetd.NEXTHOP_THROW;
7612 break;
7613 default:
7614 nextHop = INetd.NEXTHOP_NONE;
7615 break;
7616 }
7617
7618 final RouteInfoParcel rip = new RouteInfoParcel();
7619 rip.ifName = route.getInterface();
7620 rip.destination = route.getDestination().toString();
7621 rip.nextHop = nextHop;
7622 rip.mtu = route.getMtu();
7623
7624 return rip;
7625 }
7626
Paul Jensene0fd4a82014-08-06 15:51:33 -04007627 /**
7628 * Have netd update routes from oldLp to newLp.
7629 * @return true if routes changed between oldLp and newLp
7630 */
7631 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007632 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007633 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7634 new CompareOrUpdateResult<>(
7635 oldLp != null ? oldLp.getAllRoutes() : null,
7636 newLp != null ? newLp.getAllRoutes() : null,
7637 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007638
7639 // add routes before removing old in case it helps with continuous connectivity
7640
Chalard Jean9dd11612018-06-04 16:52:49 +09007641 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007642 for (RouteInfo route : routeDiff.added) {
7643 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007644 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007645 try {
Tyler Weare4314862019-12-05 14:55:30 -08007646 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007647 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007648 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007649 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007650 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007651 }
7652 }
7653 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007654 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007655 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007656 try {
Tyler Weare4314862019-12-05 14:55:30 -08007657 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007658 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007659 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007660 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007661 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007662 }
7663 }
7664
7665 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007666 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007667 try {
Tyler Weare4314862019-12-05 14:55:30 -08007668 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007669 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007670 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007671 }
7672 }
Tyler Weare4314862019-12-05 14:55:30 -08007673
7674 for (RouteInfo route : routeDiff.updated) {
7675 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7676 try {
7677 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7678 } catch (Exception e) {
7679 loge("Exception in networkUpdateRouteParcel: " + e);
7680 }
7681 }
7682 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7683 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007684 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007685
Erik Klineb9888902016-04-05 13:30:49 +09007686 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7687 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7688 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007689 }
Erik Klineb9888902016-04-05 13:30:49 +09007690
Erik Kline31b4a9e2018-01-11 21:07:29 +09007691 if (DBG) {
7692 final Collection<InetAddress> dnses = newLp.getDnsServers();
7693 log("Setting DNS servers for network " + netId + " to " + dnses);
7694 }
Erik Klineb9888902016-04-05 13:30:49 +09007695 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007696 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007697 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007698 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007699 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007700 }
Erik Kline54e35c02017-04-07 15:29:29 +09007701 }
7702
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007703 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7704 NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007705 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7706 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007707 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7708 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007709
7710 if (!wasFiltering && !needsFiltering) {
7711 // Nothing to do.
7712 return;
7713 }
7714
7715 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7716 // Nothing changed.
7717 return;
7718 }
7719
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007720 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00007721 if (ranges == null || ranges.isEmpty()) {
7722 return;
7723 }
7724
Qingxi Libb8da982020-01-17 17:54:27 -08007725 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007726 // TODO: this create a window of opportunity for apps to receive traffic between the time
7727 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007728 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007729 // old rules are being removed.
7730 if (wasFiltering) {
7731 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7732 }
7733 if (needsFiltering) {
7734 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7735 }
7736 }
7737
Valentin Iftime9fa35092019-09-24 13:32:13 +02007738 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007739 if (mWolSupportedInterfaces == null) {
7740 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007741 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007742 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007743 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7744 }
7745
Luke Huangb913c812018-08-24 20:33:16 +08007746 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007747 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007748 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007749 }
7750 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007751 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007752 }
Luke Huangb913c812018-08-24 20:33:16 +08007753 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007754 }
7755
Chalard Jean62edfd82019-12-02 18:39:29 +09007756 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7757 @NonNull final NetworkCapabilities newNc) {
7758 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7759 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09007760 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09007761 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007762 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007763 } catch (RemoteException | ServiceSpecificException e) {
7764 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007765 }
7766 }
7767 }
7768
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007769 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007770 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007771 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007772 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007773 underlyingNetworks = underlyingNetworksOrDefault(
7774 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007775 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007776 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7777 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007778 // metered if any underlying is metered, or originally declared metered by the agent.
7779 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007780 boolean roaming = false; // roaming if any underlying is roaming
7781 boolean congested = false; // congested if any underlying is congested
7782 boolean suspended = true; // suspended if all underlying are suspended
7783
7784 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007785 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007786 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007787 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007788 for (Network underlyingNetwork : underlyingNetworks) {
7789 final NetworkAgentInfo underlying =
7790 getNetworkAgentInfoForNetwork(underlyingNetwork);
7791 if (underlying == null) continue;
7792
7793 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7794 hadUnderlyingNetworks = true;
7795 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007796 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007797 }
7798
7799 // Merge capabilities of this underlying network. For bandwidth, assume the
7800 // worst case.
7801 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7802 underlyingCaps.getLinkDownstreamBandwidthKbps());
7803 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7804 underlyingCaps.getLinkUpstreamBandwidthKbps());
7805 // If this underlying network is metered, the VPN is metered (it may cost money
7806 // to send packets on this network).
7807 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7808 // If this underlying network is roaming, the VPN is roaming (the billing structure
7809 // is different than the usual, local one).
7810 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7811 // If this underlying network is congested, the VPN is congested (the current
7812 // condition of the network affects the performance of this network).
7813 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7814 // If this network is not suspended, the VPN is not suspended (the VPN
7815 // is able to transfer some data).
7816 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007817 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007818 }
7819 }
7820 if (!hadUnderlyingNetworks) {
7821 // No idea what the underlying networks are; assume reasonable defaults
7822 metered = true;
7823 roaming = false;
7824 congested = false;
7825 suspended = false;
7826 }
7827
lifrade6c2a2021-03-04 14:08:08 +08007828 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007829 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7830 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7831 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7832 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7833 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7834 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007835 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007836 }
7837
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007838 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007839 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7840 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7841 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007842 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007843 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007844 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007845 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007846 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7847 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007848 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007849 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09007850 if (nai.everConnected()
7851 && !nai.isVPN()
7852 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007853 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007854 // does not cause any request (that is not a listen) currently matching that agent to
7855 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007856 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007857 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007858 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007859 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007860 }
7861
Paul Jensen53f08952015-06-16 14:27:36 -04007862 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007863 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09007864 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007865 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007866 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007867 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007868 }
Chalard Jean254bd162022-08-25 13:04:51 +09007869 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007870 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007871 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007872 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007873 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007874 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007875 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007876 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007877 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007878 }
Chalard Jean254bd162022-08-25 13:04:51 +09007879 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08007880 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7881 } else {
7882 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7883 }
lucasline117e2e2019-10-22 18:27:33 +08007884 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007885
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007886 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007887 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7888 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007889 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007890 }
7891
Lorenzo Colittibd079452021-07-02 11:47:57 +09007892 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09007893 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09007894 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007895 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007896 }
7897
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007898 return newNc;
7899 }
7900
Lorenzo Colitti44840702021-01-11 22:27:57 +09007901 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7902 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7903 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7904 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7905 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7906 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7907 if (prevSuspended != suspended) {
7908 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7909 // onResumed have been removed.
7910 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7911 : ConnectivityManager.CALLBACK_RESUMED);
7912 }
7913 if (prevSuspended != suspended || prevRoaming != roaming) {
7914 // updateNetworkInfo will mix in the suspended info from the capabilities and
7915 // take appropriate action for the network having possibly changed state.
7916 updateNetworkInfo(nai, nai.networkInfo);
7917 }
7918 }
7919
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007920 /**
7921 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7922 *
7923 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7924 * capabilities we manage and store in {@code nai}, such as validated status and captive
7925 * portal status)
7926 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7927 * potentially triggers rematches.
7928 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7929 * change.)
7930 *
7931 * @param oldScore score of the network before any of the changes that prompted us
7932 * to call this function.
7933 * @param nai the network having its capabilities updated.
7934 * @param nc the new network capabilities.
7935 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007936 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09007937 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007938 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007939 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007940 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007941 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007942
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007943 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09007944 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007945 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007946
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007947 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007948 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7949 // the change we're processing can't affect any requests, it can only affect the listens
7950 // on this network. We might have been called by rematchNetworkAndRequests when a
7951 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007952 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007953 } else {
7954 // If the requestable capabilities have changed or the score changed, we can't have been
7955 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007956 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007957 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007958 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007959 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007960
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007961 final boolean oldMetered = prevNc.isMetered();
7962 final boolean newMetered = newNc.isMetered();
7963 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007964
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007965 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007966 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7967 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007968 }
junyulaif2c67e42018-08-07 19:50:45 +08007969
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007970 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7971 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007972
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007973 // Report changes that are interesting for network statistics tracking.
7974 if (meteredChanged || roamingChanged) {
7975 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007976 }
7977
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007978 // This network might have been underlying another network. Propagate its capabilities.
7979 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007980
7981 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007982 mDnsManager.updateTransportsForNetwork(
7983 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007984 }
lucaslin53e8a262021-06-08 01:43:59 +08007985
7986 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007987 }
7988
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007989 /** Convenience method to update the capabilities for a given network. */
7990 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007991 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007992 }
7993
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007994 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00007995 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007996 *
7997 * Ingress interface filtering enforces that all apps under the given network can only receive
7998 * packets from the network's interface (and loopback). This is important for VPNs because
7999 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8000 * non-VPN interfaces.
8001 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008002 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008003 * 1. the network is an app VPN (not legacy VPN)
8004 * 2. the VPN does not allow bypass
8005 * 3. the VPN is fully-routed
8006 * 4. the VPN interface is non-null
8007 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008008 * @see INetd#firewallAddUidInterfaceRules
8009 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008010 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008011 @Nullable
8012 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008013 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008014 if (nc == null || lp == null) return null;
8015 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008016 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008017 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008018 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008019 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008020 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008021 && !lp.hasExcludeRoute()) {
8022 return lp.getInterfaceName();
8023 }
8024 return null;
8025 }
8026
8027 /**
8028 * Returns whether we need to set interface filtering rule or not
8029 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008030 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008031 String isolationIface) {
8032 // Allow rules are always needed if VPN isolation is enabled.
8033 if (isolationIface != null) return true;
8034
8035 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8036 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8037 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8038 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008039 }
8040
Chiachang Wang28afaff2020-12-10 22:24:47 +08008041 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8042 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8043 int index = 0;
8044 for (UidRange range : ranges) {
8045 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8046 index++;
8047 }
8048 return stableRanges;
8049 }
8050
Chalard Jeane6c95272022-01-25 21:04:21 +09008051 private static UidRangeParcel[] intsToUidRangeStableParcels(
8052 final @NonNull ArraySet<Integer> uids) {
8053 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8054 int index = 0;
8055 for (int uid : uids) {
8056 stableRanges[index] = new UidRangeParcel(uid, uid);
8057 index++;
8058 }
8059 return stableRanges;
8060 }
8061
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008062 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8063 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8064 for (int i = 0; i < ranges.length; i++) {
8065 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8066 }
8067 return stableRanges;
8068 }
8069
Ken Chen5e65a852020-12-24 12:59:10 +08008070 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8071 int[] exemptUids) {
8072 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8073 try {
8074 mNetd.socketDestroy(ranges, exemptUids);
8075 } catch (Exception e) {
8076 loge("Exception in socket destroy: ", e);
8077 }
8078 }
8079 }
8080
paulhuaa0743d2021-05-26 21:56:03 +08008081 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008082 int[] exemptUids = new int[2];
8083 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8084 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8085 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8086 exemptUids[0] = VPN_UID;
8087 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8088 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8089
8090 maybeCloseSockets(nai, ranges, exemptUids);
8091 try {
8092 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008093 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008094 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008095 } else {
paulhu0e79d952021-06-09 16:11:35 +08008096 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008097 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008098 }
8099 } catch (Exception e) {
8100 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8101 " on netId " + nai.network.netId + ". " + e);
8102 }
8103 maybeCloseSockets(nai, ranges, exemptUids);
8104 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008105
lucaslin53e8a262021-06-08 01:43:59 +08008106 private boolean isProxySetOnAnyDefaultNetwork() {
8107 ensureRunningOnConnectivityServiceThread();
8108 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8109 final NetworkAgentInfo nai = nri.getSatisfier();
8110 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8111 return true;
8112 }
8113 }
8114 return false;
8115 }
8116
8117 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8118 NetworkCapabilities newNc) {
8119 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8120 // the proxy might be changed since the default network satisfied by the apps might also
8121 // changed.
8122 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8123 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008124 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8125 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008126 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008127 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8128 mProxyTracker.sendProxyBroadcast();
8129 }
8130 }
8131
Chalard Jeane6c95272022-01-25 21:04:21 +09008132 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8133 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008134 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8135 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008136 if (null == prevRanges) prevRanges = new ArraySet<>();
8137 if (null == newRanges) newRanges = new ArraySet<>();
8138 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8139
8140 prevRanges.removeAll(newRanges);
8141 newRanges.removeAll(prevRangesCopy);
8142
8143 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008144 // When updating the VPN uid routing rules, add the new range first then remove the old
8145 // range. If old range were removed first, there would be a window between the old
8146 // range being removed and the new range being added, during which UIDs contained
8147 // in both ranges are not subject to any VPN routing rules. Adding new range before
8148 // removing old range works because, unlike the filtering rules below, it's possible to
8149 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008150 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8151 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8152 // [1-5] & [1-2],[4-5] == [3]
8153 // Then we can do:
8154 // maybeCloseSockets([3])
8155 // mNetd.networkAddUidRanges([1-2],[4-5])
8156 // mNetd.networkRemoveUidRanges([1-5])
8157 // maybeCloseSockets([3])
8158 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8159 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008160 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008161 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008162 }
8163 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008164 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008165 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008166 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8167 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008168 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8169 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008170 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008171 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008172 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8173 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8174 // were added first and then newRanges got removed later, there would be only one uid
8175 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8176 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8177 // Note that this is in contrast with the (more robust) update of VPN routing rules
8178 // above, where the addition of new ranges happens before the removal of old ranges.
8179 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8180 // to be removed will never overlap with the new range to be added.
8181 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008182 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8183 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008184 }
8185 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008186 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008187 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008188 } catch (Exception e) {
8189 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008190 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008191 }
8192 }
8193
Chalard Jeande665262022-02-25 16:12:12 +09008194 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008195 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8196 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008197 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8198 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008199 if (prevEmpty && newEmpty) return;
8200
8201 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008202 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008203 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008204 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008205
8206 if (prevUids.equals(newUids)) return;
8207
8208 // This implementation is very simple and vastly faster for sets of Integers than
8209 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8210 // a key computed from the value and has storage for that.
8211 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8212 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8213 toRemove.removeAll(newUids);
8214 toAdd.removeAll(prevUids);
8215
8216 try {
8217 if (!toAdd.isEmpty()) {
8218 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8219 nai.network.netId,
8220 intsToUidRangeStableParcels(toAdd),
8221 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8222 }
8223 if (!toRemove.isEmpty()) {
8224 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8225 nai.network.netId,
8226 intsToUidRangeStableParcels(toRemove),
8227 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8228 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008229 } catch (ServiceSpecificException e) {
8230 // Has the interface disappeared since the network was built ?
8231 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008232 } catch (RemoteException e) {
8233 // Netd died. This usually causes a runtime restart anyway.
8234 }
8235 }
8236
Hugo Benichi9d35b752017-09-01 01:23:32 +00008237 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008238 ensureRunningOnConnectivityServiceThread();
8239
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008240 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008241 // Ignore updates for disconnected networks
8242 return;
8243 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008244 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008245 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008246 + "; created=" + nai.getCreatedTime()
8247 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008248 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008249 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8250 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008251 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008252 }
8253
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008254 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8255 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008256 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008257 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008258 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008259 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8260 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8261 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008262 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8263 // need to be sent as a separate extra.
8264 final NetworkRequest req = nri.isMultilayerRequest()
8265 ? nri.getActiveRequest()
8266 // Non-multilayer listen requests do not have an active request
8267 : nri.mRequests.get(0);
8268 if (req == null) {
8269 Log.wtf(TAG, "No request in NRI " + nri);
8270 }
8271 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008272 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008273 sendIntent(nri.mPendingIntent, intent);
8274 }
8275 // else not handled
8276 }
8277
8278 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8279 mPendingIntentWakeLock.acquire();
8280 try {
8281 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008282 final BroadcastOptions options = BroadcastOptions.makeBasic();
8283 if (SdkLevel.isAtLeastT()) {
8284 // Explicitly disallow the receiver from starting activities, to prevent apps from
8285 // utilizing the PendingIntent as a backdoor to do this.
8286 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8287 }
8288 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8289 null /* requiredPermission */,
8290 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008291 } catch (PendingIntent.CanceledException e) {
8292 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8293 mPendingIntentWakeLock.release();
8294 releasePendingNetworkRequest(pendingIntent);
8295 }
8296 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8297 }
8298
8299 @Override
8300 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8301 String resultData, Bundle resultExtras) {
8302 if (DBG) log("Finished sending " + pendingIntent);
8303 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008304 // Release with a delay so the receiving client has an opportunity to put in its
8305 // own request.
8306 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008307 }
8308
Chalard Jean46bfbf02022-02-02 00:56:25 +09008309 // networkAgent is only allowed to be null if notificationType is
8310 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8311 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008312 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008313 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008314 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008315 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008316 // Default request has no msgr. Also prevents callbacks from being invoked for
8317 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8318 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8319 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008320 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008321 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008322 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008323 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008324 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008325 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008326 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008327 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8328 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008329 }
Roshan Pius951c0032020-12-22 15:10:42 -08008330 final boolean includeLocationSensitiveInfo =
8331 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008332 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008333 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008334 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008335 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008336 networkCapabilitiesRestrictedForCallerPermissions(
8337 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8338 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008339 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008340 nri.mCallingAttributionTag);
8341 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008342 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8343 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008344 // For this notification, arg1 contains the blocked status.
8345 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008346 break;
8347 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008348 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008349 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008350 break;
8351 }
8352 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008353 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008354 final NetworkCapabilities netCap =
8355 networkCapabilitiesRestrictedForCallerPermissions(
8356 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8357 putParcelable(
8358 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008359 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008360 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008361 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008362 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008363 break;
8364 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008365 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008366 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8367 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008368 break;
8369 }
junyulaif2c67e42018-08-07 19:50:45 +08008370 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008371 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008372 msg.arg1 = arg1;
8373 break;
8374 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008375 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008376 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008377 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008378 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008379 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008380 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008381 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008382 }
James Mattis45d81842021-01-10 14:24:24 -08008383 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008384 } catch (RemoteException e) {
8385 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008386 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008387 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008388 }
8389
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008390 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8391 bundle.putParcelable(t.getClass().getSimpleName(), t);
8392 }
8393
Chalard Jean0702f982021-09-16 21:50:07 +09008394 /**
8395 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8396 *
8397 * When a request should be assigned to a new network, it is normally lingered to give
8398 * time for apps to gracefully migrate their connections. When both networks are on the same
8399 * radio, but that radio can't do time-sharing efficiently, this may end up being
8400 * counter-productive because any traffic on the old network may drastically reduce the
8401 * performance of the new network.
8402 * The stack supports a configuration to let modem vendors state that their radio can't
8403 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8404 * from one cell network to another can't be done gracefully.
8405 *
8406 * @param oldNai the old network serving the request
8407 * @param newNai the new network serving the request
8408 * @return whether the switch can be graceful
8409 */
8410 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8411 @NonNull final NetworkAgentInfo newSatisfier) {
8412 if (mCellularRadioTimesharingCapable) return true;
8413 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8414 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8415 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8416 }
8417
Paul Jensenaf94b982014-09-30 15:37:41 -04008418 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008419 if (nai.numRequestNetworkRequests() != 0) {
8420 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8421 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008422 // Ignore listening and track default requests.
8423 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008424 loge("Dead network still had at least " + nr);
8425 break;
8426 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008427 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008428 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008429 }
8430
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008431 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8432 if (oldNetwork == null) {
8433 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8434 return;
8435 }
Chalard Jean49707572019-12-10 21:07:02 +09008436 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008437
8438 // If we get here it means that the last linger timeout for this network expired. So there
8439 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008440 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008441
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008442 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008443 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008444 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008445 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008446 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008447 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008448 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008449 }
8450
James Mattise3ef1912020-12-20 11:09:58 -08008451 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8452 boolean isDefaultChanged = false;
8453 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8454 final NetworkReassignment.RequestReassignment reassignment =
8455 changes.getReassignment(defaultRequestInfo);
8456 if (null == reassignment) {
8457 continue;
8458 }
8459 // reassignment only contains those instances where the satisfying network changed.
8460 isDefaultChanged = true;
8461 // Notify system services of the new default.
8462 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8463 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008464
James Mattise3ef1912020-12-20 11:09:58 -08008465 if (isDefaultChanged) {
8466 // Hold a wakelock for a short time to help apps in migrating to a new default.
8467 scheduleReleaseNetworkTransitionWakelock();
8468 }
8469 }
8470
8471 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8472 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8473 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8474 if (DBG) {
8475 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8476 }
Chalard Jean8e382112019-12-03 20:45:30 +09008477
James Mattisd31bdfa2020-12-23 16:37:26 -08008478 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8479 if (newDefaultNetwork != null) {
8480 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008481 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008482
James Mattisd31bdfa2020-12-23 16:37:26 -08008483 // Set an app level managed default and return since further processing only applies to the
8484 // default network.
8485 if (mDefaultRequest != nri) {
8486 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8487 return;
8488 }
8489
8490 makeDefaultNetwork(newDefaultNetwork);
8491
James Mattise3ef1912020-12-20 11:09:58 -08008492 if (oldDefaultNetwork != null) {
8493 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8494 }
8495 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008496 handleApplyDefaultProxy(null != newDefaultNetwork
8497 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8498 updateTcpBufferSizes(null != newDefaultNetwork
8499 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008500 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008501 }
8502
James Mattisd31bdfa2020-12-23 16:37:26 -08008503 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8504 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8505 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8506 try {
8507 if (VDBG) {
8508 log("Setting default network for " + nri
8509 + " using UIDs " + nri.getUids()
8510 + " with old network " + (oldDefaultNetwork != null
8511 ? oldDefaultNetwork.network().getNetId() : "null")
8512 + " and new network " + (newDefaultNetwork != null
8513 ? newDefaultNetwork.network().getNetId() : "null"));
8514 }
8515 if (nri.getUids().isEmpty()) {
8516 throw new IllegalStateException("makeDefaultForApps called without specifying"
8517 + " any applications to set as the default." + nri);
8518 }
8519 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008520 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008521 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008522 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008523 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008524 }
8525 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008526 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008527 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008528 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008529 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008530 }
8531 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008532 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008533 }
8534 }
8535
8536 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8537 try {
8538 if (null != newDefaultNetwork) {
8539 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8540 } else {
8541 mNetd.networkClearDefault();
8542 }
8543 } catch (RemoteException | ServiceSpecificException e) {
8544 loge("Exception setting default network :" + e);
8545 }
8546 }
8547
Chalard Jean05cbe972019-12-09 11:50:38 +09008548 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008549 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008550 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008551 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008552 processNewlySatisfiedListenRequests(nai);
8553 }
8554
8555 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008556 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8557 if (nri.isMultilayerRequest()) {
8558 continue;
8559 }
8560 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008561 if (!nr.isListen()) continue;
8562 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008563 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008564 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8565 }
8566 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008567 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008568
Chalard Jeancd397a22019-11-22 22:33:33 +09008569 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008570 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8571 if (nri.isMultilayerRequest()) {
8572 continue;
8573 }
8574 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008575 if (!nr.isListen()) continue;
8576 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8577 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008578 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008579 }
8580 }
8581 }
8582
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008583 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008584 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008585 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008586 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008587 @Nullable public final NetworkRequest mOldNetworkRequest;
8588 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008589 @Nullable public final NetworkAgentInfo mOldNetwork;
8590 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008591 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008592 @Nullable final NetworkRequest oldNetworkRequest,
8593 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008594 @Nullable final NetworkAgentInfo oldNetwork,
8595 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008596 mNetworkRequestInfo = networkRequestInfo;
8597 mOldNetworkRequest = oldNetworkRequest;
8598 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008599 mOldNetwork = oldNetwork;
8600 mNewNetwork = newNetwork;
8601 }
Chalard Jean49707572019-12-10 21:07:02 +09008602
8603 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008604 final NetworkRequest requestToShow = null != mNewNetworkRequest
8605 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8606 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008607 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8608 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008609 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008610 }
8611
Chalard Jean46a62372019-12-10 21:25:24 +09008612 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008613
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008614 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008615 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008616 }
8617
8618 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008619 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008620 // The code is never supposed to add two reassignments of the same request. Make
8621 // sure this stays true, but without imposing this expensive check on all
8622 // reassignments on all user devices.
8623 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008624 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008625 throw new IllegalStateException("Trying to reassign ["
8626 + reassignment + "] but already have ["
8627 + existing + "]");
8628 }
8629 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008630 }
Chalard Jean46a62372019-12-10 21:25:24 +09008631 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008632 }
8633
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008634 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008635 // the passed request.
8636 @Nullable
8637 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008638 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008639 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008640 }
8641 return null;
8642 }
Chalard Jean49707572019-12-10 21:07:02 +09008643
8644 public String toString() {
8645 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8646 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008647 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008648 for (final RequestReassignment rr : getRequestReassignments()) {
8649 sj.add(rr.toString());
8650 }
8651 return sj.toString();
8652 }
8653
8654 public String debugString() {
8655 final StringBuilder sb = new StringBuilder();
8656 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008657 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008658 for (final RequestReassignment rr : getRequestReassignments()) {
8659 sb.append("\n ").append(rr);
8660 }
8661 return sb.append("\n").toString();
8662 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008663 }
8664
Chalard Jean24344d72019-12-04 13:32:31 +09008665 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008666 @Nullable final NetworkRequest previousRequest,
8667 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008668 @Nullable final NetworkAgentInfo previousSatisfier,
8669 @Nullable final NetworkAgentInfo newSatisfier,
8670 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008671 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008672 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008673 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008674 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008675 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008676 }
James Mattisa076c532020-12-02 14:12:41 -08008677 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008678 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09008679 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09008680 // If this network switch can't be supported gracefully, the request is not
8681 // lingered. This allows letting go of the network sooner to reclaim some
8682 // performance on the new network, since the radio can't do both at the same
8683 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008684 //
8685 // Also don't linger the request if the old network has been destroyed.
8686 // A destroyed network does not provide actual network connectivity, so
8687 // lingering it is not useful. In particular this ensures that a destroyed
8688 // network is outscored by its replacement,
8689 // then it is torn down immediately instead of being lingered, and any apps that
8690 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09008691 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8692 }
Chalard Jean24344d72019-12-04 13:32:31 +09008693 } else {
8694 if (VDBG || DDBG) log(" accepting network in place of null");
8695 }
junyulai0ac374f2020-12-14 18:41:52 +08008696
8697 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8698 // and immediately satisfies a request then remove the timer. This will happen for
8699 // all networks except in the case of an underlying network for a VCN.
8700 if (newSatisfier.isNascent()) {
8701 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008702 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008703 }
8704
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008705 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008706 newSatisfier.unlingerRequest(newRequest.requestId);
8707 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008708 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008709 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008710 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008711 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008712 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008713 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008714 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008715 }
James Mattisa076c532020-12-02 14:12:41 -08008716 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008717 }
James Mattisa076c532020-12-02 14:12:41 -08008718 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008719 }
8720
James Mattisa076c532020-12-02 14:12:41 -08008721 /**
8722 * This function is triggered when something can affect what network should satisfy what
8723 * request, and it computes the network reassignment from the passed collection of requests to
8724 * network match to the one that the system should now have. That data is encoded in an
8725 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8726 * satisfier.
8727 *
8728 * After the reassignment is computed, it is applied to the state objects.
8729 *
8730 * @param networkRequests the nri objects to evaluate for possible network reassignment
8731 * @return NetworkReassignment listing of proposed network assignment changes
8732 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008733 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008734 private NetworkReassignment computeNetworkReassignment(
8735 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008736 final NetworkReassignment changes = new NetworkReassignment();
8737
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008738 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008739 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008740 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09008741 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008742 }
Chalard Jean857a1712019-12-10 21:08:07 +09008743
James Mattisa076c532020-12-02 14:12:41 -08008744 for (final NetworkRequestInfo nri : networkRequests) {
8745 // Non-multilayer listen requests can be ignored.
8746 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8747 continue;
8748 }
8749 NetworkAgentInfo bestNetwork = null;
8750 NetworkRequest bestRequest = null;
8751 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008752 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008753 // Stop evaluating as the highest possible priority request is satisfied.
8754 if (null != bestNetwork) {
8755 bestRequest = req;
8756 break;
8757 }
8758 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008759 if (null == bestNetwork && isDefaultBlocked(nri)) {
8760 // Remove default networking if disallowed for managed default requests.
8761 bestNetwork = mNoServiceNetwork;
8762 }
8763 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008764 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008765 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008766 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008767 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008768 }
8769 return changes;
8770 }
8771
James Mattisa076c532020-12-02 14:12:41 -08008772 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8773 return new HashSet<>(mNetworkRequests.values());
8774 }
8775
Paul Jensenc88b39b2015-06-16 14:27:36 -04008776 /**
James Mattisa076c532020-12-02 14:12:41 -08008777 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008778 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008779 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008780 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008781 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8782 }
8783
8784 /**
8785 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8786 * being disconnected.
8787 */
8788 private void rematchNetworksAndRequests(
8789 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8790 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008791 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09008792 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008793 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09008794 final long computed = SystemClock.elapsedRealtime();
8795 applyNetworkReassignment(changes, start);
8796 final long applied = SystemClock.elapsedRealtime();
8797 issueNetworkNeeds();
8798 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09008799 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008800 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
8801 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008802 log(changes.debugString());
8803 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008804 // Shorter form, only one line of log
8805 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
8806 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008807 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09008808 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008809
Chalard Jeand7f762d2019-12-10 19:01:29 +09008810 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008811 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008812 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008813
8814 // Since most of the time there are only 0 or 1 background networks, it would probably
8815 // be more efficient to just use an ArrayList here. TODO : measure performance
8816 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8817 for (final NetworkAgentInfo nai : nais) {
8818 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8819 }
8820
Chalard Jeand7f762d2019-12-10 19:01:29 +09008821 // First, update the lists of satisfied requests in the network agents. This is necessary
8822 // because some code later depends on this state to be correct, most prominently computing
8823 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008824 for (final NetworkReassignment.RequestReassignment event :
8825 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008826 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8827 event.mOldNetworkRequest, event.mNewNetworkRequest,
8828 event.mOldNetwork, event.mNewNetwork,
8829 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008830 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008831
James Mattise3ef1912020-12-20 11:09:58 -08008832 // Process default network changes if applicable.
8833 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008834
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008835 // Notify requested networks are available after the default net is switched, but
8836 // before LegacyTypeTracker sends legacy broadcasts
8837 for (final NetworkReassignment.RequestReassignment event :
8838 changes.getRequestReassignments()) {
8839 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008840 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008841 } else {
James Mattisa076c532020-12-02 14:12:41 -08008842 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008843 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008844 }
8845 }
8846
junyulai0ac374f2020-12-14 18:41:52 +08008847 // Update the inactivity state before processing listen callbacks, because the background
8848 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008849 // just yet though, because they have to be sent after the listens are processed to keep
8850 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008851 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008852 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008853 // Rematching may have altered the inactivity state of some networks, so update all
8854 // inactivity timers. updateInactivityState reads the state from the network agent
8855 // and does nothing if the state has not changed : the source of truth is controlled
8856 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8857 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008858 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008859 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008860 }
8861 }
8862
Chalard Jeanb10ab412019-12-11 14:12:30 +09008863 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008864 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008865 // Process listen requests and update capabilities if the background state has
8866 // changed for this network. For consistency with previous behavior, send onLost
8867 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008868 processNewlyLostListenRequests(nai);
8869 if (oldBackground != nai.isBackgroundNetwork()) {
8870 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008871 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008872 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008873 }
8874
junyulai0ac374f2020-12-14 18:41:52 +08008875 for (final NetworkAgentInfo nai : inactiveNetworks) {
8876 // For nascent networks, if connecting with no foreground request, skip broadcasting
8877 // LOSING for backward compatibility. This is typical when mobile data connected while
8878 // wifi connected with mobile data always-on enabled.
8879 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008880 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008881 }
8882
James Mattise3ef1912020-12-20 11:09:58 -08008883 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008884
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008885 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008886 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008887 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008888 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008889 // This network has active linger timers and no requests, but is not
8890 // lingering. Linger it.
8891 //
8892 // One way (the only way?) this can happen if this network is unvalidated
8893 // and became unneeded due to another network improving its score to the
8894 // point where this network will no longer be able to satisfy any requests
8895 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008896 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008897 notifyNetworkLosing(nai, now);
8898 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008899 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008900 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008901 teardownUnneededNetwork(nai);
8902 }
8903 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008904 }
8905 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008906
Chalard Jean62edfd82019-12-02 18:39:29 +09008907 /**
8908 * Apply a change in background state resulting from rematching networks with requests.
8909 *
8910 * During rematch, a network may change background states by starting to satisfy or stopping
8911 * to satisfy a foreground request. Listens don't count for this. When a network changes
8912 * background states, its capabilities need to be updated and callbacks fired for the
8913 * capability change.
8914 *
8915 * @param nai The network that changed background states
8916 */
8917 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8918 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8919 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8920 updateNetworkPermissions(nai, newNc);
8921 nai.getAndSetNetworkCapabilities(newNc);
8922 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8923 }
8924
Chalard Jeanf0344532019-11-19 19:23:38 +09008925 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008926 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008927 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008928 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8929 changes.getReassignment(mDefaultRequest);
8930 final NetworkAgentInfo oldDefaultNetwork =
8931 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8932 final NetworkAgentInfo newDefaultNetwork =
8933 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008934
Chalard Jean5b409c72021-02-04 13:12:59 +09008935 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008936 // Maintain the illusion : since the legacy API only understands one network at a time,
8937 // if the default network changed, apps should see a disconnected broadcast for the
8938 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008939 if (oldDefaultNetwork != null) {
8940 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8941 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008942 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008943 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008944 // The new default network can be newly null if and only if the old default
8945 // network doesn't satisfy the default request any more because it lost a
8946 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09008947 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008948 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008949 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008950 }
8951 }
8952
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008953 // Now that all the callbacks have been sent, send the legacy network broadcasts
8954 // as needed. This is necessary so that legacy requests correctly bind dns
8955 // requests to this network. The legacy users are listening for this broadcast
8956 // and will generally do a dns request so they can ensureRouteToHost and if
8957 // they do that before the callbacks happen they'll use the default network.
8958 //
8959 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8960 // callbacks, but if apps can receive the broadcast before the callback, they still might
8961 // have an inconsistent view of networking.
8962 //
8963 // This *does* introduce a race where if the user uses the new api
8964 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8965 // they may get old info. Reverse this after the old startUsing api is removed.
8966 // This is on top of the multiple intent sequencing referenced in the todo above.
8967 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09008968 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008969 addNetworkToLegacyTypeTracker(nai);
8970 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008971 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008972 }
8973
Chalard Jean0354d8c2021-01-12 10:58:56 +09008974 private void issueNetworkNeeds() {
8975 ensureRunningOnConnectivityServiceThread();
8976 for (final NetworkOfferInfo noi : mNetworkOffers) {
8977 issueNetworkNeeds(noi);
8978 }
8979 }
8980
8981 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8982 ensureRunningOnConnectivityServiceThread();
8983 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8984 informOffer(nri, noi.offer, mNetworkRanker);
8985 }
8986 }
8987
8988 /**
8989 * Inform a NetworkOffer about any new situation of a request.
8990 *
8991 * This function handles updates to offers. A number of events may happen that require
8992 * updating the registrant for this offer about the situation :
8993 * • The offer itself was updated. This may lead the offer to no longer being able
8994 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8995 * or conversely being strengthened enough to beat the satisfier (and therefore
8996 * start being needed)
8997 * • The network satisfying a request changed (including cases where the request
8998 * starts or stops being satisfied). The new network may be a stronger or weaker
8999 * match than the old one, possibly affecting whether the offer is needed.
9000 * • The network satisfying a request updated their score. This may lead the offer
9001 * to no longer be able to beat it if the current satisfier got better, or
9002 * conversely start being a good choice if the current satisfier got weaker.
9003 *
9004 * @param nri The request
9005 * @param offer The offer. This may be an updated offer.
9006 */
9007 private static void informOffer(@NonNull NetworkRequestInfo nri,
9008 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9009 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9010 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009011
9012 // Multi-layer requests have a currently active request, the one being satisfied.
9013 // Since the system will try to bring up a better network than is currently satisfying
9014 // the request, NetworkProviders need to be told the offers matching the requests *above*
9015 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9016 // not needed, and the offer is needed for the active request iff the offer can beat
9017 // the satisfier.
9018 // For non-multilayer requests, the logic above gracefully degenerates to only the
9019 // last case.
9020 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9021 // providers that the offer is needed for this request, until the active request is found.
9022 // In a second phase, deal with the currently active request. In a third phase, inform
9023 // the providers that offer is unneeded for the remaining requests.
9024
9025 // First phase : inform providers of all requests above the active request.
9026 int i;
9027 for (i = 0; nri.mRequests.size() > i; ++i) {
9028 final NetworkRequest request = nri.mRequests.get(i);
9029 if (activeRequest == request) break; // Found the active request : go to phase 2
9030 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9031 // Since this request is higher-priority than the one currently satisfied, if the
9032 // offer can satisfy it, the provider should try and bring up the network for sure ;
9033 // no need to even ask the ranker – an offer that can satisfy is always better than
9034 // no network. Hence tell the provider so unless it already knew.
9035 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9036 offer.onNetworkNeeded(request);
9037 }
9038 }
9039
9040 // Second phase : deal with the active request (if any)
9041 if (null != activeRequest && activeRequest.isRequest()) {
9042 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009043 // If an offer can satisfy the request, it is considered needed if it is currently
9044 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009045 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009046 && satisfier.factorySerialNumber == offer.providerId
9047 && activeRequest.canBeSatisfiedBy(offer.caps);
9048 final boolean newNeeded = currentlyServing
9049 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009050 if (newNeeded != oldNeeded) {
9051 if (newNeeded) {
9052 offer.onNetworkNeeded(activeRequest);
9053 } else {
9054 // The offer used to be able to beat the satisfier. Now it can't.
9055 offer.onNetworkUnneeded(activeRequest);
9056 }
9057 }
9058 }
9059
9060 // Third phase : inform the providers that the offer isn't needed for any request
9061 // below the active one.
9062 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9063 final NetworkRequest request = nri.mRequests.get(i);
9064 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9065 // Since this request is lower-priority than the one currently satisfied, if the
9066 // offer can satisfy it, the provider should not try and bring up the network.
9067 // Hence tell the provider so unless it already knew.
9068 if (offer.neededFor(request)) {
9069 offer.onNetworkUnneeded(request);
9070 }
9071 }
9072 }
9073
Chalard Jean61c79252019-11-07 23:07:32 +09009074 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9075 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9076 NetworkRequest nr = nai.requestAt(i);
9077 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9078 // legacy type tracker filters out repeat adds
9079 mLegacyTypeTracker.add(nr.legacyType, nai);
9080 }
9081 }
9082
9083 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009084 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009085 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9086 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9087 if (nai.isVPN()) {
9088 mLegacyTypeTracker.add(TYPE_VPN, nai);
9089 }
9090 }
9091
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009092 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009093 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009094 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009095 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009096 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009097 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009098
Chalard Jean254bd162022-08-25 13:04:51 +09009099 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009100 // Don't repeat publish.
9101 if (newInetCondition == mDefaultInetConditionPublished) return;
9102
9103 mDefaultInetConditionPublished = newInetCondition;
9104 sendInetConditionBroadcast(nai.networkInfo);
9105 }
9106
Chalard Jeand61375d2020-01-14 22:46:36 +09009107 @NonNull
9108 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9109 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009110 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009111 final boolean suspended =
9112 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9113 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9114 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9115 // state. This is because the network could have been suspended before connecting,
9116 // or it could be disconnecting while being suspended, and in both these cases
9117 // the state should not be overridden. Note that the only detailed state that
9118 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9119 // worry about multiple different substates of CONNECTED.
9120 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9121 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009122 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9123 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9124 // network agent is created, then goes to suspended, then goes out of suspended without
9125 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009126 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009127 ? NetworkInfo.DetailedState.CONNECTED
9128 : NetworkInfo.DetailedState.CONNECTING,
9129 info.getReason(),
9130 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009131 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009132 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009133 return newInfo;
9134 }
9135
9136 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9137 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9138
Erik Kline99f301b2017-02-15 19:59:17 +09009139 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009140 NetworkInfo oldInfo = null;
9141 synchronized (networkAgent) {
9142 oldInfo = networkAgent.networkInfo;
9143 networkAgent.networkInfo = newInfo;
9144 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009145
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009146 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009147 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9148 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009149 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009150
Chalard Jean254bd162022-08-25 13:04:51 +09009151 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009152 && (state == NetworkInfo.State.CONNECTED
9153 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009154
9155 // A network that has just connected has zero requests and is thus a foreground network.
9156 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9157
Luke Huangfdd11f82019-04-09 18:41:49 +08009158 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009159 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009160 // Initialize the network's capabilities to their starting values according to the
9161 // underlying networks. This ensures that the capabilities are correct before
9162 // anything happens to the network.
9163 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009164 }
Chalard Jean254bd162022-08-25 13:04:51 +09009165 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009166 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009167 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01009168 }
9169
Chalard Jean254bd162022-08-25 13:04:51 +09009170 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9171 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009172
lucaslin45e639b2019-04-03 17:09:28 +08009173 // NetworkCapabilities need to be set before sending the private DNS config to
9174 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009175 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9176
Erik Kline9a62f012018-03-21 07:18:33 -07009177 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009178 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9179 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009180
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009181 // If a rate limit has been configured and is applicable to this network (network
9182 // provides internet connectivity), apply it. The tc police filter cannot be attached
9183 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9184 // updateInterfaces -> INetd#networkAddInterface.
9185 // Note: in case of a system server crash, the NetworkController constructor in netd
9186 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9187 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9188 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9189 mIngressRateLimit);
9190 }
9191
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009192 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9193 // command must be sent after updating LinkProperties to maximize chances of
9194 // NetworkMonitor seeing the correct LinkProperties when starting.
9195 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009196 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009197 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009198 }
Chalard Jeand4900722022-02-06 12:25:38 +09009199 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9200 params.networkAgentConfig = networkAgent.networkAgentConfig;
9201 params.networkCapabilities = networkAgent.networkCapabilities;
9202 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9203 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009204 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9205 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9206 // call that would cause a Log.wtf to be emitted from the system_server process, and
9207 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9208 // process to check the interface version, just use an SDK check. NetworkStack will
9209 // always be new enough when running on T+.
9210 if (SdkLevel.isAtLeastT()) {
9211 networkAgent.networkMonitor().notifyNetworkConnected(params);
9212 } else {
9213 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9214 params.networkCapabilities);
9215 }
Chalard Jean4c463082022-09-08 20:52:25 +09009216 scheduleUnvalidatedPrompt(networkAgent.network);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009217
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009218 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9219 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9220 // capabilities, so it only needs to be done once on initial connect, not every time the
9221 // network's capabilities change. Note that we do this before rematching the network,
9222 // so we could decide to tear it down immediately afterwards. That's fine though - on
9223 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9224 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009225 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009226
junyulai0ac374f2020-12-14 18:41:52 +08009227 // Before first rematching networks, put an inactivity timer without any request, this
9228 // allows {@code updateInactivityState} to update the state accordingly and prevent
9229 // tearing down for any {@code unneeded} evaluation in this period.
9230 // Note that the timer will not be rescheduled since the expiry time is
9231 // fixed after connection regardless of the network satisfying other requests or not.
9232 // But it will be removed as soon as the network satisfies a request for the first time.
9233 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9234 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009235 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009236
Paul Jensen05e85ee2014-09-11 11:00:39 -04009237 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009238 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009239
9240 // This has to happen after matching the requests, because callbacks are just requests.
9241 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009242 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009243 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009244 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009245 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009246 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009247 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009248 if (networkAgent.isVPN()) {
9249 // As the active or bound network changes for apps, broadcast the default proxy, as
9250 // apps may need to update their proxy data. This is called after disconnecting from
9251 // VPN to make sure we do not broadcast the old proxy data.
9252 // TODO(b/122649188): send the broadcast only to VPN users.
9253 mProxyTracker.sendProxyBroadcast();
9254 }
Chalard Jean254bd162022-08-25 13:04:51 +09009255 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9256 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009257 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009258 }
9259 }
9260
Chalard Jean28018572020-12-21 18:36:52 +09009261 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009262 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9263 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009264 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009265 }
9266
Erik Kline99f301b2017-02-15 19:59:17 +09009267 // Notify only this one new request of the current state. Transfer all the
9268 // current state by calling NetworkCapabilities and LinkProperties callbacks
9269 // so that callers can be guaranteed to have as close to atomicity in state
9270 // transfer as can be supported by this current API.
9271 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009272 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009273 if (nri.mPendingIntent != null) {
9274 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9275 // Attempt no subsequent state pushes where intents are involved.
9276 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009277 }
Erik Kline99f301b2017-02-15 19:59:17 +09009278
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009279 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009280 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009281 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9282 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9283 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009284 }
9285
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009286 // Notify the requests on this NAI that the network is now lingered.
9287 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009288 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009289 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9290 }
9291
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009292 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9293 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9294 return vpnBlocked
9295 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9296 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9297 }
9298
9299 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9300 if (blockedReasons == BLOCKED_REASON_NONE) {
9301 mUidBlockedReasons.delete(uid);
9302 } else {
9303 mUidBlockedReasons.put(uid, blockedReasons);
9304 }
9305 }
9306
junyulaif2c67e42018-08-07 19:50:45 +08009307 /**
9308 * Notify of the blocked state apps with a registered callback matching a given NAI.
9309 *
9310 * Unlike other callbacks, blocked status is different between each individual uid. So for
9311 * any given nai, all requests need to be considered according to the uid who filed it.
9312 *
9313 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009314 * @param oldMetered True if the previous network capabilities were metered.
9315 * @param newMetered True if the current network capabilities are metered.
9316 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9317 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009318 */
9319 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009320 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9321 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009322
9323 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9324 NetworkRequest nr = nai.requestAt(i);
9325 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009326
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009327 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9328 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9329 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009330 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009331 : oldVpnBlocked;
9332
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009333 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9334 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9335 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009336 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009337 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009338 }
9339 }
9340 }
9341
9342 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009343 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009344 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009345 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009346 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009347 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009348 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009349 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009350 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009351
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009352 final int oldBlockedState = getBlockedState(
9353 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9354 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9355 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009356 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009357 }
junyulaif2c67e42018-08-07 19:50:45 +08009358 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9359 NetworkRequest nr = nai.requestAt(i);
9360 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009361 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009362 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9363 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009364 }
9365 }
9366 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009367 }
9368
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009369 @VisibleForTesting
9370 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009371 // The NetworkInfo we actually send out has no bearing on the real
9372 // state of affairs. For example, if the default connection is mobile,
9373 // and a request for HIPRI has just gone away, we need to pretend that
9374 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9375 // the state to DISCONNECTED, even though the network is of type MOBILE
9376 // and is still connected.
9377 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9378 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009379 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009380 if (state != DetailedState.DISCONNECTED) {
9381 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009382 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009383 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009384 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009385 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9386 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9387 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9388 if (info.isFailover()) {
9389 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9390 nai.networkInfo.setFailover(false);
9391 }
9392 if (info.getReason() != null) {
9393 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9394 }
9395 if (info.getExtraInfo() != null) {
9396 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9397 }
9398 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009399 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009400 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009401 if (newDefaultAgent != null) {
9402 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9403 newDefaultAgent.networkInfo);
9404 } else {
9405 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9406 }
9407 }
9408 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9409 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009410 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009411 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009412 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009413 }
9414 }
9415 }
9416
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009417 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009418 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009419 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009420 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009421 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009422 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9423 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009424 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9425 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009426 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009427 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009428 } else {
9429 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9430 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009431 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009432 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009433
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009434 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9435 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9436 }
9437
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009438 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009439 * Returns the list of all interfaces that could be used by network traffic that does not
9440 * explicitly specify a network. This includes the default network, but also all VPNs that are
9441 * currently connected.
9442 *
9443 * Must be called on the handler thread.
9444 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009445 @NonNull
9446 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009447 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009448 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009449 final Set<Integer> activeNetIds = new ArraySet<>();
9450 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9451 if (nri.isBeingSatisfied()) {
9452 activeNetIds.add(nri.getSatisfier().network().netId);
9453 }
9454 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009455 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009456 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009457 defaultNetworks.add(nai.network);
9458 }
9459 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009460 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009461 }
9462
9463 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009464 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9465 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009466 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009467 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009468 ensureRunningOnConnectivityServiceThread();
9469 String activeIface = null;
9470 LinkProperties activeLinkProperties = getActiveLinkProperties();
9471 if (activeLinkProperties != null) {
9472 activeIface = activeLinkProperties.getInterfaceName();
9473 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009474
junyulai2050bed2021-01-23 09:46:34 +08009475 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009476 try {
junyulaide41fc22021-01-22 22:46:01 +08009477 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009478 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009479 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9480 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009481 } catch (Exception ignored) {
9482 }
9483 }
9484
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009485 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009486 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009487 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009488 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009489 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009490
9491 if (!TextUtils.isEmpty(settingUrl)) {
9492 return settingUrl;
9493 }
9494
9495 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009496 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009497 if (!TextUtils.isEmpty(settingUrl)) {
9498 return settingUrl;
9499 }
9500
9501 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009502 }
9503
9504 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009505 public void startNattKeepalive(Network network, int intervalSeconds,
9506 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009507 enforceKeepalivePermission();
9508 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009509 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009510 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009511 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009512 }
9513
9514 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009515 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009516 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009517 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009518 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009519 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009520 mKeepaliveTracker.startNattKeepalive(
9521 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9522 intervalSeconds, cb,
9523 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9524 } finally {
9525 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9526 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009527 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9528 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009529 }
9530 }
junyulaid05a1922019-01-15 11:32:44 +08009531 }
9532
9533 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009534 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009535 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009536 try {
9537 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009538 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009539 mKeepaliveTracker.startTcpKeepalive(
9540 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9541 } finally {
9542 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9543 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009544 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9545 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009546 }
9547 }
junyulai0835a1e2019-01-08 20:04:33 +08009548 }
9549
9550 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009551 public void stopKeepalive(Network network, int slot) {
9552 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009553 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009554 }
9555
9556 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009557 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009558 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009559
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009560 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009561 final long token = Binder.clearCallingIdentity();
9562 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009563 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9564 UserHandle.getUserHandleForUid(uid))) {
9565 return;
9566 }
9567
Heemin Seogdb8489d2019-06-12 09:21:44 -07009568 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9569 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009570
9571 // Turn airplane mode off
9572 setAirplaneMode(false);
9573
9574 // restore private DNS settings to default mode (opportunistic)
9575 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9576 UserHandle.getUserHandleForUid(uid))) {
9577 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9578 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9579 }
9580
9581 Settings.Global.putString(mContext.getContentResolver(),
9582 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009583 } finally {
9584 Binder.restoreCallingIdentity(token);
9585 }
Stuart Scottd5463642015-04-02 18:00:02 -07009586 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009587
Ricky Wai7097cc92018-01-23 04:09:45 +00009588 @Override
9589 public byte[] getNetworkWatchlistConfigHash() {
9590 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9591 if (nwm == null) {
9592 loge("Unable to get NetworkWatchlistManager");
9593 return null;
9594 }
9595 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9596 return nwm.getWatchlistConfigHash();
9597 }
9598
Hugo Benichibe0c7652016-05-31 16:28:06 +09009599 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009600 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009601 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009602 }
Hugo Benichif4210292017-04-21 15:07:12 +09009603
9604 private static boolean toBool(int encodedBoolean) {
9605 return encodedBoolean != 0; // Only 0 means false.
9606 }
9607
9608 private static int encodeBool(boolean b) {
9609 return b ? 1 : 0;
9610 }
mswest4632928412018-03-12 10:34:34 -07009611
9612 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009613 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9614 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9615 @NonNull String[] args) {
9616 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9617 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009618 }
9619
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009620 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009621 @Override
9622 public int onCommand(String cmd) {
9623 if (cmd == null) {
9624 return handleDefaultCommands(cmd);
9625 }
9626 final PrintWriter pw = getOutPrintWriter();
9627 try {
9628 switch (cmd) {
9629 case "airplane-mode":
9630 final String action = getNextArg();
9631 if ("enable".equals(action)) {
9632 setAirplaneMode(true);
9633 return 0;
9634 } else if ("disable".equals(action)) {
9635 setAirplaneMode(false);
9636 return 0;
9637 } else if (action == null) {
9638 final ContentResolver cr = mContext.getContentResolver();
9639 final int enabled = Settings.Global.getInt(cr,
9640 Settings.Global.AIRPLANE_MODE_ON);
9641 pw.println(enabled == 0 ? "disabled" : "enabled");
9642 return 0;
9643 } else {
9644 onHelp();
9645 return -1;
9646 }
9647 default:
9648 return handleDefaultCommands(cmd);
9649 }
9650 } catch (Exception e) {
9651 pw.println(e);
9652 }
9653 return -1;
9654 }
9655
9656 @Override
9657 public void onHelp() {
9658 PrintWriter pw = getOutPrintWriter();
9659 pw.println("Connectivity service commands:");
9660 pw.println(" help");
9661 pw.println(" Print this help text.");
9662 pw.println(" airplane-mode [enable|disable]");
9663 pw.println(" Turn airplane mode on or off.");
9664 pw.println(" airplane-mode");
9665 pw.println(" Get airplane mode.");
9666 }
9667 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009668
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009669 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009670 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9671 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9672 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009673 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009674 }
9675
he_won.hwang881307a2022-03-15 21:23:52 +09009676 private void maybeUpdateWifiRoamTimestamp(NetworkAgentInfo nai, NetworkCapabilities nc) {
9677 if (nai == null) return;
9678 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
9679 final TransportInfo newInfo = nc.getTransportInfo();
9680 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
9681 return;
9682 }
9683 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +09009684 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +09009685 }
9686 }
9687
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009688 /**
9689 * @param connectionInfo the connection to resolve.
9690 * @return {@code uid} if the connection is found and the app has permission to observe it
9691 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9692 * connection is not found.
9693 */
9694 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009695 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9696 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9697 }
9698
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009699 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009700 connectionInfo.local, connectionInfo.remote);
9701
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009702 if (uid == INVALID_UID) return uid; // Not found.
9703
9704 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9705 // VPN, if any, that applies to the UID that owns the connection.
9706 if (checkNetworkStackPermission()) return uid;
9707
9708 final NetworkAgentInfo vpn = getVpnForUid(uid);
9709 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009710 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009711 return INVALID_UID;
9712 }
9713
9714 return uid;
9715 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009716
Benedict Wong493e04b2018-11-09 14:45:34 -08009717 /**
9718 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9719 *
9720 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9721 */
9722 @Override
9723 public IBinder startOrGetTestNetworkService() {
9724 synchronized (mTNSLock) {
9725 TestNetworkService.enforceTestNetworkPermissions(mContext);
9726
9727 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009728 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009729 }
9730
9731 return mTNS;
9732 }
9733 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009734
Cody Kesting73708bf2019-12-18 10:57:50 -08009735 /**
9736 * Handler used for managing all Connectivity Diagnostics related functions.
9737 *
9738 * @see android.net.ConnectivityDiagnosticsManager
9739 *
9740 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9741 */
9742 @VisibleForTesting
9743 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009744 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9745
Cody Kesting73708bf2019-12-18 10:57:50 -08009746 /**
9747 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9748 * android.net.ConnectivityDiagnosticsManager}.
9749 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9750 * NetworkRequestInfo to be registered
9751 */
9752 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9753
9754 /**
9755 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9756 * android.net.ConnectivityDiagnosticsManager}.
9757 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9758 * arg1 = the uid of the caller
9759 */
9760 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9761
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009762 /**
9763 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009764 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009765 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9766 * NetworkMonitor.
9767 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009768 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009769 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009770
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009771 /**
9772 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9773 * been detected on the network.
9774 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9775 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9776 * arg2 = NetID.
9777 * data = PersistableBundle of extras passed from NetworkMonitor.
9778 */
9779 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9780
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009781 /**
9782 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9783 * the platform. This event will invoke {@link
9784 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9785 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009786 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009787 */
9788 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9789
Cody Kesting73708bf2019-12-18 10:57:50 -08009790 private ConnectivityDiagnosticsHandler(Looper looper) {
9791 super(looper);
9792 }
9793
9794 @Override
9795 public void handleMessage(Message msg) {
9796 switch (msg.what) {
9797 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9798 handleRegisterConnectivityDiagnosticsCallback(
9799 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9800 break;
9801 }
9802 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9803 handleUnregisterConnectivityDiagnosticsCallback(
9804 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9805 break;
9806 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009807 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009808 final ConnectivityReportEvent reportEvent =
9809 (ConnectivityReportEvent) msg.obj;
9810
Aaron Huang959d3642021-01-21 15:47:41 +08009811 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009812 break;
9813 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009814 case EVENT_DATA_STALL_SUSPECTED: {
9815 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009816 final Pair<Long, PersistableBundle> arg =
9817 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009818 if (nai == null) break;
9819
Aaron Huang959d3642021-01-21 15:47:41 +08009820 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009821 break;
9822 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009823 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009824 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009825 break;
9826 }
9827 default: {
9828 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9829 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009830 }
9831 }
9832 }
9833
9834 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9835 @VisibleForTesting
9836 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9837 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9838 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009839 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009840
9841 @VisibleForTesting
9842 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009843 @NonNull IConnectivityDiagnosticsCallback cb,
9844 @NonNull NetworkRequestInfo nri,
9845 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009846 mCb = cb;
9847 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009848 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009849 }
9850
9851 @Override
9852 public void binderDied() {
9853 log("ConnectivityDiagnosticsCallback IBinder died.");
9854 unregisterConnectivityDiagnosticsCallback(mCb);
9855 }
9856 }
9857
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009858 /**
9859 * Class used for sending information from {@link
9860 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9861 */
9862 private static class NetworkTestedResults {
9863 private final int mNetId;
9864 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009865 @Nullable private final String mRedirectUrl;
9866
9867 private NetworkTestedResults(
9868 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9869 mNetId = netId;
9870 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009871 mRedirectUrl = redirectUrl;
9872 }
9873 }
9874
9875 /**
9876 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9877 * ConnectivityDiagnosticsHandler}.
9878 */
9879 private static class ConnectivityReportEvent {
9880 private final long mTimestampMillis;
9881 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009882 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009883
Aaron Huang959d3642021-01-21 15:47:41 +08009884 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9885 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009886 mTimestampMillis = timestampMillis;
9887 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009888 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009889 }
9890 }
9891
Cody Kestingf1120be2020-08-03 18:01:40 -07009892 /**
9893 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9894 * ConnectivityDiagnosticsHandler}.
9895 */
9896 private static class ReportedNetworkConnectivityInfo {
9897 public final boolean hasConnectivity;
9898 public final boolean isNetworkRevalidating;
9899 public final int reporterUid;
9900 @NonNull public final NetworkAgentInfo nai;
9901
9902 private ReportedNetworkConnectivityInfo(
9903 boolean hasConnectivity,
9904 boolean isNetworkRevalidating,
9905 int reporterUid,
9906 @NonNull NetworkAgentInfo nai) {
9907 this.hasConnectivity = hasConnectivity;
9908 this.isNetworkRevalidating = isNetworkRevalidating;
9909 this.reporterUid = reporterUid;
9910 this.nai = nai;
9911 }
9912 }
9913
Cody Kesting73708bf2019-12-18 10:57:50 -08009914 private void handleRegisterConnectivityDiagnosticsCallback(
9915 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9916 ensureRunningOnConnectivityServiceThread();
9917
9918 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009919 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009920 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9921
James Mattis64b8b0f2020-11-24 17:40:49 -08009922 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9923 // confusing for these networks to change when an NRI is satisfied in another layer.
9924 if (nri.isMultilayerRequest()) {
9925 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9926 + "network requests.");
9927 }
9928
Cody Kesting73708bf2019-12-18 10:57:50 -08009929 // This means that the client registered the same callback multiple times. Do
9930 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009931 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009932 if (VDBG) log("Diagnostics callback is already registered");
9933
9934 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9935 // incremented when the NetworkRequestInfo is created as part of
9936 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +08009937 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -08009938 return;
9939 }
9940
Cody Kesting31f1ff62020-03-05 10:46:02 -08009941 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009942
9943 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009944 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009945 } catch (RemoteException e) {
9946 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009947 return;
9948 }
9949
9950 // Once registered, provide ConnectivityReports for matching Networks
9951 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9952 synchronized (mNetworkForNetId) {
9953 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9954 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009955 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9956 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009957 matchingNetworks.add(nai);
9958 }
9959 }
9960 }
9961 for (final NetworkAgentInfo nai : matchingNetworks) {
9962 final ConnectivityReport report = nai.getConnectivityReport();
9963 if (report == null) {
9964 continue;
9965 }
9966 if (!checkConnectivityDiagnosticsPermissions(
9967 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9968 continue;
9969 }
9970
9971 try {
9972 cb.onConnectivityReportAvailable(report);
9973 } catch (RemoteException e) {
9974 // Exception while sending the ConnectivityReport. Move on to the next network.
9975 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009976 }
9977 }
9978
9979 private void handleUnregisterConnectivityDiagnosticsCallback(
9980 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9981 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009982 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009983
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009984 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9985 mConnectivityDiagnosticsCallbacks.remove(iCb);
9986 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009987 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9988 return;
9989 }
9990
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009991 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009992
Cody Kesting70fa2b22020-12-02 12:16:56 -08009993 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9994 // (if the Binder died)
9995 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9996 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009997 return;
9998 }
9999
Cody Kesting46cb1672020-03-04 13:35:20 -080010000 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10001 // incremented when the NetworkRequestInfo is created as part of
10002 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010003 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010004
Cody Kesting31f1ff62020-03-05 10:46:02 -080010005 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010006 }
10007
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010008 private void handleNetworkTestedWithExtras(
10009 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10010 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010011 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010012 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010013 final ConnectivityReport report =
10014 new ConnectivityReport(
10015 reportEvent.mNai.network,
10016 reportEvent.mTimestampMillis,
10017 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010018 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010019 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010020 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010021
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010022 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010023 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010024 for (final IConnectivityDiagnosticsCallback cb : results) {
10025 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010026 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010027 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010028 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010029 }
10030 }
10031 }
10032
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010033 private void handleDataStallSuspected(
10034 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10035 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010036 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010037 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010038 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010039 new DataStallReport(
10040 nai.network,
10041 timestampMillis,
10042 detectionMethod,
10043 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010044 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010045 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010046 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010047 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010048 for (final IConnectivityDiagnosticsCallback cb : results) {
10049 try {
10050 cb.onDataStallSuspected(report);
10051 } catch (RemoteException ex) {
10052 loge("Error invoking onDataStallSuspected", ex);
10053 }
10054 }
10055 }
10056
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010057 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010058 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10059 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10060 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10061
10062 // If the Network is being re-validated as a result of this call to
10063 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10064 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010065 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010066 getMatchingPermissionedCallbacks(
10067 nai,
10068 reportedNetworkConnectivityInfo.isNetworkRevalidating
10069 ? Process.INVALID_UID
10070 : reportedNetworkConnectivityInfo.reporterUid);
10071
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010072 for (final IConnectivityDiagnosticsCallback cb : results) {
10073 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010074 cb.onNetworkConnectivityReported(
10075 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010076 } catch (RemoteException ex) {
10077 loge("Error invoking onNetworkConnectivityReported", ex);
10078 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010079
10080 // If the Network isn't re-validating, also provide the cached report. If there is no
10081 // cached report, the Network is still being validated and a report will be sent once
10082 // validation is complete. Note that networks which never undergo validation will still
10083 // have a cached ConnectivityReport with RESULT_SKIPPED.
10084 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10085 try {
10086 cb.onConnectivityReportAvailable(cachedReport);
10087 } catch (RemoteException ex) {
10088 loge("Error invoking onConnectivityReportAvailable", ex);
10089 }
10090 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010091 }
10092 }
10093
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010094 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010095 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10096 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010097 sanitized.setUids(null);
10098 sanitized.setAdministratorUids(new int[0]);
10099 sanitized.setOwnerUid(Process.INVALID_UID);
10100 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010101 }
10102
Cody Kestingf1120be2020-08-03 18:01:40 -070010103 /**
10104 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10105 *
10106 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10107 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010108 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010109 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010110 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010111 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010112 mConnectivityDiagnosticsCallbacks.entrySet()) {
10113 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10114 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010115
James Mattis64b8b0f2020-11-24 17:40:49 -080010116 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010117 if (!nai.satisfies(nri.mRequests.get(0))) {
10118 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010119 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010120
10121 // UID for this callback must either be:
10122 // - INVALID_UID (which sends callbacks to all UIDs), or
10123 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10124 // notified as a result)
10125 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10126 continue;
10127 }
10128
10129 if (!checkConnectivityDiagnosticsPermissions(
10130 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10131 continue;
10132 }
10133
10134 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010135 }
10136 return results;
10137 }
10138
Cody Kesting7474f672021-05-11 14:22:40 -070010139 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10140 @NonNull NetworkAgentInfo nai) {
10141 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10142 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10143 }
10144
Cody Kesting160ef392021-05-05 13:17:22 -070010145 private boolean hasLocationPermission(String packageName, int uid) {
10146 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10147 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10148 // call in a try-catch.
10149 try {
10150 if (!mLocationPermissionChecker.checkLocationPermission(
10151 packageName, null /* featureId */, uid, null /* message */)) {
10152 return false;
10153 }
10154 } catch (SecurityException e) {
10155 return false;
10156 }
10157
10158 return true;
10159 }
10160
10161 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10162 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010163 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010164 && virtual.networkCapabilities.getOwnerUid() == uid
10165 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10166 return true;
10167 }
10168 }
10169
10170 return false;
10171 }
10172
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010173 @VisibleForTesting
10174 boolean checkConnectivityDiagnosticsPermissions(
10175 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10176 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10177 return true;
10178 }
10179
Cody Kesting160ef392021-05-05 13:17:22 -070010180 // Administrator UIDs also contains the Owner UID
10181 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10182 if (!CollectionUtils.contains(administratorUids, callbackUid)
10183 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010184 return false;
10185 }
10186
Cody Kesting7474f672021-05-11 14:22:40 -070010187 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10188 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010189 }
10190
Cody Kestingd199a9d2019-12-17 12:55:28 -080010191 @Override
10192 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010193 @NonNull IConnectivityDiagnosticsCallback callback,
10194 @NonNull NetworkRequest request,
10195 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010196 Objects.requireNonNull(callback, "callback must not be null");
10197 Objects.requireNonNull(request, "request must not be null");
10198 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10199
Cody Kesting73708bf2019-12-18 10:57:50 -080010200 if (request.legacyType != TYPE_NONE) {
10201 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10202 + " Please use NetworkCapabilities instead.");
10203 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010204 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010205 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010206
10207 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10208 // and administrator uids to be safe.
10209 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010210 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010211
10212 final NetworkRequest requestWithId =
10213 new NetworkRequest(
10214 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10215
10216 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10217 //
10218 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10219 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10220 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010221 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010222 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010223 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010224
10225 mConnectivityDiagnosticsHandler.sendMessage(
10226 mConnectivityDiagnosticsHandler.obtainMessage(
10227 ConnectivityDiagnosticsHandler
10228 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10229 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010230 }
10231
10232 @Override
10233 public void unregisterConnectivityDiagnosticsCallback(
10234 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010235 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010236 mConnectivityDiagnosticsHandler.sendMessage(
10237 mConnectivityDiagnosticsHandler.obtainMessage(
10238 ConnectivityDiagnosticsHandler
10239 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010240 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010241 0,
10242 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010243 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010244
10245 @Override
10246 public void simulateDataStall(int detectionMethod, long timestampMillis,
10247 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010248 Objects.requireNonNull(network, "network must not be null");
10249 Objects.requireNonNull(extras, "extras must not be null");
10250
paulhu3ffffe72021-09-16 10:15:22 +080010251 enforceAnyPermissionOf(mContext,
10252 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010253 android.Manifest.permission.NETWORK_STACK);
10254 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10255 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010256 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010257 }
10258
10259 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010260 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010261 throw new SecurityException("Data Stall simulation is only possible for network "
10262 + "creators");
10263 }
10264
Cody Kesting652e3ec2020-05-21 12:08:21 -070010265 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10266 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10267 // Data Stall information as a DataStallReportParcelable and passing to
10268 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10269 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010270 final DataStallReportParcelable p = new DataStallReportParcelable();
10271 p.timestampMillis = timestampMillis;
10272 p.detectionMethod = detectionMethod;
10273
10274 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10275 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10276 }
10277 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10278 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10279 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10280 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10281 }
10282
Serik Beketayevec8ad212020-12-07 22:43:07 -080010283 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010284 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010285
lucaslin66f44212021-02-23 01:12:55 +080010286 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10287 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010288 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010289 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010290 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010291 }
lucaslin37a16d92021-01-21 19:48:09 +080010292
10293 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010294 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010295 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010296 nai.clatd.interfaceLinkStateChanged(iface, up);
10297 }
10298 }
10299
10300 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010301 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010302 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010303 nai.clatd.interfaceRemoved(iface);
10304 }
lucaslin66f44212021-02-23 01:12:55 +080010305 }
10306 }
10307
lucaslin1a8b4c62021-01-21 02:02:55 +080010308 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10309
10310 /**
10311 * Class used for updating network activity tracking with netd and notify network activity
10312 * changes.
10313 */
10314 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010315 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010316 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010317 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010318 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10319 new RemoteCallbackList<>();
10320 // Indicate the current system default network activity is active or not.
10321 @GuardedBy("mActiveIdleTimers")
10322 private boolean mNetworkActive;
10323 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010324 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010325 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010326
Chalard Jean46bfbf02022-02-02 00:56:25 +090010327 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010328 public final int timeout;
10329 public final int transportType;
10330
10331 IdleTimerParams(int timeout, int transport) {
10332 this.timeout = timeout;
10333 this.transportType = transport;
10334 }
10335 }
10336
10337 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010338 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010339 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010340 mNetd = netd;
10341 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010342 }
10343
lucaslin66f44212021-02-23 01:12:55 +080010344 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10345 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10346 synchronized (mActiveIdleTimers) {
10347 mNetworkActive = active;
10348 // If there are no idle timers, it means that system is not monitoring
10349 // activity, so the system default network for those default network
10350 // unspecified apps is always considered active.
10351 //
10352 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10353 // any network activity change event. Whenever this event is received,
10354 // the mActiveIdleTimers should be always not empty. The legacy behavior
10355 // is no-op. Remove to refer to mNetworkActive only.
10356 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10357 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10358 }
10359 }
10360 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010361
lucaslin1193a5d2021-01-21 02:04:15 +080010362 // The network activity should only be updated from ConnectivityService handler thread
10363 // when mActiveIdleTimers lock is held.
10364 @GuardedBy("mActiveIdleTimers")
10365 private void reportNetworkActive() {
10366 final int length = mNetworkActivityListeners.beginBroadcast();
10367 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10368 try {
10369 for (int i = 0; i < length; i++) {
10370 try {
10371 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10372 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010373 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010374 }
10375 }
10376 } finally {
10377 mNetworkActivityListeners.finishBroadcast();
10378 }
10379 }
10380
10381 @GuardedBy("mActiveIdleTimers")
10382 public void handleReportNetworkActivity() {
10383 synchronized (mActiveIdleTimers) {
10384 reportNetworkActive();
10385 }
10386 }
10387
lucaslin1a8b4c62021-01-21 02:02:55 +080010388 // This is deprecated and only to support legacy use cases.
10389 private int transportTypeToLegacyType(int type) {
10390 switch (type) {
10391 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010392 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010393 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010394 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010395 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010396 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010397 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010398 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010399 default:
10400 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10401 }
10402 return ConnectivityManager.TYPE_NONE;
10403 }
10404
10405 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10406 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10407 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10408 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10409 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10410 final long ident = Binder.clearCallingIdentity();
10411 try {
10412 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10413 RECEIVE_DATA_ACTIVITY_CHANGE,
10414 null /* resultReceiver */,
10415 null /* scheduler */,
10416 0 /* initialCode */,
10417 null /* initialData */,
10418 null /* initialExtra */);
10419 } finally {
10420 Binder.restoreCallingIdentity(ident);
10421 }
10422 }
10423
10424 /**
10425 * Setup data activity tracking for the given network.
10426 *
10427 * Every {@code setupDataActivityTracking} should be paired with a
10428 * {@link #removeDataActivityTracking} for cleanup.
10429 */
10430 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10431 final String iface = networkAgent.linkProperties.getInterfaceName();
10432
10433 final int timeout;
10434 final int type;
10435
10436 if (networkAgent.networkCapabilities.hasTransport(
10437 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10438 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010439 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010440 10);
10441 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10442 } else if (networkAgent.networkCapabilities.hasTransport(
10443 NetworkCapabilities.TRANSPORT_WIFI)) {
10444 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010445 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010446 15);
10447 type = NetworkCapabilities.TRANSPORT_WIFI;
10448 } else {
10449 return; // do not track any other networks
10450 }
10451
lucaslinb961efc2021-01-21 02:03:17 +080010452 updateRadioPowerState(true /* isActive */, type);
10453
lucaslin1a8b4c62021-01-21 02:02:55 +080010454 if (timeout > 0 && iface != null) {
10455 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010456 synchronized (mActiveIdleTimers) {
10457 // Networks start up.
10458 mNetworkActive = true;
10459 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10460 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10461 reportNetworkActive();
10462 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010463 } catch (Exception e) {
10464 // You shall not crash!
10465 loge("Exception in setupDataActivityTracking " + e);
10466 }
10467 }
10468 }
10469
10470 /**
10471 * Remove data activity tracking when network disconnects.
10472 */
10473 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10474 final String iface = networkAgent.linkProperties.getInterfaceName();
10475 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10476
lucaslinb961efc2021-01-21 02:03:17 +080010477 if (iface == null) return;
10478
10479 final int type;
10480 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10481 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10482 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10483 type = NetworkCapabilities.TRANSPORT_WIFI;
10484 } else {
10485 return; // do not track any other networks
10486 }
10487
10488 try {
10489 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010490 synchronized (mActiveIdleTimers) {
10491 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10492 // The call fails silently if no idle timer setup for this interface
10493 mNetd.idletimerRemoveInterface(iface, params.timeout,
10494 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010495 }
lucaslinb961efc2021-01-21 02:03:17 +080010496 } catch (Exception e) {
10497 // You shall not crash!
10498 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010499 }
10500 }
10501
10502 /**
10503 * Update data activity tracking when network state is updated.
10504 */
10505 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10506 NetworkAgentInfo oldNetwork) {
10507 if (newNetwork != null) {
10508 setupDataActivityTracking(newNetwork);
10509 }
10510 if (oldNetwork != null) {
10511 removeDataActivityTracking(oldNetwork);
10512 }
10513 }
lucaslinb961efc2021-01-21 02:03:17 +080010514
10515 private void updateRadioPowerState(boolean isActive, int transportType) {
10516 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10517 switch (transportType) {
10518 case NetworkCapabilities.TRANSPORT_CELLULAR:
10519 bs.reportMobileRadioPowerState(isActive, NO_UID);
10520 break;
10521 case NetworkCapabilities.TRANSPORT_WIFI:
10522 bs.reportWifiRadioPowerState(isActive, NO_UID);
10523 break;
10524 default:
10525 logw("Untracked transport type:" + transportType);
10526 }
10527 }
lucaslin1193a5d2021-01-21 02:04:15 +080010528
10529 public boolean isDefaultNetworkActive() {
10530 synchronized (mActiveIdleTimers) {
10531 // If there are no idle timers, it means that system is not monitoring activity,
10532 // so the default network is always considered active.
10533 //
10534 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10535 // tracking is disabled (negative idle timer value configured), or no active default
10536 // network. In the latter case, this reports active but it should report inactive.
10537 return mNetworkActive || mActiveIdleTimers.isEmpty();
10538 }
10539 }
10540
10541 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10542 mNetworkActivityListeners.register(l);
10543 }
10544
10545 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10546 mNetworkActivityListeners.unregister(l);
10547 }
lucaslin012f7a12021-01-21 02:04:35 +080010548
10549 public void dump(IndentingPrintWriter pw) {
10550 synchronized (mActiveIdleTimers) {
10551 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10552 pw.println("Idle timers:");
10553 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10554 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10555 final IdleTimerParams params = ent.getValue();
10556 pw.print(" timeout="); pw.print(params.timeout);
10557 pw.print(" type="); pw.println(params.transportType);
10558 }
10559 }
10560 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010561 }
James Mattis47db0582021-01-01 14:13:35 -080010562
Daniel Brightf9e945b2020-06-15 16:10:01 -070010563 /**
10564 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10565 *
10566 * @param socketInfo the socket information
10567 * @param callback the callback to register
10568 */
10569 @Override
10570 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10571 @NonNull final IQosCallback callback) {
10572 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10573 if (nai == null || nai.networkCapabilities == null) {
10574 try {
10575 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10576 } catch (final RemoteException ex) {
10577 loge("registerQosCallbackInternal: RemoteException", ex);
10578 }
10579 return;
10580 }
10581 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10582 }
10583
10584 /**
10585 * Register a {@link IQosCallback} with base {@link QosFilter}.
10586 *
10587 * @param filter the filter to register
10588 * @param callback the callback to register
10589 * @param nai the agent information related to the filter's network
10590 */
10591 @VisibleForTesting
10592 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10593 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010594 Objects.requireNonNull(filter, "filter must be non-null");
10595 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010596
10597 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010598 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10599 // on this network is unregistered when the app loses permission or b) no QoS
10600 // callbacks are sent for restricted networks unless the app currently has permission
10601 // to access restricted networks.
10602 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010603 }
10604 mQosCallbackTracker.registerCallback(callback, filter, nai);
10605 }
10606
10607 /**
10608 * Unregisters the given callback.
10609 *
10610 * @param callback the callback to unregister
10611 */
10612 @Override
10613 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010614 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010615 mQosCallbackTracker.unregisterCallback(callback);
10616 }
James Mattis47db0582021-01-01 14:13:35 -080010617
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010618 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
10619 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
10620 // Enterprise device can be fully managed like device owner and such use case
10621 // also should be supported. Calling app check for work profile and fully managed device
10622 // is already done in DevicePolicyManager.
10623 // This check is an extra caution to be sure device is fully managed or not.
10624 final UserManager um = mContext.getSystemService(UserManager.class);
10625 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
10626 if (um.isManagedProfile(profile.getIdentifier())) {
10627 return true;
10628 }
10629 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
10630 return false;
10631 }
10632
James Mattis45d81842021-01-10 14:24:24 -080010633 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010634 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010635 *
10636 * See the documentation for the individual preferences for a description of the supported
10637 * behaviors.
10638 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010639 * @param profile If the device owner is set, any profile is allowed.
10640 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010641 * @param preferences the list of profile network preferences for the
10642 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010643 * @param listener an optional listener to listen for completion of the operation.
10644 */
10645 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010646 public void setProfileNetworkPreferences(
10647 @NonNull final UserHandle profile,
10648 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010649 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010650 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010651 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010652
10653 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010654 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
10655 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
10656 .build();
10657 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010658 }
10659
paulhu3ffffe72021-09-16 10:15:22 +080010660 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010661 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010662 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010663 }
10664 if (profile.getIdentifier() < 0) {
10665 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10666 + "UserHandle.CURRENT not supported)");
10667 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010668 if (!isNetworkPreferenceAllowedForProfile(profile)) {
10669 throw new IllegalArgumentException("Profile must be a managed profile "
10670 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010671 }
paulhuaa0743d2021-05-26 21:56:03 +080010672
Chalard Jean46bfbf02022-02-02 00:56:25 +090010673 final List<ProfileNetworkPreferenceList.Preference> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010674 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010675 for (final ProfileNetworkPreference preference : preferences) {
10676 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010677 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010678 switch (preference.getPreference()) {
10679 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10680 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010681 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010682 if (preference.getPreferenceEnterpriseId() != 0) {
10683 throw new IllegalArgumentException(
10684 "Invalid enterprise identifier in setProfileNetworkPreferences");
10685 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010686 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010687 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10688 allowFallback = false;
10689 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010690 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010691 // This code is needed even though there is a check later on,
10692 // because isRangeAlreadyInPreferenceList assumes that every preference
10693 // has a UID list.
10694 if (hasDefaultPreference) {
10695 throw new IllegalArgumentException(
10696 "Default profile preference should not be set along with other "
10697 + "preference");
10698 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010699 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10700 throw new IllegalArgumentException(
10701 "Invalid enterprise identifier in setProfileNetworkPreferences");
10702 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010703 final Set<UidRange> uidRangeSet =
10704 getUidListToBeAppliedForNetworkPreference(profile, preference);
10705 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10706 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10707 } else {
10708 throw new IllegalArgumentException(
10709 "Overlapping uid range in setProfileNetworkPreferences");
10710 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010711 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010712 nc.addEnterpriseId(
10713 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010714 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10715 break;
10716 default:
10717 throw new IllegalArgumentException(
10718 "Invalid preference in setProfileNetworkPreferences");
10719 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010720 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10721 profile, nc, allowFallback));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010722 if (hasDefaultPreference && preferenceList.size() > 1) {
10723 throw new IllegalArgumentException(
10724 "Default profile preference should not be set along with other preference");
10725 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010726 }
10727 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010728 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010729 }
10730
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010731 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10732 @NonNull final UserHandle profile,
10733 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10734 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080010735 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
10736 profileNetworkPreference.getIncludedUids());
10737
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010738 if (uidRangeSet.size() > 0) {
10739 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10740 throw new IllegalArgumentException(
10741 "Allow uid range is outside the uid range of profile.");
10742 }
10743 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080010744 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010745 profileNetworkPreference.getExcludedUids());
10746 if (disallowUidRangeSet.size() > 0) {
10747 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10748 throw new IllegalArgumentException(
10749 "disallow uid range is outside the uid range of profile.");
10750 }
10751 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10752 disallowUidRangeSet);
10753 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010754 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010755 uidRangeSet.add(profileUids);
10756 }
10757 }
10758 return uidRangeSet;
10759 }
10760
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010761 private boolean isEnterpriseIdentifierValid(
10762 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010763 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010764 return true;
10765 }
10766 return false;
10767 }
10768
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010769 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010770 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010771 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010772 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010773 // The NRI for a user should contain the request for capabilities.
10774 // If fallback to default network is needed then NRI should include
10775 // the request for the default network. Create an image of it to
10776 // have the correct UIDs in it (also a request can only be part of one NRI, because
10777 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010778 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10779 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010780 if (pref.allowFallback) {
10781 nrs.add(createDefaultInternetRequestForTransport(
10782 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10783 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010784 if (VDBG) {
10785 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10786 pref.capabilities.getUids()));
10787 }
10788
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010789 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010790 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010791 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010792 result.add(nri);
10793 }
10794 return result;
10795 }
10796
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010797 /**
10798 * Compare if the given UID range sets have the same UIDs.
10799 *
10800 */
10801 private boolean isRangeAlreadyInPreferenceList(
10802 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10803 @NonNull Set<UidRange> uidRangeSet) {
10804 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10805 return false;
10806 }
10807 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10808 if (UidRangeUtils.doesRangeSetOverlap(
10809 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10810 return true;
10811 }
10812 }
10813 return false;
10814 }
10815
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010816 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010817 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010818 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010819 /*
10820 * handleSetProfileNetworkPreference is always called for single user.
10821 * preferenceList only contains preferences for different uids within the same user
10822 * (enforced by getUidListToBeAppliedForNetworkPreference).
10823 * Clear all the existing preferences for the user before applying new preferences.
10824 *
10825 */
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010826 mProfileNetworkPreferences = mProfileNetworkPreferences.withoutUser(
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010827 preferenceList.get(0).user);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010828 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010829 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10830 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010831
paulhu74128522021-09-28 02:29:03 +000010832 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10833 addPerAppDefaultNetworkRequests(
10834 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai31d38bf2022-07-04 17:28:39 +080010835
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010836 // Finally, rematch.
10837 rematchAllNetworksAndRequests();
10838
10839 if (null != listener) {
10840 try {
10841 listener.onComplete();
10842 } catch (RemoteException e) {
10843 loge("Listener for setProfileNetworkPreference has died");
10844 }
10845 }
10846 }
10847
paulhu51f77dc2021-06-07 02:34:20 +000010848 @VisibleForTesting
10849 @NonNull
10850 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10851 @NonNull final Set<Integer> uids) {
10852 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10853 if (uids.size() == 0) {
10854 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10855 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10856 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10857 return nris;
10858 }
10859
10860 final List<NetworkRequest> requests = new ArrayList<>();
10861 // The NRI should be comprised of two layers:
10862 // - The request for the mobile network preferred.
10863 // - The request for the default network, for fallback.
10864 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010865 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010866 requests.add(createDefaultInternetRequestForTransport(
10867 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10868 final Set<UidRange> ranges = new ArraySet<>();
10869 for (final int uid : uids) {
10870 ranges.add(new UidRange(uid, uid));
10871 }
10872 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010873 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010874 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010875 return nris;
10876 }
10877
10878 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010879 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010880 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10881 addPerAppDefaultNetworkRequests(
10882 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010883 // Finally, rematch.
10884 rematchAllNetworksAndRequests();
10885 }
10886
Patrick Rohr2857ac42022-01-21 14:58:16 +010010887 private void handleIngressRateLimitChanged() {
10888 final long oldIngressRateLimit = mIngressRateLimit;
10889 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
10890 mContext);
10891 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
10892 if (canNetworkBeRateLimited(networkAgent)) {
10893 // If rate limit has previously been enabled, remove the old limit first.
10894 if (oldIngressRateLimit >= 0) {
10895 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
10896 }
10897 if (mIngressRateLimit >= 0) {
10898 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10899 mIngressRateLimit);
10900 }
10901 }
10902 }
10903 }
10904
10905 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090010906 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
10907 if (!SdkLevel.isAtLeastT()) return false;
10908
Patrick Rohrff3b3f82022-02-09 15:15:52 +010010909 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
10910 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
10911 // internet connectivity can be rate limited.
10912 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
10913 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010010914 return false;
10915 }
10916
10917 final String iface = networkAgent.linkProperties.getInterfaceName();
10918 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010010919 // This may happen in tests, but if there is no interface then there is nothing that
10920 // can be rate limited.
10921 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010010922 return false;
10923 }
10924 return true;
10925 }
10926
James Mattis45d81842021-01-10 14:24:24 -080010927 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010928 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10929 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010930 }
10931
10932 /**
10933 * Used by automotive devices to set the network preferences used to direct traffic at an
10934 * application level as per the given OemNetworkPreferences. An example use-case would be an
10935 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10936 * vehicle via a particular network.
10937 *
10938 * Calling this will overwrite the existing preference.
10939 *
James Mattisda32cfe2021-01-26 16:23:52 -080010940 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010941 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010942 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010943 */
James Mattis47db0582021-01-01 14:13:35 -080010944 @Override
James Mattis45d81842021-01-10 14:24:24 -080010945 public void setOemNetworkPreference(
10946 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010947 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010948
James Mattisfa270db2021-05-31 17:11:10 -070010949 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10950 // Only bypass the permission/device checks if this is a valid test request.
10951 if (isValidTestOemNetworkPreference(preference)) {
10952 enforceManageTestNetworksPermission();
10953 } else {
10954 enforceAutomotiveDevice();
10955 enforceOemNetworkPreferencesPermission();
10956 validateOemNetworkPreferences(preference);
10957 }
James Mattis45d81842021-01-10 14:24:24 -080010958
James Mattis45d81842021-01-10 14:24:24 -080010959 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10960 new Pair<>(preference, listener)));
10961 }
10962
James Mattisfa270db2021-05-31 17:11:10 -070010963 /**
10964 * Check the validity of an OEM network preference to be used for testing purposes.
10965 * @param preference the preference to validate
10966 * @return true if this is a valid OEM network preference test request.
10967 */
10968 private boolean isValidTestOemNetworkPreference(
10969 @NonNull final OemNetworkPreferences preference) {
10970 // Allow for clearing of an existing OemNetworkPreference used for testing.
10971 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10972 // changes after this check is complete. This is an unlikely scenario as calling of this API
10973 // is controlled by the OEM therefore the added complexity is not worth adding given those
10974 // circumstances. That said, it is an edge case to be aware of hence this comment.
10975 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10976 && isTestOemNetworkPreference(mOemNetworkPreferences);
10977 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10978 }
10979
10980 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10981 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10982 return prefMap.size() == 1
10983 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10984 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10985 }
10986
James Mattis45d81842021-01-10 14:24:24 -080010987 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10988 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10989 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010990 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10991 throw new IllegalArgumentException(
10992 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10993 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010994 }
10995 }
10996 }
10997
10998 private void handleSetOemNetworkPreference(
10999 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011000 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011001 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11002 if (DBG) {
11003 log("set OEM network preferences :" + preference.toString());
11004 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011005
James Mattiscb1e0362021-04-06 17:07:42 -070011006 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011007 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11008 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11009 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011010 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011011
11012 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011013 try {
11014 listener.onComplete();
11015 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011016 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011017 }
James Mattis45d81842021-01-10 14:24:24 -080011018 }
11019 }
11020
paulhu74128522021-09-28 02:29:03 +000011021 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011022 // Skip the requests which are set by other network preference. Because the uid range rules
11023 // should stay in netd.
11024 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011025 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011026 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011027 }
11028
James Mattis3ce3d3c2021-02-09 18:18:28 -080011029 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11030 ensureRunningOnConnectivityServiceThread();
11031 mDefaultNetworkRequests.addAll(nris);
11032 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11033 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011034 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011035 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11036 nrisToRegister.addAll(
11037 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11038 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011039 }
11040
11041 /**
11042 * All current requests that are tracking the default network need to be assessed as to whether
11043 * or not the current set of per-application default requests will be changing their default
11044 * network. If so, those requests will need to be updated so that they will send callbacks for
11045 * default network changes at the appropriate time. Additionally, those requests tracking the
11046 * default that were previously updated by this flow will need to be reassessed.
11047 * @return the nris which will need to be updated.
11048 */
11049 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11050 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11051 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11052 // same nri in the map's values for each of its NetworkRequest objects.
11053 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011054 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011055 // Include this nri if it is currently being tracked.
11056 if (isPerAppTrackedNri(nri)) {
11057 defaultCallbackRequests.add(nri);
11058 continue;
11059 }
11060 // We only track callbacks for requests tracking the default.
11061 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11062 continue;
11063 }
11064 // Include this nri if it will be tracked by the new per-app default requests.
11065 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011066 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011067 if (isNriGoingToBeTracked) {
11068 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011069 }
11070 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011071 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011072 }
11073
James Mattis3ce3d3c2021-02-09 18:18:28 -080011074 /**
11075 * Create nris for those network requests that are currently tracking the default network that
11076 * are being controlled by a per-application default.
11077 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11078 * foundation when creating the nri. Important items include the calling uid's original
11079 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11080 * requests are assumed to have already been validated as needing to be updated.
11081 * @return the Set of nris to use when registering network requests.
11082 */
11083 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11084 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11085 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11086 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11087 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011088 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011089
Chalard Jean9473c982021-07-29 20:03:04 +090011090 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011091 if (trackingNri == mDefaultRequest) {
11092 callbackRequestsToRegister.add(new NetworkRequestInfo(
11093 callbackRequest,
11094 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11095 continue;
11096 }
11097
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011098 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011099 callbackRequestsToRegister.add(new NetworkRequestInfo(
11100 callbackRequest,
11101 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011102 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011103 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011104 }
11105 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011106 }
11107
Chalard Jean17215832021-03-01 14:06:28 +090011108 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11109 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011110 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011111 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011112 }
11113 }
11114
James Mattis45d81842021-01-10 14:24:24 -080011115 /**
11116 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11117 */
11118 @VisibleForTesting
11119 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011120 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011121 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011122 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011123 final SparseArray<Set<Integer>> uids =
11124 createUidsFromOemNetworkPreferences(preference);
11125 for (int i = 0; i < uids.size(); i++) {
11126 final int key = uids.keyAt(i);
11127 final Set<Integer> value = uids.valueAt(i);
11128 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11129 // No need to add an nri without any requests.
11130 if (0 == nri.mRequests.size()) {
11131 continue;
11132 }
11133 nris.add(nri);
11134 }
11135
11136 return nris;
11137 }
11138
11139 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11140 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011141 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011142 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011143 final List<UserHandle> users =
11144 mContext.getSystemService(UserManager.class).getUserHandles(true);
11145 if (null == users || users.size() == 0) {
11146 if (VDBG || DDBG) {
11147 log("No users currently available for setting the OEM network preference.");
11148 }
James Mattisb6b6a432021-06-01 22:30:36 -070011149 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011150 }
James Mattis45d81842021-01-10 14:24:24 -080011151 for (final Map.Entry<String, Integer> entry :
11152 preference.getNetworkPreferences().entrySet()) {
11153 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011154 // Add the rules for all users as this policy is device wide.
11155 for (final UserHandle user : users) {
11156 try {
11157 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11158 if (!prefToUids.contains(pref)) {
11159 prefToUids.put(pref, new ArraySet<>());
11160 }
11161 prefToUids.get(pref).add(uid);
11162 } catch (PackageManager.NameNotFoundException e) {
11163 // Although this may seem like an error scenario, it is ok that uninstalled
11164 // packages are sent on a network preference as the system will watch for
11165 // package installations associated with this network preference and update
11166 // accordingly. This is done to minimize race conditions on app install.
11167 continue;
James Mattis45d81842021-01-10 14:24:24 -080011168 }
James Mattis45d81842021-01-10 14:24:24 -080011169 }
11170 }
James Mattisb6b6a432021-06-01 22:30:36 -070011171 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011172 }
11173
11174 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11175 @OemNetworkPreferences.OemNetworkPreference final int preference,
11176 @NonNull final Set<Integer> uids) {
11177 final List<NetworkRequest> requests = new ArrayList<>();
11178 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11179 switch (preference) {
11180 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11181 requests.add(createUnmeteredNetworkRequest());
11182 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011183 requests.add(createDefaultInternetRequestForTransport(
11184 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011185 break;
11186 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11187 requests.add(createUnmeteredNetworkRequest());
11188 requests.add(createOemPaidNetworkRequest());
11189 break;
11190 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11191 requests.add(createOemPaidNetworkRequest());
11192 break;
11193 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11194 requests.add(createOemPrivateNetworkRequest());
11195 break;
James Mattisfa270db2021-05-31 17:11:10 -070011196 case OEM_NETWORK_PREFERENCE_TEST:
11197 requests.add(createUnmeteredNetworkRequest());
11198 requests.add(createTestNetworkRequest());
11199 requests.add(createDefaultRequest());
11200 break;
11201 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11202 requests.add(createTestNetworkRequest());
11203 break;
James Mattis45d81842021-01-10 14:24:24 -080011204 default:
11205 // This should never happen.
11206 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11207 + " called with invalid preference of " + preference);
11208 }
11209
James Mattisfa270db2021-05-31 17:11:10 -070011210 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011211 for (final int uid : uids) {
11212 ranges.add(new UidRange(uid, uid));
11213 }
11214 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011215 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011216 }
11217
11218 private NetworkRequest createUnmeteredNetworkRequest() {
11219 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11220 .addCapability(NET_CAPABILITY_NOT_METERED)
11221 .addCapability(NET_CAPABILITY_VALIDATED);
11222 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11223 }
11224
11225 private NetworkRequest createOemPaidNetworkRequest() {
11226 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11227 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11228 .addCapability(NET_CAPABILITY_OEM_PAID)
11229 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11230 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11231 }
11232
11233 private NetworkRequest createOemPrivateNetworkRequest() {
11234 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11235 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11236 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11237 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11238 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11239 }
11240
11241 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011242 final NetworkCapabilities netcap = new NetworkCapabilities();
11243 netcap.addCapability(NET_CAPABILITY_INTERNET);
11244 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11245 return netcap;
11246 }
11247
11248 private NetworkRequest createTestNetworkRequest() {
11249 final NetworkCapabilities netcap = new NetworkCapabilities();
11250 netcap.clearAll();
11251 netcap.addTransportType(TRANSPORT_TEST);
11252 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011253 }
James Mattis47db0582021-01-01 14:13:35 -080011254 }
markchien738ad912021-12-09 18:15:45 +080011255
11256 @Override
11257 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11258 enforceNetworkStackOrSettingsPermission();
11259
11260 try {
11261 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011262 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011263 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011264 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011265 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011266 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011267 throw new IllegalStateException(e);
11268 }
11269 }
11270
11271 @Override
11272 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11273 enforceNetworkStackOrSettingsPermission();
11274
11275 try {
11276 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011277 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011278 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011279 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011280 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011281 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011282 throw new IllegalStateException(e);
11283 }
11284 }
markchiene1561fa2021-12-09 22:00:56 +080011285
11286 @Override
markchien3c04e662022-03-22 16:29:56 +080011287 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011288 enforceNetworkStackOrSettingsPermission();
11289
markchien3c04e662022-03-22 16:29:56 +080011290 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11291 int firewallRule = getFirewallRuleType(chain, rule);
11292
11293 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11294 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11295 }
11296
markchiene1561fa2021-12-09 22:00:56 +080011297 try {
markchien3c04e662022-03-22 16:29:56 +080011298 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011299 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011300 throw new IllegalStateException(e);
11301 }
11302 }
markchien98a6f952022-01-13 23:43:53 +080011303
markchien3c04e662022-03-22 16:29:56 +080011304 private int getFirewallRuleType(int chain, int rule) {
11305 final int defaultRule;
11306 switch (chain) {
11307 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011308 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11309 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011310 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011311 defaultRule = FIREWALL_RULE_ALLOW;
11312 break;
11313 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11314 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11315 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11316 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11317 defaultRule = FIREWALL_RULE_DENY;
11318 break;
11319 default:
11320 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11321 }
11322 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11323
11324 return rule;
11325 }
11326
markchien98a6f952022-01-13 23:43:53 +080011327 @Override
11328 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11329 enforceNetworkStackOrSettingsPermission();
11330
11331 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011332 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011333 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011334 throw new IllegalStateException(e);
11335 }
11336 }
11337
markchien00a0bed2022-01-13 23:46:13 +080011338 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011339 public boolean getFirewallChainEnabled(final int chain) {
11340 enforceNetworkStackOrSettingsPermission();
11341
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011342 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011343 }
11344
11345 @Override
markchien00a0bed2022-01-13 23:46:13 +080011346 public void replaceFirewallChain(final int chain, final int[] uids) {
11347 enforceNetworkStackOrSettingsPermission();
11348
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011349 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011350 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011351}